dynamic-workflow-run-service.test.ts 370 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608
  1. /**
  2. * dwf run service 的集成测试。装配照 workflow-driver.helpers.ts 的 runDriverScript:真实脚本 →
  3. * 真实编译 / schema 合成 / validate / lowering → 沙箱子进程 → 引擎核心 → 真实 AgentRuntime
  4. * driver,只把模型换成可预测的脚本化 adapter。被测对象是 run service 本身:编译一次、
  5. * 引擎独占 createRun、run 元数据落库、actor 会话真实化、取消语义、caps 默认值、事件分页。
  6. */
  7. import {
  8. TYPED_SCRIPT,
  9. type ActorPlan,
  10. type ModelRequestLog,
  11. type HarnessOptions,
  12. type Harness,
  13. HARNESS_PARENT_SESSION,
  14. SweepableJournalStore,
  15. preloadRun,
  16. makeHarness,
  17. } from "./dynamic-workflow-run-service-fixture.js";
  18. import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
  19. import { createTestAgentRuntime } from "./helpers/test-agent-runtime.js";
  20. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  21. import { createHash } from "node:crypto";
  22. import { tmpdir } from "node:os";
  23. import { join } from "node:path";
  24. import { createInMemorySessionEventStore, createSqliteSessionStore } from "@zcode/adapters/storage";
  25. import type { DwfRunIntrospectionQueries, DwfRunLifeSpan } from "@zcode/adapters/storage";
  26. import {
  27. ESCALATE_TOOL_NAME,
  28. RESOLVE_WORKFLOW_QUESTION_TOOL_NAME,
  29. createRootTraceContext,
  30. createSessionId,
  31. createToolCallId,
  32. createTurnId,
  33. DYNAMIC_WORKFLOW_RUN_EVENT_PAYLOAD_LIMITS,
  34. LIST_WORKFLOW_RUNS_MAX_LIMIT,
  35. type CollaborationMode,
  36. type DynamicWorkflowRunDetail,
  37. type DynamicWorkflowRunListQuery,
  38. type DynamicWorkflowRunListResult,
  39. type DynamicWorkflowRunProgressPayload,
  40. type MessageWithParts,
  41. type ModelSelection,
  42. type SessionId,
  43. type ToolArtifactStorePort,
  44. type ToolArtifactWriteRequest,
  45. type WorkflowEscalatePort,
  46. } from "@zcode/contracts";
  47. import {
  48. AgentRuntime,
  49. PermissionService,
  50. builtInTools,
  51. createToolExecutor,
  52. createToolRegistry,
  53. defaultPermissionConfig,
  54. } from "@zcode/core";
  55. import {
  56. reduceWorkflowRunsState,
  57. WORKFLOW_RUN_EVENTS_PAGE_LIMITS,
  58. workflowRunsStateSchema,
  59. type WorkflowRunProgressEnvelope,
  60. type WorkflowRunsState,
  61. } from "@zcode/shared/zcode-protocol-v4";
  62. import {
  63. holeSiteId,
  64. InMemoryJournalStore,
  65. refToString,
  66. type JournalStorePort,
  67. type RunEvent,
  68. type RunStatus,
  69. type RunStopReason,
  70. } from "@zcode/dynamic-workflow";
  71. import { resolveDynamicWorkflowJournalStore } from "../src/app/dynamic-workflow-run-service.js";
  72. import {
  73. createWorkflowConcurrencyGovernor,
  74. type WorkflowConcurrencyPort,
  75. } from "../src/app/workflow-concurrency-governor.js";
  76. import { resolveWorkflowDefaultConcurrency } from "../src/app/workflow-default-concurrency.js";
  77. import { replayRunProgress } from "../src/app/dynamic-workflow-run-replay.js";
  78. import {
  79. WORKFLOW_QUOTA_RESUME_MARGIN_MS,
  80. startWorkflowQuotaAutoResume,
  81. } from "../src/app/dynamic-workflow-quota-resume.js";
  82. import { fakeFileSystemPort } from "./workflow-driver.helpers.js";
  83. import type { ExecutionPort } from "@zcode/contracts";
  84. import { mkdtempSync, readFileSync } from "node:fs";
  85. /**
  86. * 独立的 run cwd:harness 把入口文件写到 `<cwd>/.zcode/workflow-runs/<runId>.mjs` 且保留,
  87. * 用 process.cwd() 会把存档留在包目录里,并让并行测试文件互相覆写同名入口文件。
  88. */
  89. const TEST_CWD: string = mkdtempSync(join(tmpdir(), "dwf-bootstrap-test-cwd-"));
  90. // 数真实的 ts.Program 建了几次,让「编译一次」成为可断言的事实。用 importOriginal 保持
  91. // 编译本身是真的——其余用例依赖真实的 lowering 与 schema 合成。
  92. const { compiledScripts } = vi.hoisted(() => ({ compiledScripts: [] as string[] }));
  93. vi.mock("@zcode/dynamic-workflow", async (importOriginal) => {
  94. const actual = await importOriginal<typeof import("@zcode/dynamic-workflow")>();
  95. return {
  96. ...actual,
  97. createWorkflowProgram: (scriptText: string) => {
  98. compiledScripts.push(scriptText);
  99. return actual.createWorkflowProgram(scriptText);
  100. },
  101. };
  102. });
  103. const BROKEN_SCRIPT = 'const x: number = "definitely not a number";';
  104. /**
  105. * 发布一个用户面产物(docs/dynamic-workflow/authoring.md)。用 markdown 而不是 file:这条用例
  106. * 要证的是**接线**(service → launch → driver → store),而 markdown 不需要工作区里真有一个
  107. * 文件——文件那一侧的路径 / 上限 / 类型语义归 workflow-driver-artifacts.test.ts。
  108. */
  109. const ARTIFACT_SCRIPT = ['artifact.markdown("summary", "# 结论");', 'return "done";'].join("\n");
  110. function traceFor(name: string) {
  111. const sessionId = createSessionId(name);
  112. return createRootTraceContext({ sessionId, turnId: createTurnId(name) });
  113. }
  114. /**
  115. * submit 并断言被接受,回 runId。submit 的结果是判别联合(amend-resume 的三道门可以拒绝一次
  116. * 提交,见 contracts 的 DynamicWorkflowRunSubmitResult),所以「提交成功」在每个用例里都得
  117. * 先成立;把这个断言收在一处,用例正文才不必逐个写 if (!result.ok)。
  118. * 拒绝路径由 amend 那组用例直接对 service.submit 断言。
  119. */
  120. async function submitRun(
  121. harness: Harness,
  122. request: Parameters<Harness["service"]["submit"]>[0],
  123. ): Promise<string> {
  124. const result = await harness.service.submit(request);
  125. return result.runId;
  126. }
  127. /** amend 入口的成功路径(refusal 在专门的用例里断言)。 */
  128. async function amendRun(
  129. harness: Harness,
  130. request: Parameters<NonNullable<Harness["service"]["amend"]>>[0],
  131. ): Promise<{ runId: string; supersededRunId?: string }> {
  132. const result = await harness.service.amend!(request);
  133. if (!result.ok) throw new Error(`amend refused unexpectedly: ${result.reason}`);
  134. return result;
  135. }
  136. /** 等某个 run 结算(waitForTask 是端口自己的等待面,顺带被这些用例覆盖)。 */
  137. async function settle(harness: Harness, runId: string): Promise<void> {
  138. await harness.service.waitForTask(runId);
  139. }
  140. describe("dynamic workflow run service — 在飞计数与结算订阅(registry 安全边界的读面)", () => {
  141. it("submit 后 countLiveRuns 为 1;结算后归零,监听器恰好收到一次、计数已扣掉本 run", async () => {
  142. const harness = makeHarness();
  143. const notices: { runId: string; liveRunCount: number }[] = [];
  144. const unsubscribe = harness.service.subscribeRunSettled((notice) => {
  145. notices.push(notice);
  146. });
  147. expect(harness.service.countLiveRuns()).toBe(0);
  148. const runId = await submitRun(harness, {
  149. cwd: TEST_CWD,
  150. parentSessionId: createSessionId("live-count-parent"),
  151. scriptText: TYPED_SCRIPT,
  152. toolCallId: createToolCallId("live-count-call"),
  153. trace: traceFor("live-count"),
  154. });
  155. expect(harness.service.countLiveRuns()).toBe(1);
  156. expect(notices).toEqual([]);
  157. await settle(harness, runId);
  158. expect(harness.service.countLiveRuns()).toBe(0);
  159. expect(notices).toEqual([{ runId, liveRunCount: 0 }]);
  160. // 退订后再跑一个 run:不再通知,但计数照常。
  161. unsubscribe();
  162. const second = await submitRun(harness, {
  163. cwd: TEST_CWD,
  164. parentSessionId: createSessionId("live-count-parent"),
  165. scriptText: TYPED_SCRIPT,
  166. toolCallId: createToolCallId("live-count-call-2"),
  167. trace: traceFor("live-count-2"),
  168. });
  169. await settle(harness, second);
  170. expect(notices).toHaveLength(1);
  171. expect(harness.service.countLiveRuns()).toBe(0);
  172. });
  173. it("监听器抛错只记日志,不影响结算与其他监听器", async () => {
  174. const harness = makeHarness();
  175. const seen: string[] = [];
  176. harness.service.subscribeRunSettled(() => {
  177. throw new Error("listener boom");
  178. });
  179. harness.service.subscribeRunSettled((notice) => {
  180. seen.push(notice.runId);
  181. });
  182. const runId = await submitRun(harness, {
  183. cwd: TEST_CWD,
  184. parentSessionId: createSessionId("listener-throw-parent"),
  185. scriptText: TYPED_SCRIPT,
  186. toolCallId: createToolCallId("listener-throw-call"),
  187. trace: traceFor("listener-throw"),
  188. });
  189. await settle(harness, runId);
  190. expect((await harness.service.getTask(runId))?.status).toBe("completed");
  191. expect(seen).toEqual([runId]);
  192. expect(
  193. harness.logs.some(
  194. (log) =>
  195. log.level === "warn" &&
  196. log.context?.event === "dynamic_workflow.run.settled_listener_failed",
  197. ),
  198. ).toBe(true);
  199. });
  200. });
  201. /**
  202. * 常驻登记(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Engine ownership」规则一)。
  203. *
  204. * Bug 根因(2026-09-15):引擎活在会话 App 的闭包里、不进 runtime task registry,而常驻池只读
  205. * registry——一个仍在跑的 run 被读成 idle,App 被关闭(10 分钟空闲),resume 起了第二个引擎。
  206. * 登记必须落在**启动的同一同步片**,所以下面两条用例都在 await 入口 promise **之前**断言。
  207. */
  208. describe("dynamic workflow run service — 常驻登记(Engine ownership 规则一)", () => {
  209. /** 记录登记过的 promise 与它们是否已结算;后者证明登记的不是注册表条目上的占位 promise。 */
  210. function recorder(): {
  211. register: (work: Promise<unknown>) => void;
  212. settled: boolean[];
  213. works: Promise<unknown>[];
  214. } {
  215. const works: Promise<unknown>[] = [];
  216. const settled: boolean[] = [];
  217. return {
  218. settled,
  219. works,
  220. register: (work: Promise<unknown>) => {
  221. const index = works.push(work) - 1;
  222. settled[index] = false;
  223. void work.then(() => {
  224. settled[index] = true;
  225. });
  226. },
  227. };
  228. }
  229. it("submit 在同一同步片登记恰好一次,登记的 promise 随 run 结算解除", async () => {
  230. const hook = recorder();
  231. const harness = makeHarness({ registerResidencyBlockingWork: hook.register });
  232. const submitted = harness.service.submit({
  233. cwd: TEST_CWD,
  234. parentSessionId: HARNESS_PARENT_SESSION,
  235. scriptText: TYPED_SCRIPT,
  236. trace: traceFor("residency-submit"),
  237. });
  238. // submit 的 promise 尚未被 await,登记已经发生:落在这里的常驻再平衡看得见这个 run。
  239. expect(hook.works).toHaveLength(1);
  240. const runId = (await submitted).runId;
  241. // 登记的是真结算 promise,不是条目上那个同步可见的占位 Promise.resolve。
  242. expect(hook.settled[0]).toBe(false);
  243. expect(harness.service.countLiveRuns()).toBe(1);
  244. await settle(harness, runId);
  245. await hook.works[0];
  246. expect(hook.settled[0]).toBe(true);
  247. // 恰好一次:submit 只经 trackSettlement 这一个登记点。
  248. expect(hook.works).toHaveLength(1);
  249. expect(harness.journal.getRun(runId)?.status).toBe("completed");
  250. });
  251. it("resume 同样在同一同步片登记一次(登记的是新起的那条结算)", async () => {
  252. const hook = recorder();
  253. const journal = new SweepableJournalStore();
  254. const runId = "dwfrun-residency-resume";
  255. preloadRun(journal, {
  256. cwd: TEST_CWD,
  257. parentSessionId: HARNESS_PARENT_SESSION,
  258. runId,
  259. scriptText: TYPED_SCRIPT,
  260. status: "stopped",
  261. stopReason: "user",
  262. });
  263. const harness = makeHarness({
  264. journal,
  265. registerResidencyBlockingWork: hook.register,
  266. });
  267. const resumed = harness.service.resume!(runId);
  268. expect(hook.works).toHaveLength(1);
  269. expect(await resumed).toMatchObject({ ok: true, runId });
  270. expect(hook.settled[0]).toBe(false);
  271. await settle(harness, runId);
  272. await hook.works[0];
  273. expect(hook.settled[0]).toBe(true);
  274. expect(hook.works).toHaveLength(1);
  275. expect(harness.journal.getRun(runId)?.status).toBe("completed");
  276. });
  277. });
  278. describe("dynamic workflow run service — submit", () => {
  279. it("返回 runId 并把 run 跑到 completed", async () => {
  280. const harness = makeHarness();
  281. const runId = await submitRun(harness, {
  282. cwd: TEST_CWD,
  283. parentSessionId: createSessionId("submit-parent"),
  284. scriptText: TYPED_SCRIPT,
  285. toolCallId: createToolCallId("submit-call"),
  286. trace: traceFor("submit-ok"),
  287. });
  288. expect(runId).toBeTruthy();
  289. await settle(harness, runId);
  290. const snapshot = await harness.service.getTask(runId);
  291. expect(snapshot?.status).toBe("completed");
  292. // 脚本的顶层返回值就是 run 的产物(Answer.text)。
  293. expect(snapshot?.output).toBe("done");
  294. });
  295. // GUI「配置」读快照取 run 名字(launch.md「The settings turn」);快照曾不带 name,设置轮与通知退成 run id。
  296. it("快照带 run 的名字;没起名的 run 不带", async () => {
  297. const harness = makeHarness();
  298. const named = await submitRun(harness, {
  299. cwd: TEST_CWD,
  300. name: "triage",
  301. scriptText: TYPED_SCRIPT,
  302. trace: traceFor("submit-named"),
  303. });
  304. const unnamed = await submitRun(harness, {
  305. cwd: TEST_CWD,
  306. scriptText: TYPED_SCRIPT,
  307. trace: traceFor("submit-unnamed"),
  308. });
  309. await settle(harness, named);
  310. await settle(harness, unnamed);
  311. expect((await harness.service.getTask(named))?.name).toBe("triage");
  312. expect("name" in (await harness.service.getTask(unnamed))!).toBe(false);
  313. });
  314. it("快照说明引擎在不在本进程:别的进程的在飞 run 为假,终态的 run 不带", async () => {
  315. const harness = makeHarness();
  316. const runId = await submitRun(harness, {
  317. cwd: TEST_CWD,
  318. scriptText: TYPED_SCRIPT,
  319. trace: traceFor("submit-live-here"),
  320. });
  321. await settle(harness, runId);
  322. expect("liveInThisProcess" in (await harness.service.getTask(runId))!).toBe(false);
  323. preloadRun(harness.journal, {
  324. runId: "dwfrun-other-process",
  325. cwd: TEST_CWD,
  326. status: "running",
  327. parentSessionId: "sess_other",
  328. });
  329. expect((await harness.service.getTask("dwfrun-other-process"))?.liveInThisProcess).toBe(false);
  330. });
  331. it("runId 字符集安全:无 # @ /", async () => {
  332. const harness = makeHarness();
  333. const runId = await submitRun(harness, {
  334. cwd: TEST_CWD,
  335. scriptText: TYPED_SCRIPT,
  336. trace: traceFor("submit-charset"),
  337. });
  338. await settle(harness, runId);
  339. expect(runId).toMatch(/^[A-Za-z0-9._-]+$/);
  340. });
  341. // 「编译一次」:一个 ts.Program 喂站点表 / schema 合成 / lowering。三个便捷入口各建自己的
  342. // program,串起来会 typecheck 三遍——这条断言就是防止有人把链换回便捷入口。
  343. it("一次 submit 只建一个 ts.Program", async () => {
  344. const harness = makeHarness();
  345. compiledScripts.length = 0;
  346. const runId = await submitRun(harness, {
  347. cwd: TEST_CWD,
  348. scriptText: TYPED_SCRIPT,
  349. trace: traceFor("submit-compile-once"),
  350. });
  351. await settle(harness, runId);
  352. expect(compiledScripts.filter((script) => script === TYPED_SCRIPT)).toHaveLength(1);
  353. });
  354. // 引擎独占 createRun:submit 路径绝不预插 dwf_run 行,否则引擎构造翻进 resume 分支,
  355. // 静默从一份空 journal「恢复」。
  356. it("submit 不预插 dwf_run 行,run 由引擎创建", async () => {
  357. const journal = new InMemoryJournalStore();
  358. const createRun = vi.spyOn(journal, "createRun");
  359. const getRun = vi.spyOn(journal, "getRun");
  360. const harness = makeHarness({ journal });
  361. const runId = await submitRun(harness, {
  362. cwd: TEST_CWD,
  363. scriptText: TYPED_SCRIPT,
  364. trace: traceFor("submit-create-run"),
  365. });
  366. await settle(harness, runId);
  367. // createRun 恰好一次,且发生在引擎构造里——它之前那次 getRun 必须返回 undefined
  368. // (那正是引擎判断「新 run 而非 resume」的依据)。
  369. expect(createRun).toHaveBeenCalledTimes(1);
  370. const firstGetRunResult = getRun.mock.results[0];
  371. expect(firstGetRunResult?.value).toBeUndefined();
  372. });
  373. // run 元数据落库:没有这四个字段,resume 的 script_hash 校验没有比对对象。
  374. it("scriptText / scriptHash / parentSessionId / cwd 落库", async () => {
  375. const harness = makeHarness();
  376. const parentSessionId = createSessionId("meta-parent");
  377. const runId = await submitRun(harness, {
  378. cwd: "/tmp/dwf-meta",
  379. parentSessionId,
  380. scriptText: TYPED_SCRIPT,
  381. trace: traceFor("submit-meta"),
  382. });
  383. await settle(harness, runId);
  384. const record = harness.journal.getRun(runId);
  385. expect(record?.scriptText).toBe(TYPED_SCRIPT);
  386. expect(record?.parentSessionId).toBe(parentSessionId);
  387. expect(record?.cwd).toBe("/tmp/dwf-meta");
  388. // scriptHash 由调用方(本服务)算:sha256 hex over 作者原文,不是 lowered 函数体。
  389. const { createHash } = await import("node:crypto");
  390. expect(record?.scriptHash).toBe(
  391. createHash("sha256").update(TYPED_SCRIPT, "utf8").digest("hex"),
  392. );
  393. });
  394. // 防御性:脏脚本不该走到 submit(handler 只在 ok 时调),走到了就硬失败且不建 run。
  395. it("脏脚本硬失败且不建 run", async () => {
  396. const journal = new InMemoryJournalStore();
  397. const createRun = vi.spyOn(journal, "createRun");
  398. const harness = makeHarness({ journal });
  399. await expect(
  400. harness.service.submit({
  401. cwd: TEST_CWD,
  402. scriptText: BROKEN_SCRIPT,
  403. trace: traceFor("submit-broken"),
  404. }),
  405. ).rejects.toThrow(/does not typecheck/);
  406. // 一行 dwf_run 都没建:脏脚本在编译阶段就被挡下,引擎从未被构造。
  407. expect(createRun).not.toHaveBeenCalled();
  408. // actor 会话也从未开始。
  409. expect(harness.actorRuntimeInputs).toEqual([]);
  410. });
  411. it("caps 只剩并发上界;双核机器的默认并发地板为 4", async () => {
  412. const harness = makeHarness({ availableParallelism: () => 2 });
  413. const runId = await submitRun(harness, {
  414. cwd: TEST_CWD,
  415. scriptText: TYPED_SCRIPT,
  416. trace: traceFor("submit-caps"),
  417. });
  418. await settle(harness, runId);
  419. const record = harness.journal.getRun(runId);
  420. expect(record?.caps).toEqual({ maxConcurrency: 4 });
  421. });
  422. it("默认并发的硬顶为 16", async () => {
  423. const harness = makeHarness({ availableParallelism: () => 64 });
  424. const runId = await submitRun(harness, {
  425. cwd: TEST_CWD,
  426. scriptText: TYPED_SCRIPT,
  427. trace: traceFor("submit-caps-ceiling"),
  428. });
  429. await settle(harness, runId);
  430. expect(harness.journal.getRun(runId)?.caps.maxConcurrency).toBe(16);
  431. });
  432. });
  433. // ── 请求的并发上界(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)─────────────
  434. // `max_concurrency` 高于低于默认并发都照用、没有上限:缺席即默认并发。这一组把
  435. // 「请求 → 取整 → 落 dwf_run.caps_max_concurrency → 两条读面 → run-started 载荷」整条路钉住。
  436. describe("dynamic workflow run service — 请求的并发上界", () => {
  437. /** 10 核 → 默认并发 8:既高于地板 4、又低于硬顶 16。 */
  438. const TEN_CORES = () => 10;
  439. const DEFAULT_OF_TEN_CORES = 8;
  440. async function submitWithLimit(
  441. harness: Harness,
  442. name: string,
  443. maxConcurrency?: number,
  444. ): Promise<string> {
  445. const runId = await submitRun(harness, {
  446. cwd: TEST_CWD,
  447. scriptText: TYPED_SCRIPT,
  448. ...(maxConcurrency === undefined ? {} : { maxConcurrency }),
  449. trace: traceFor(name),
  450. });
  451. await settle(harness, runId);
  452. return runId;
  453. }
  454. it("请求低于默认并发 → 原样落 dwf_run.caps_max_concurrency", async () => {
  455. const harness = makeHarness({ availableParallelism: TEN_CORES });
  456. const runId = await submitWithLimit(harness, "limit-3", 3);
  457. expect(harness.journal.getRun(runId)?.caps).toEqual({ maxConcurrency: 3 });
  458. });
  459. it("请求高于默认并发 → 原样照用(没有上限:默认是起点不是天花板)", async () => {
  460. const harness = makeHarness({ availableParallelism: TEN_CORES });
  461. const runId = await submitWithLimit(harness, "limit-99", 99);
  462. expect(harness.journal.getRun(runId)?.caps.maxConcurrency).toBe(99);
  463. });
  464. it("缺席 → 默认并发", async () => {
  465. const harness = makeHarness({ availableParallelism: TEN_CORES });
  466. const runId = await submitWithLimit(harness, "limit-absent");
  467. expect(harness.journal.getRun(runId)?.caps.maxConcurrency).toBe(DEFAULT_OF_TEN_CORES);
  468. });
  469. it("0 / 负数 → 地板 1;非整数向下取整(绝不偷偷越过用户说的数)", async () => {
  470. const harness = makeHarness({ availableParallelism: TEN_CORES });
  471. const zero = await submitWithLimit(harness, "limit-zero", 0);
  472. expect(harness.journal.getRun(zero)?.caps.maxConcurrency).toBe(1);
  473. const negative = await submitWithLimit(harness, "limit-negative", -5);
  474. expect(harness.journal.getRun(negative)?.caps.maxConcurrency).toBe(1);
  475. const fractional = await submitWithLimit(harness, "limit-fractional", 3.7);
  476. expect(harness.journal.getRun(fractional)?.caps.maxConcurrency).toBe(3);
  477. });
  478. it("amend 把上界带到后继 run(前驱的值不被继承——三态归一在工具层)", async () => {
  479. // 挂住 actor:前驱没有已完结的 ask,于是预检不需要消息边界(无转录存储的装配里本就没有
  480. // 边界记账,与既有 amend 用例同款)。
  481. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  482. const predecessor = await submitRun(harness, {
  483. cwd: TEST_CWD,
  484. maxConcurrency: 2,
  485. scriptText: TYPED_SCRIPT,
  486. trace: traceFor("amend-limit-a"),
  487. });
  488. await vi.waitFor(() => {
  489. expect(harness.journal.getRun(predecessor)?.caps.maxConcurrency).toBe(2);
  490. });
  491. const amended = await amendRun(harness, {
  492. cwd: TEST_CWD,
  493. maxConcurrency: 5,
  494. predecessorRunId: predecessor,
  495. scriptText: TYPED_SCRIPT,
  496. trace: traceFor("amend-limit-b"),
  497. });
  498. await vi.waitFor(() => {
  499. expect(harness.journal.getRun(amended.runId)?.caps.maxConcurrency).toBe(5);
  500. });
  501. expect(await harness.service.cancel(amended.runId)).toBe(true);
  502. await settle(harness, amended.runId);
  503. // 同一个前驱、这次不带字段:后继跑在默认并发上(缺席 ≠ 沿用前驱的 2)。
  504. const inherited = await amendRun(harness, {
  505. cwd: TEST_CWD,
  506. predecessorRunId: predecessor,
  507. scriptText: TYPED_SCRIPT,
  508. trace: traceFor("amend-limit-c"),
  509. });
  510. await vi.waitFor(() => {
  511. expect(harness.journal.getRun(inherited.runId)?.caps.maxConcurrency).toBe(
  512. DEFAULT_OF_TEN_CORES,
  513. );
  514. });
  515. expect(await harness.service.cancel(inherited.runId)).toBe(true);
  516. await settle(harness, inherited.runId);
  517. });
  518. it("defaultConcurrency() 与默认并发的唯一实现同值(必须与缺省落库的那个数对得上)", () => {
  519. const harness = makeHarness({ availableParallelism: TEN_CORES });
  520. expect(harness.service.defaultConcurrency!()).toBe(
  521. resolveWorkflowDefaultConcurrency(TEN_CORES),
  522. );
  523. expect(harness.service.defaultConcurrency!()).toBe(DEFAULT_OF_TEN_CORES);
  524. });
  525. it("快照只在不等于默认并发时带 maxConcurrency(高于、低于都带)", async () => {
  526. const harness = makeHarness({ availableParallelism: TEN_CORES });
  527. const limited = await submitWithLimit(harness, "snapshot-limited", 2);
  528. expect(await harness.service.getTask(limited)).toMatchObject({ maxConcurrency: 2 });
  529. const raised = await submitWithLimit(harness, "snapshot-raised", 20);
  530. expect(await harness.service.getTask(raised)).toMatchObject({ maxConcurrency: 20 });
  531. // 跑在默认值上的 run 没有可说的:字段整个缺席,而不是报一个等于默认值的数。
  532. const unlimited = await submitWithLimit(harness, "snapshot-unlimited");
  533. const snapshot = await harness.service.getTask(unlimited);
  534. expect("maxConcurrency" in snapshot!).toBe(false);
  535. const explicitDefault = await submitWithLimit(
  536. harness,
  537. "snapshot-default",
  538. DEFAULT_OF_TEN_CORES,
  539. );
  540. expect("maxConcurrency" in (await harness.service.getTask(explicitDefault))!).toBe(false);
  541. });
  542. // 间隙(submit 已返回、dwf_run 行还没落)是 AmendWorkflow 的 resolveInput 最可能读到快照的
  543. // 时刻——修订一个刚起步的 run。注册表副本必须与行给出同一个答案。
  544. it("间隙里的快照与详情读注册表副本,答案与落行后一致", async () => {
  545. await withSqliteJournal(async (real) => {
  546. const hidden = new Set<string>();
  547. const journal = hideRunsFromReads(real, hidden);
  548. const harness = makeHarness({
  549. availableParallelism: TEN_CORES,
  550. hangActors: true,
  551. journal,
  552. });
  553. const runId = await submitRun(harness, {
  554. cwd: projectCwd,
  555. maxConcurrency: 2,
  556. parentSessionId: HARNESS_PARENT_SESSION,
  557. scriptText: TYPED_SCRIPT,
  558. trace: traceFor("limit-gap"),
  559. });
  560. hidden.add(runId);
  561. expect(await harness.service.getTask(runId)).toMatchObject({ maxConcurrency: 2 });
  562. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  563. maxConcurrency: 2,
  564. });
  565. hidden.delete(runId);
  566. await vi.waitFor(async () => {
  567. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  568. maxConcurrency: 2,
  569. });
  570. });
  571. await harness.service.cancel(runId);
  572. await settle(harness, runId);
  573. });
  574. });
  575. it("getRunDetail 带 maxConcurrency,列表行不带(很少设置的字段不该把每一行加宽)", async () => {
  576. await withSqliteJournal(async (journal) => {
  577. const harness = makeHarness({ availableParallelism: TEN_CORES, journal });
  578. const limited = await submitRun(harness, {
  579. cwd: projectCwd,
  580. maxConcurrency: 2,
  581. parentSessionId: HARNESS_PARENT_SESSION,
  582. scriptText: TYPED_SCRIPT,
  583. trace: traceFor("detail-limited"),
  584. });
  585. await settle(harness, limited);
  586. const unlimited = await submitRun(harness, {
  587. cwd: projectCwd,
  588. parentSessionId: HARNESS_PARENT_SESSION,
  589. scriptText: TYPED_SCRIPT,
  590. trace: traceFor("detail-unlimited"),
  591. });
  592. await settle(harness, unlimited);
  593. const introspection = introspectionOf(harness);
  594. expect(await introspection.getRunDetail(limited)).toMatchObject({ maxConcurrency: 2 });
  595. const plain = await introspection.getRunDetail(unlimited);
  596. expect("maxConcurrency" in plain!).toBe(false);
  597. const { runs } = await introspection.listRuns({ cwd: projectCwd, limit: 20 });
  598. expect(runs).toHaveLength(2);
  599. for (const row of runs) expect("maxConcurrency" in row).toBe(false);
  600. });
  601. });
  602. // 跨切片的线契约:`run-started` 载荷上的 `concurrencyCeiling` 是共享 reducer 判断
  603. // 「这个 run 有没有自己的上界」的另一半(另一半是引擎自己的 caps.maxConcurrency)。
  604. it("run-started 载荷带 concurrencyCeiling,与引擎的 caps 并列", async () => {
  605. const harness = makeHarness({ availableParallelism: TEN_CORES });
  606. const runId = await submitWithLimit(harness, "payload-ceiling", 2);
  607. const started = harness.runEvents.find(
  608. (event) => event.runId === runId && event.eventType === "run-started",
  609. );
  610. expect(started?.payload).toMatchObject({
  611. caps: { maxConcurrency: 2 },
  612. concurrencyCeiling: DEFAULT_OF_TEN_CORES,
  613. });
  614. });
  615. });
  616. // ── 就地改一个在飞 run 的上界(docs/dynamic-workflow/concurrency.md「Retuning a live run」)──
  617. // 一次只改 `max_concurrency` 的修订不铸后继:同一个 runId、不 supersede、在飞 ask 一个不丢。
  618. // 这一组钉住端口这一侧的全部可观察后果——行、注册表副本、事件(含宿主派生的默认并发)、两种拒绝、
  619. // 钳制,以及「resume 从新上界起跑」。引擎内部那半边(caps 现读、pumpAll、no-op)由
  620. // dynamic-workflow 的 engine-retune-concurrency 测试负责。
  621. describe("dynamic workflow run service — retuneConcurrency", () => {
  622. const TEN_CORES = () => 10;
  623. const DEFAULT_OF_TEN_CORES = 8;
  624. /** 起一个挂住的 run(actor 永不返回 ⇒ run 一直在飞),并等引擎把 dwf_run 行落下来。 */
  625. async function liveRun(harness: Harness, name: string, maxConcurrency?: number): Promise<string> {
  626. const runId = await submitRun(harness, {
  627. cwd: TEST_CWD,
  628. scriptText: TYPED_SCRIPT,
  629. ...(maxConcurrency === undefined ? {} : { maxConcurrency }),
  630. trace: traceFor(name),
  631. });
  632. await vi.waitFor(() => {
  633. expect(harness.journal.getRun(runId)?.caps).toBeDefined();
  634. });
  635. return runId;
  636. }
  637. function retune(harness: Harness, runId: string, maxConcurrency: number | null) {
  638. return harness.service.retuneConcurrency!({ maxConcurrency, runId });
  639. }
  640. async function stop(harness: Harness, runId: string): Promise<void> {
  641. await harness.service.cancel(runId);
  642. await settle(harness, runId);
  643. }
  644. it("在飞 run:行、注册表副本与事件三处同时挪动,同一个 runId、没有后继", async () => {
  645. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  646. const runId = await liveRun(harness, "retune-ok", 4);
  647. expect(await retune(harness, runId, 2)).toEqual({
  648. ok: true,
  649. maxConcurrency: 2,
  650. previous: 4,
  651. defaultConcurrency: DEFAULT_OF_TEN_CORES,
  652. });
  653. // resume 沿用行里的 caps,所以不落库就等于什么都没改。
  654. expect(harness.journal.getRun(runId)?.caps).toEqual({ maxConcurrency: 2 });
  655. // 注册表副本:快照优先读它,不挪就会在 retune 之后继续报提交时那个数,而
  656. // `AmendWorkflow` 的 resolveInput 正是读这张快照判「沿用什么」。
  657. expect(await harness.service.getTask(runId)).toMatchObject({ maxConcurrency: 2 });
  658. const changed = harness.runEvents.filter(
  659. (event) => event.runId === runId && event.eventType === "run-caps-changed",
  660. );
  661. expect(changed).toHaveLength(1);
  662. expect(changed[0]?.payload).toMatchObject({
  663. runId,
  664. caps: { maxConcurrency: 2 },
  665. previous: { maxConcurrency: 4 },
  666. // 宿主派生字段:读侧据它判断新上界该写下还是该清掉,与 `run-started` 同一条缝。
  667. concurrencyCeiling: DEFAULT_OF_TEN_CORES,
  668. });
  669. await stop(harness, runId);
  670. });
  671. it("同一个值 ⇒ unchanged,点名此刻生效的上界;什么都不写、什么都不发", async () => {
  672. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  673. const runId = await liveRun(harness, "retune-unchanged", 3);
  674. expect(await retune(harness, runId, 3)).toEqual({ ok: false, reason: "unchanged", current: 3 });
  675. expect(harness.journal.getRun(runId)?.caps).toEqual({ maxConcurrency: 3 });
  676. expect(
  677. harness.runEvents.filter((event) => event.eventType === "run-caps-changed"),
  678. ).toHaveLength(0);
  679. await stop(harness, runId);
  680. });
  681. it("高于默认并发照用、没有上限;等于默认时读面把字段整个撤掉", async () => {
  682. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  683. const runId = await liveRun(harness, "retune-clamp", 2);
  684. expect(await retune(harness, runId, 99)).toEqual({
  685. ok: true,
  686. maxConcurrency: 99,
  687. previous: 2,
  688. defaultConcurrency: DEFAULT_OF_TEN_CORES,
  689. });
  690. expect(await harness.service.getTask(runId)).toMatchObject({ maxConcurrency: 99 });
  691. expect(await retune(harness, runId, DEFAULT_OF_TEN_CORES)).toMatchObject({ ok: true });
  692. const snapshot = await harness.service.getTask(runId);
  693. expect("maxConcurrency" in snapshot!).toBe(false);
  694. // 地板同规:0 与负数都落到 1。
  695. expect(await retune(harness, runId, 0)).toMatchObject({ ok: true, maxConcurrency: 1 });
  696. await stop(harness, runId);
  697. });
  698. it("null = 默认并发 = 解除本 run 自己的界", async () => {
  699. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  700. const runId = await liveRun(harness, "retune-null", 2);
  701. expect(await retune(harness, runId, null)).toEqual({
  702. ok: true,
  703. maxConcurrency: DEFAULT_OF_TEN_CORES,
  704. previous: 2,
  705. defaultConcurrency: DEFAULT_OF_TEN_CORES,
  706. });
  707. expect(harness.journal.getRun(runId)?.caps.maxConcurrency).toBe(DEFAULT_OF_TEN_CORES);
  708. // 已经在默认值上,再要一次「解除」就是同一个值。
  709. expect(await retune(harness, runId, null)).toMatchObject({ ok: false, reason: "unchanged" });
  710. await stop(harness, runId);
  711. });
  712. // 治理器那一侧(docs/dynamic-workflow/concurrency.md「The governor」「The control path」):
  713. // launch 把本 run 的上界登记给治理器(抬它用过的 key 的增长上限),retune 经控制面覆盖,
  714. // launch 结算时清掉——三处与调度器、座位闸门同一刻换值。
  715. it("launch 登记上界、retune 覆盖、结算清掉:治理器上的增长上限跟着 run 走", async () => {
  716. const governor = createWorkflowConcurrencyGovernor({
  717. defaultConcurrency: DEFAULT_OF_TEN_CORES,
  718. });
  719. const calls: string[] = [];
  720. const concurrency: WorkflowConcurrencyPort = {
  721. tryAdmit: (runId, key) => governor.tryAdmit(runId, key),
  722. admit: (runId, key, signal) => governor.admit(runId, key, signal),
  723. subscribe: (runId, listener) => governor.subscribe(runId, listener),
  724. setRunBound: (runId, bound) => {
  725. calls.push(`set:${runId}:${bound}`);
  726. governor.setRunBound(runId, bound);
  727. },
  728. clearRunBound: (runId) => {
  729. calls.push(`clear:${runId}`);
  730. governor.clearRunBound(runId);
  731. },
  732. };
  733. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true, concurrency });
  734. const runId = await liveRun(harness, "retune-governor", 30);
  735. await vi.waitFor(() => {
  736. expect(calls).toContain(`set:${runId}:30`);
  737. });
  738. expect(await retune(harness, runId, 40)).toMatchObject({ ok: true, maxConcurrency: 40 });
  739. expect(calls).toContain(`set:${runId}:40`);
  740. await stop(harness, runId);
  741. await vi.waitFor(() => {
  742. expect(calls.at(-1)).toBe(`clear:${runId}`);
  743. });
  744. });
  745. it("结算之后与未知 run 都是 not_live(调用方回落到一次真正的修订)", async () => {
  746. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  747. const runId = await liveRun(harness, "retune-settled", 4);
  748. await stop(harness, runId);
  749. expect(await retune(harness, runId, 2)).toEqual({ ok: false, reason: "not_live" });
  750. expect(await retune(harness, "dwfrun-nobody", 2)).toEqual({ ok: false, reason: "not_live" });
  751. // 拒绝即零副作用:行还是停止那一刻的那一份。
  752. expect(harness.journal.getRun(runId)?.caps).toEqual({ maxConcurrency: 4 });
  753. });
  754. it("resume 从 retune 之后的上界起跑(行是 caps 的权威,条目抄的也是它)", async () => {
  755. const harness = makeHarness({ availableParallelism: TEN_CORES, hangActors: true });
  756. const runId = await liveRun(harness, "retune-resume", 4);
  757. expect(await retune(harness, runId, 2)).toMatchObject({ ok: true, maxConcurrency: 2 });
  758. await stop(harness, runId);
  759. const resumed = await harness.service.resume!(runId);
  760. expect(resumed).toMatchObject({ ok: true, runId });
  761. await vi.waitFor(() => {
  762. expect(harness.journal.getRun(runId)?.caps).toEqual({ maxConcurrency: 2 });
  763. });
  764. // 新一世的注册表条目抄的是行里那个数,所以 `previous` 说的是 retune 之后的上界。
  765. expect(await harness.service.getTask(runId)).toMatchObject({ maxConcurrency: 2 });
  766. expect(await retune(harness, runId, 5)).toMatchObject({ ok: true, previous: 2 });
  767. await stop(harness, runId);
  768. });
  769. // 同一条契约的**端到端**那一半:live 侧是 launch 的 emit 钩子铸的(toProgressPayload 的
  770. // `run-caps-changed` 分支),冷侧是 replayRunProgress 铸的。两者必须逐字节相等——live 路只给
  771. // `run-started` 拼默认并发、冷路给每条事件都拼,这个差别正是这条用例要挡住的。
  772. it("live 与冷回放为同一条 run-caps-changed 铸出逐字节相同的载荷", async () => {
  773. const journal = new SweepableJournalStore();
  774. const harness = makeHarness({
  775. availableParallelism: TEN_CORES,
  776. hangActors: true,
  777. journal,
  778. });
  779. const runId = await submitRun(harness, {
  780. cwd: TEST_CWD,
  781. maxConcurrency: 4,
  782. parentSessionId: HARNESS_PARENT_SESSION,
  783. scriptText: TYPED_SCRIPT,
  784. trace: traceFor("retune-live-vs-cold"),
  785. });
  786. await vi.waitFor(() => {
  787. expect(harness.journal.getRun(runId)?.caps).toBeDefined();
  788. });
  789. expect(await retune(harness, runId, 2)).toMatchObject({ ok: true });
  790. await stop(harness, runId);
  791. const live = harness.runEvents.find(
  792. (event) => event.runId === runId && event.eventType === "run-caps-changed",
  793. );
  794. // 冷侧:同一份 journal、新的 service(本进程没有这个 run 的条目,所以它会被回放)。
  795. const cold = makeHarness({ availableParallelism: TEN_CORES, journal });
  796. const replayed = await cold.service.replayProgressForSession!({ excludeRunIds: new Set() });
  797. const coldEvent = replayed.find(
  798. (event) => event.runId === runId && event.eventType === "run-caps-changed",
  799. );
  800. expect(live).toBeDefined();
  801. expect(coldEvent).toEqual(live);
  802. });
  803. // 冷回放的契约:同一条铸造链、同一个默认并发,所以 `run-caps-changed` 在重启前后逐字节相等。
  804. it("冷回放给 run-caps-changed 铸上同一个 concurrencyCeiling", async () => {
  805. const journal = new SweepableJournalStore();
  806. preloadRun(journal, {
  807. runId: "dwfrun-retuned",
  808. parentSessionId: HARNESS_PARENT_SESSION,
  809. scriptText: TYPED_SCRIPT,
  810. status: "stopped",
  811. stopReason: "user",
  812. caps: { maxConcurrency: 2 },
  813. });
  814. journal.appendEvent("dwfrun-retuned", {
  815. type: "run-started",
  816. caps: { maxConcurrency: 4 },
  817. } as never);
  818. journal.appendEvent("dwfrun-retuned", {
  819. type: "run-caps-changed",
  820. runId: "dwfrun-retuned",
  821. caps: { maxConcurrency: 2 },
  822. previous: { maxConcurrency: 4 },
  823. } as never);
  824. const harness = makeHarness({ availableParallelism: TEN_CORES, journal });
  825. const replayed = await harness.service.replayProgressForSession!({ excludeRunIds: new Set() });
  826. const changed = replayed.find((event) => event.eventType === "run-caps-changed");
  827. expect(changed?.payload).toEqual({
  828. runId: "dwfrun-retuned",
  829. caps: { maxConcurrency: 2 },
  830. previous: { maxConcurrency: 4 },
  831. concurrencyCeiling: DEFAULT_OF_TEN_CORES,
  832. });
  833. });
  834. });
  835. // ── 端到端:真 AmendWorkflow 工具 → 真 run service → 真引擎 → journal / 事件 ─────────────
  836. // docs/dynamic-workflow/launch.md「Changing only the parallelism of a live run」。上面那一组
  837. // 直接对 service 断言,core 那一侧的用例又把端口换成了 stub——两条缝之间没有任何东西证明它们
  838. // 真的对得上。这一组把工具执行器、resolveInput 的路由、handler、端口、引擎与 journal 串成一条。
  839. //
  840. // **哪些是真的**:工具注册表与执行器、AmendWorkflow 的 resolveInput / 权限步 / handler、
  841. // `createDynamicWorkflowRunService`、引擎与调度器、driver、journal 行与事件流、进度载荷。
  842. // **哪些是替身**:actor 的模型适配器(`hangActors`:generateText 永不 resolve,于是三个 ask
  843. // 稳定停在在飞状态),以及并发探测(固定 10 核 → 默认并发 8)。
  844. //
  845. // **这里不证停驻**:让子代理真的发出「下一个 turn step」需要一个可外部拨动的假模型,本 harness
  846. // 的脚本化 adapter 给不了那个控制点。座位闸门那一半由 workflow-driver-seat-gate.test.ts 用真
  847. // 治理器 + 真 driver 证(压低 4→1 停驻、FIFO 放行、工具侧不停驻、取消不腾座位);本组证的是
  848. // 「工具的一次调用真的把上界改到了引擎与 journal 上,而且一个在飞 ask 都没动」。
  849. describe("dynamic workflow run service — AmendWorkflow 就地 retune(端到端)", () => {
  850. const TEN_CORES = () => 10;
  851. const DEFAULT_OF_TEN_CORES = 8;
  852. /** 三个子代理同时在飞:压低上界要有「超出的那些」才说得上话。 */
  853. const THREE_PARALLEL_SCRIPT = [
  854. "interface Answer { text: string }",
  855. 'const one = agent("one");',
  856. 'const two = agent("two");',
  857. 'const three = agent("three");',
  858. "const [a, b, c] = await Promise.all([",
  859. ' one.ask<Answer>("first"),',
  860. ' two.ask<Answer>("second"),',
  861. ' three.ask<Answer>("third"),',
  862. "]);",
  863. "return `${a.text}|${b.text}|${c.text}`;",
  864. ].join("\n");
  865. interface AmendOutcome {
  866. success: boolean;
  867. message: string;
  868. output: { response: string; diagnostics?: unknown[]; retuned?: Record<string, unknown> };
  869. }
  870. it("只带 max_concurrency 的一次调用:同一个 run 被就地改低,在飞 ask 一个不停", async () => {
  871. const journal = new SweepableJournalStore();
  872. const sessionId = createSessionId("retune-e2e");
  873. const harness = makeHarness({
  874. availableParallelism: TEN_CORES,
  875. hangActors: true,
  876. journal,
  877. parentSessionId: sessionId,
  878. });
  879. const runId = await submitRun(harness, {
  880. cwd: TEST_CWD,
  881. parentSessionId: sessionId,
  882. scriptText: THREE_PARALLEL_SCRIPT,
  883. trace: traceFor("retune-e2e"),
  884. });
  885. // 三个 ask 都已派发并卡在模型请求里;run 起于默认并发(提交时没给 max_concurrency)。
  886. await vi.waitFor(() => {
  887. expect(
  888. journal
  889. .listNodes(runId, { kinds: "all", withResult: true })
  890. .filter((node) => node.status === "running"),
  891. ).toHaveLength(3);
  892. });
  893. expect(journal.getRun(runId)?.caps.maxConcurrency).toBe(DEFAULT_OF_TEN_CORES);
  894. const runsBefore = journal.listRunsByParentSession(sessionId, 50).length;
  895. // ——— 真工具执行器 ———
  896. const registry = createToolRegistry();
  897. const amendEntry = builtInTools.find((entry) => entry.metadata.name === "AmendWorkflow");
  898. expect(amendEntry).toBeDefined();
  899. registry.register(amendEntry!);
  900. const turnId = createTurnId("retune-e2e");
  901. const traceContext = createRootTraceContext({ sessionId, turnId });
  902. const permissionAsks: unknown[] = [];
  903. const executor = createToolExecutor({
  904. emitEvent: async () => {},
  905. dynamicWorkflowRunPort: harness.service,
  906. mode: "build",
  907. permissionBroker: {
  908. async requestPermission(request) {
  909. permissionAsks.push(request);
  910. return { decision: "allow" as const };
  911. },
  912. },
  913. permissionService: new PermissionService(defaultPermissionConfig),
  914. registry,
  915. sessionId,
  916. turnId,
  917. traceContext,
  918. workingDirectory: TEST_CWD,
  919. });
  920. const amend = async (maxConcurrency: number | null): Promise<AmendOutcome> => {
  921. const result = await executor.execute(
  922. {
  923. id: createToolCallId(`retune-e2e-${String(maxConcurrency)}`),
  924. input: { max_concurrency: maxConcurrency, run_id: runId },
  925. name: "AmendWorkflow",
  926. },
  927. { traceContext },
  928. );
  929. return {
  930. success: result.success,
  931. message: String(result.error?.message ?? ""),
  932. output: result.output as AmendOutcome["output"],
  933. };
  934. };
  935. // ——— 1. 压低到 1 ———
  936. const lowered = await amend(1);
  937. expect(lowered.success).toBe(true);
  938. expect(lowered.output.response).toBe(
  939. `Applied to the running run ${runId}; at most 1 subagent runs at once. ` +
  940. `Run ${runId} keeps running under it: nothing was stopped and no new run was started.`,
  941. );
  942. expect(lowered.output.retuned).toEqual({
  943. runId,
  944. maxConcurrency: 1,
  945. previous: DEFAULT_OF_TEN_CORES,
  946. defaultConcurrency: DEFAULT_OF_TEN_CORES,
  947. });
  948. // 不是一次修订:没有后台任务、没有编译产物、没有诊断。
  949. expect(lowered.output).not.toHaveProperty("backgroundTaskId");
  950. expect(lowered.output).not.toHaveProperty("status");
  951. expect(lowered.output).not.toHaveProperty("causalityGraph");
  952. expect(lowered.output.diagnostics).toEqual([]);
  953. // 本会话自己的在飞 run:不该弹确认窗(docs/dynamic-workflow/launch.md 的归属规则)。
  954. expect(permissionAsks).toEqual([]);
  955. // 同一个 run、没有后继、没有人被 supersede。
  956. expect(journal.listRunsByParentSession(sessionId, 50)).toHaveLength(runsBefore);
  957. const row = journal.getRun(runId);
  958. expect(row?.status).toBe("running");
  959. expect(row?.supersededBy).toBeUndefined();
  960. expect(row?.caps.maxConcurrency).toBe(1);
  961. expect(harness.runEvents.filter((event) => event.eventType === "run-settled")).toEqual([]);
  962. // 恰好一条 run-caps-changed,带着宿主拼上的默认并发。
  963. const changed = harness.runEvents.filter(
  964. (event) => event.runId === runId && event.eventType === "run-caps-changed",
  965. );
  966. expect(changed).toHaveLength(1);
  967. expect(changed[0]?.payload).toEqual({
  968. runId,
  969. caps: { maxConcurrency: 1 },
  970. previous: { maxConcurrency: DEFAULT_OF_TEN_CORES },
  971. concurrencyCeiling: DEFAULT_OF_TEN_CORES,
  972. });
  973. // 快照立刻报新值(`AmendWorkflow` 的 resolveInput 判「沿用什么」读的就是它)。详情面与
  974. // `GetWorkflowRun` 读的是同一个 `runConcurrencyField`,取数来自下面断言的那一行 caps;
  975. // 那条读面需要带内省查询的 journal,由本文件「getRunDetail 带 maxConcurrency」一组覆盖。
  976. expect(await harness.service.getTask(runId)).toMatchObject({ maxConcurrency: 1 });
  977. // 在飞的三个 ask 一个都没被停:行还是 running,一条 node-settled 都没有。
  978. expect(
  979. journal
  980. .listNodes(runId, { kinds: "all", withResult: true })
  981. .filter((node) => node.status === "running"),
  982. ).toHaveLength(3);
  983. expect(
  984. harness.runEvents.filter(
  985. (event) => event.runId === runId && event.eventType === "node-settled",
  986. ),
  987. ).toEqual([]);
  988. // ——— 2. 同一个值再来一次 ———
  989. const again = await amend(1);
  990. expect(again.success).toBe(false);
  991. expect(again.message.startsWith("workflow_retune_unchanged:")).toBe(true);
  992. expect(again.message).toContain(runId);
  993. // 拒绝即零副作用:行没动,也没有第二条事件。
  994. expect(journal.getRun(runId)?.caps.maxConcurrency).toBe(1);
  995. expect(
  996. harness.runEvents.filter(
  997. (event) => event.runId === runId && event.eventType === "run-caps-changed",
  998. ),
  999. ).toHaveLength(1);
  1000. // ——— 3. null 回到默认并发 ———
  1001. const raised = await amend(null);
  1002. expect(raised.success).toBe(true);
  1003. expect(raised.output.response).toBe(
  1004. `Applied to the running run ${runId}; at most ${DEFAULT_OF_TEN_CORES} subagents run at once ` +
  1005. `(the default). ` +
  1006. `Run ${runId} keeps running under it: nothing was stopped and no new run was started.`,
  1007. );
  1008. expect(journal.getRun(runId)?.caps.maxConcurrency).toBe(DEFAULT_OF_TEN_CORES);
  1009. // 回到默认并发 ⇒ 读面把字段整个撤掉(「无则缺席」)。
  1010. const snapshot = await harness.service.getTask(runId);
  1011. expect("maxConcurrency" in snapshot!).toBe(false);
  1012. expect(
  1013. harness.runEvents.filter(
  1014. (event) => event.runId === runId && event.eventType === "run-caps-changed",
  1015. ),
  1016. ).toHaveLength(2);
  1017. // 三次调用之后 run 仍然健康、仍归本 service 所有:照常停得下来,落成可恢复的 stopped(user)。
  1018. expect(
  1019. journal
  1020. .listNodes(runId, { kinds: "all", withResult: true })
  1021. .filter((node) => node.status === "running"),
  1022. ).toHaveLength(3);
  1023. expect(await harness.service.cancel(runId)).toBe(true);
  1024. await settle(harness, runId);
  1025. expect(journal.getRun(runId)).toMatchObject({ status: "stopped", stopReason: "user" });
  1026. expect(journal.listRunsByParentSession(sessionId, 50)).toHaveLength(runsBefore);
  1027. });
  1028. });
  1029. // ── 本 run 的子代理模型(docs/dynamic-workflow/launch.md)─────────────────────────────
  1030. // `subagent_model` 只描述**子代理**跑在哪个模型上,主代理照旧在会话模型上。这一组把
  1031. // 「请求 → 归一成规范串 → 记进 journal 事件 run-launched → 两条读面 → run-started 载荷 →
  1032. // actor runtime 工厂」整条路钉住。缺席即子代理跑在会话模型上,且每一处的键都真的不出现。
  1033. //
  1034. // 落点是**事件而不是列**(用户裁决不做迁移):与发起锚点、阶段表同住 `run-launched`,
  1035. // 只在建 run 那一世写一次,宿主从事件头读回。
  1036. describe("dynamic workflow run service — 本 run 的子代理模型", () => {
  1037. /** 带档位的选择:`$level` 是选择的一部分,规范串里必须带着它走完全程。 */
  1038. const FLASH: ModelSelection = {
  1039. providerId: "zhipu",
  1040. modelId: "glm-5.3-flash",
  1041. options: { reasoningLevel: "high" },
  1042. };
  1043. const FLASH_CANONICAL = "zhipu/glm-5.3-flash$high";
  1044. /** 不带档位的选择:规范串因此只有两段。 */
  1045. const HAIKU: ModelSelection = { providerId: "anthropic", modelId: "haiku" };
  1046. /** 本 run 的 `run-launched` 事件:子代理模型就住在这里(dwf_run 上没有这一列)。 */
  1047. const launchedOf = (harness: Harness, runId: string): RunEvent | undefined =>
  1048. harness.journal
  1049. .listEvents(runId, { types: "all", reportItems: "all" })
  1050. .map((stored) => stored.event)
  1051. .find((event) => event.type === "run-launched");
  1052. const subagentModelOf = (harness: Harness, runId: string): string | undefined => {
  1053. const launched = launchedOf(harness, runId);
  1054. return launched?.type === "run-launched" ? launched.subagentModel : undefined;
  1055. };
  1056. it("submit 把规范 picker 串记进 run-launched(含 reasoning 档位),行上没有这条事实", async () => {
  1057. const harness = makeHarness();
  1058. const runId = await submitRun(harness, {
  1059. cwd: TEST_CWD,
  1060. scriptText: TYPED_SCRIPT,
  1061. subagentModel: FLASH,
  1062. trace: traceFor("subagent-model-submit"),
  1063. });
  1064. await settle(harness, runId);
  1065. expect(subagentModelOf(harness, runId)).toBe(FLASH_CANONICAL);
  1066. // 零 SQL:记录行上没有这条事实,读侧一律走事件(用户裁决不做迁移)。
  1067. expect("subagentModel" in harness.journal.getRun(runId)!).toBe(false);
  1068. });
  1069. it("没有档位的选择记成两段;不设即整个键缺席(不是 undefined)", async () => {
  1070. const harness = makeHarness();
  1071. const levelled = await submitRun(harness, {
  1072. cwd: TEST_CWD,
  1073. scriptText: TYPED_SCRIPT,
  1074. subagentModel: HAIKU,
  1075. trace: traceFor("subagent-model-two-part"),
  1076. });
  1077. await settle(harness, levelled);
  1078. expect(subagentModelOf(harness, levelled)).toBe("anthropic/haiku");
  1079. const plain = await submitRun(harness, {
  1080. cwd: TEST_CWD,
  1081. scriptText: TYPED_SCRIPT,
  1082. trace: traceFor("subagent-model-absent"),
  1083. });
  1084. await settle(harness, plain);
  1085. // 键缺席而不是 `undefined`:读侧据「在不在场」判断这个 run 有没有设过子代理模型。
  1086. expect("subagentModel" in launchedOf(harness, plain)!).toBe(false);
  1087. });
  1088. it("快照与详情给出同一个规范串;不设时两条读面都不带这个键", async () => {
  1089. await withSqliteJournal(async (journal) => {
  1090. const harness = makeHarness({ journal });
  1091. const chosen = await submitRun(harness, {
  1092. cwd: projectCwd,
  1093. parentSessionId: HARNESS_PARENT_SESSION,
  1094. scriptText: TYPED_SCRIPT,
  1095. subagentModel: FLASH,
  1096. trace: traceFor("subagent-model-read-set"),
  1097. });
  1098. await settle(harness, chosen);
  1099. const plain = await submitRun(harness, {
  1100. cwd: projectCwd,
  1101. parentSessionId: HARNESS_PARENT_SESSION,
  1102. scriptText: TYPED_SCRIPT,
  1103. trace: traceFor("subagent-model-read-absent"),
  1104. });
  1105. await settle(harness, plain);
  1106. const introspection = introspectionOf(harness);
  1107. expect(await harness.service.getTask(chosen)).toMatchObject({
  1108. subagentModel: FLASH_CANONICAL,
  1109. });
  1110. expect(await introspection.getRunDetail(chosen)).toMatchObject({
  1111. subagentModel: FLASH_CANONICAL,
  1112. });
  1113. const snapshot = await harness.service.getTask(plain);
  1114. expect("subagentModel" in snapshot!).toBe(false);
  1115. const detail = await introspection.getRunDetail(plain);
  1116. expect("subagentModel" in detail!).toBe(false);
  1117. // 列表行不带:与并发上界同规——很少设置的字段不该把枚举面的每一行都加宽。
  1118. const { runs } = await introspection.listRuns({ cwd: projectCwd, limit: 20 });
  1119. expect(runs).toHaveLength(2);
  1120. for (const row of runs) expect("subagentModel" in row).toBe(false);
  1121. // 重启(新服务、空注册表、同一个 journal):内存副本没有了,两条读面只能从
  1122. // `run-launched` 事件读回——这条断言就是「零 SQL 也能冷读」的证据。
  1123. const cold = makeHarness({ journal });
  1124. const coldIntrospection = introspectionOf(cold);
  1125. expect(await cold.service.getTask(chosen)).toMatchObject({
  1126. subagentModel: FLASH_CANONICAL,
  1127. });
  1128. expect(await coldIntrospection.getRunDetail(chosen)).toMatchObject({
  1129. subagentModel: FLASH_CANONICAL,
  1130. });
  1131. expect("subagentModel" in (await cold.service.getTask(plain))!).toBe(false);
  1132. expect("subagentModel" in (await coldIntrospection.getRunDetail(plain))!).toBe(false);
  1133. });
  1134. });
  1135. // 间隙(submit 已返回、dwf_run 行还没落):`AmendWorkflow` 的 resolveInput 读快照判「沿用
  1136. // 什么」,而修订一个刚起步的 run 恰好落在这里。注册表副本必须与落行后同一个答案。
  1137. it("间隙里的快照与详情读注册表副本,答案与落行后一致", async () => {
  1138. await withSqliteJournal(async (real) => {
  1139. const hidden = new Set<string>();
  1140. const journal = hideRunsFromReads(real, hidden);
  1141. const harness = makeHarness({ hangActors: true, journal });
  1142. const runId = await submitRun(harness, {
  1143. cwd: projectCwd,
  1144. parentSessionId: HARNESS_PARENT_SESSION,
  1145. scriptText: TYPED_SCRIPT,
  1146. subagentModel: FLASH,
  1147. trace: traceFor("subagent-model-gap"),
  1148. });
  1149. hidden.add(runId);
  1150. expect(await harness.service.getTask(runId)).toMatchObject({
  1151. subagentModel: FLASH_CANONICAL,
  1152. });
  1153. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  1154. subagentModel: FLASH_CANONICAL,
  1155. });
  1156. hidden.delete(runId);
  1157. await vi.waitFor(async () => {
  1158. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  1159. subagentModel: FLASH_CANONICAL,
  1160. });
  1161. });
  1162. await harness.service.cancel(runId);
  1163. await settle(harness, runId);
  1164. });
  1165. });
  1166. it("amend 用请求里的值,绝不继承前驱的(三态归一在工具层)", async () => {
  1167. const harness = makeHarness({ hangActors: true });
  1168. const predecessor = await submitRun(harness, {
  1169. cwd: TEST_CWD,
  1170. scriptText: TYPED_SCRIPT,
  1171. subagentModel: FLASH,
  1172. trace: traceFor("subagent-model-amend-a"),
  1173. });
  1174. await vi.waitFor(() => {
  1175. expect(subagentModelOf(harness, predecessor)).toBe(FLASH_CANONICAL);
  1176. });
  1177. // 换一个模型:后继落新值。
  1178. const amended = await amendRun(harness, {
  1179. cwd: TEST_CWD,
  1180. predecessorRunId: predecessor,
  1181. scriptText: TYPED_SCRIPT,
  1182. subagentModel: HAIKU,
  1183. trace: traceFor("subagent-model-amend-b"),
  1184. });
  1185. await vi.waitFor(() => {
  1186. expect(subagentModelOf(harness, amended.runId)).toBe("anthropic/haiku");
  1187. });
  1188. expect(await harness.service.cancel(amended.runId)).toBe(true);
  1189. await settle(harness, amended.runId);
  1190. // 同一个前驱、这次不带字段:后继回到会话模型(缺席 ≠ 沿用前驱的 FLASH)。端口若在这里
  1191. // 继承一次,工具面的 `null`(「回到会话模型」)就永远到不了落库这一步。
  1192. const cleared = await amendRun(harness, {
  1193. cwd: TEST_CWD,
  1194. predecessorRunId: predecessor,
  1195. scriptText: TYPED_SCRIPT,
  1196. trace: traceFor("subagent-model-amend-c"),
  1197. });
  1198. await vi.waitFor(() => {
  1199. expect(launchedOf(harness, cleared.runId)).toBeDefined();
  1200. });
  1201. expect("subagentModel" in launchedOf(harness, cleared.runId)!).toBe(false);
  1202. expect(await harness.service.cancel(cleared.runId)).toBe(true);
  1203. await settle(harness, cleared.runId);
  1204. });
  1205. it("run-started 载荷带 subagentModel,与 concurrencyCeiling 并列;不设即不出", async () => {
  1206. const harness = makeHarness();
  1207. const runId = await submitRun(harness, {
  1208. cwd: TEST_CWD,
  1209. scriptText: TYPED_SCRIPT,
  1210. subagentModel: FLASH,
  1211. trace: traceFor("subagent-model-payload"),
  1212. });
  1213. await settle(harness, runId);
  1214. const started = harness.runEvents.find(
  1215. (event) => event.runId === runId && event.eventType === "run-started",
  1216. );
  1217. expect(started?.payload).toMatchObject({ subagentModel: FLASH_CANONICAL });
  1218. const plain = await submitRun(harness, {
  1219. cwd: TEST_CWD,
  1220. scriptText: TYPED_SCRIPT,
  1221. trace: traceFor("subagent-model-payload-absent"),
  1222. });
  1223. await settle(harness, plain);
  1224. const plainStarted = harness.runEvents.find(
  1225. (event) => event.runId === plain && event.eventType === "run-started",
  1226. );
  1227. expect("subagentModel" in plainStarted!.payload).toBe(false);
  1228. });
  1229. it("actor runtime 工厂拿到解析回来的整条选择(含档位),不设时缺席", async () => {
  1230. const harness = makeHarness();
  1231. const runId = await submitRun(harness, {
  1232. cwd: TEST_CWD,
  1233. scriptText: TYPED_SCRIPT,
  1234. subagentModel: FLASH,
  1235. trace: traceFor("subagent-model-factory"),
  1236. });
  1237. await settle(harness, runId);
  1238. // 工厂收的是结构化选择而不是那个串:pin 只记身份两段,档位只能从这里下去。
  1239. expect(harness.actorRuntimeInputs.at(-1)?.runSubagentModel).toEqual(FLASH);
  1240. const plain = await submitRun(harness, {
  1241. cwd: TEST_CWD,
  1242. scriptText: TYPED_SCRIPT,
  1243. trace: traceFor("subagent-model-factory-absent"),
  1244. });
  1245. await settle(harness, plain);
  1246. expect("runSubagentModel" in harness.actorRuntimeInputs.at(-1)!).toBe(false);
  1247. });
  1248. it("resume 从 run-launched 事件读回选择,交给工厂并抄进注册表条目", async () => {
  1249. // resume 沿用记下来的那一份,与 caps / args 同一条纪律:一次 run 的身份包含它跑在哪个模型上。
  1250. const harness = makeHarness({ hangActors: true });
  1251. const runId = await submitRun(harness, {
  1252. cwd: TEST_CWD,
  1253. scriptText: TYPED_SCRIPT,
  1254. subagentModel: FLASH,
  1255. trace: traceFor("subagent-model-resume"),
  1256. });
  1257. await vi.waitFor(() => {
  1258. expect(harness.actorRuntimeInputs).toHaveLength(1);
  1259. });
  1260. expect(await harness.service.cancel(runId)).toBe(true);
  1261. await settle(harness, runId);
  1262. const resumed = await harness.service.resume!(runId);
  1263. expect(resumed).toMatchObject({ ok: true, runId });
  1264. await vi.waitFor(() => {
  1265. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(1);
  1266. });
  1267. // 续跑那一世的工厂输入:选择整条回来了(档位没掉),而 resume 入口根本没有这个形参。
  1268. expect(harness.actorRuntimeInputs.at(-1)?.runSubagentModel).toEqual(FLASH);
  1269. // 续跑那一世的条目也带上了这份选择,于是读面只剩一条规则:有条目就读条目,只有冷行才
  1270. // 去扫事件头。spy 是这条规则的证据——快照答得出模型,却一次 listEvents 都没发。
  1271. const listEvents = vi.spyOn(harness.journal, "listEvents");
  1272. expect(await harness.service.getTask(runId)).toMatchObject({
  1273. subagentModel: FLASH_CANONICAL,
  1274. });
  1275. expect(listEvents).not.toHaveBeenCalled();
  1276. listEvents.mockRestore();
  1277. expect(await harness.service.cancel(runId)).toBe(true);
  1278. await settle(harness, runId);
  1279. });
  1280. it("amend 带 subagentModel:run 选择压过前驱承袭的 pin,新 run 的 resolved_model 记的是新选择", async () => {
  1281. // 回归用例(2026-09-17 testfield,dwf-assets/workflow-subagent-model-precedence-brief.md):
  1282. // 前驱的子代理跑在 pin 上;AmendWorkflow 带 `subagent_model` 换模型,run-launched 记下新选择、
  1283. // 确认窗说「Subagents run on Z」,而 driver 仍按 pin 造会话——每个有 live 工作的续跑子代理都
  1284. // 跑错模型。省略即继承,显式值即替换:pin 只守没有 run 选择时的隐式缺省。
  1285. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-model-"));
  1286. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  1287. const journal = new SweepableJournalStore();
  1288. try {
  1289. // 前驱:worker 两问都 live,会话与边界真的落库——修订时第二问分歧,第一问作为已完成前缀
  1290. // 让导入表带上转录种子,pin 就是随种子承袭过来的(seq 0 就分歧的 actor 没有前缀、没有种子)。
  1291. const before = makeHarness({
  1292. actorScripts: {
  1293. "actor#1@1": [
  1294. { kind: "submit", result: { text: "one" } },
  1295. { kind: "submit", result: { text: "two" } },
  1296. ],
  1297. },
  1298. journal,
  1299. sessionStore: store as never,
  1300. });
  1301. const runA = await submitRun(before, {
  1302. cwd: TEST_CWD,
  1303. scriptText: amendScript("second question"),
  1304. trace: traceFor("subagent-model-over-pin-a"),
  1305. });
  1306. await settle(before, runA);
  1307. // 前驱 worker 跑在会话模型上。把它的记录改成哨兵,好让 pin ≠ 会话模型 ≠ 本次选择——
  1308. // 三个来源两两不同,「谁赢」才是可断言的事实。
  1309. const workerRow = journal.getActor(runA, "actor#1", 1)!;
  1310. expect(workerRow.resolvedModel).toBe("test/default-runtime-model");
  1311. journal.putActor({ ...workerRow, resolvedModel: "pinned/from-predecessor" });
  1312. // 修订:只改第二问,并给出新的子代理模型。
  1313. const after = makeHarness({
  1314. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "revised" } }] },
  1315. journal,
  1316. sessionStore: store as never,
  1317. });
  1318. const amended = await amendRun(after, {
  1319. cwd: TEST_CWD,
  1320. predecessorRunId: runA,
  1321. scriptText: amendScript("second question, revised"),
  1322. subagentModel: HAIKU,
  1323. trace: traceFor("subagent-model-over-pin-b"),
  1324. });
  1325. await settle(after, amended.runId);
  1326. expect((await after.service.getTask(amended.runId))?.output).toBe("one|revised|0");
  1327. // worker 只在分歧那一问建了一次会话,工厂同时拿到承袭的 pin 与本 run 的选择——两者都在场,
  1328. // 断言的才是优先级而不是某一方缺席。
  1329. expect(after.actorRuntimeInputs).toHaveLength(1);
  1330. expect(after.actorRuntimeInputs[0]).toMatchObject({
  1331. pinnedModel: "pinned/from-predecessor",
  1332. runSubagentModel: HAIKU,
  1333. });
  1334. // 回归点:新 run 自己的记录写的是 run 选择(修复前这里读到 pin)。
  1335. expect(journal.getActor(amended.runId, "actor#1", 1)?.resolvedModel).toBe("anthropic/haiku");
  1336. // 前驱的记录一个字节不动:lineage 因此保留「换过模型」这段历史,没有什么是静默的。
  1337. expect(journal.getActor(runA, "actor#1", 1)?.resolvedModel).toBe("pinned/from-predecessor");
  1338. } finally {
  1339. store.close();
  1340. await rm(tempRoot, { force: true, recursive: true });
  1341. }
  1342. });
  1343. });
  1344. // ── 脚本点名的模型(docs/dynamic-workflow/launch.md「Models the script names」)─────────────
  1345. // persona 的 `model` 名字 → run-launched 上的绑定表 → 建会话时查表、压过 run 的子代理模型 →
  1346. // dwf_actor.resolved_model 记下实际用上的那一个。resume 从同一条事件读回同一张表。
  1347. describe("dynamic workflow run service — 脚本点名的模型", () => {
  1348. const LIGHT: ModelSelection = { providerId: "zhipu", modelId: "GLM-5.3-Flash" };
  1349. const STRONG: ModelSelection = {
  1350. providerId: "zhipu",
  1351. modelId: "GLM-5.3",
  1352. options: { reasoningLevel: "high" },
  1353. };
  1354. const RUN_DEFAULT: ModelSelection = { providerId: "anthropic", modelId: "haiku" };
  1355. const ROUTED_SCRIPT = [
  1356. "interface Answer { text: string }",
  1357. 'const MODELS = { light: model("GLM-5.3-Flash"), strong: model("GLM-5.3$high") };',
  1358. 'const judge = await agent("评审员", { model: MODELS.light }).ask<Answer>("judge");',
  1359. 'const writer = await agent("写手", { model: MODELS.strong }).ask<Answer>("write");',
  1360. 'const plain = await agent("旁观者").ask<Answer>("watch");',
  1361. 'return [judge.text, writer.text, plain.text].join(",");',
  1362. ].join("\n");
  1363. const launchedOf = (harness: Harness, runId: string): RunEvent | undefined =>
  1364. harness.journal
  1365. .listEvents(runId, { types: "all", reportItems: "all" })
  1366. .map((stored) => stored.event)
  1367. .find((event) => event.type === "run-launched");
  1368. it("每个子代理跑在自己 persona 点名的模型上,压过 run 的子代理模型;没点名的照旧跑 run 的", async () => {
  1369. const harness = makeHarness();
  1370. const runId = await submitRun(harness, {
  1371. cwd: TEST_CWD,
  1372. scriptText: ROUTED_SCRIPT,
  1373. subagentModel: RUN_DEFAULT,
  1374. modelBindings: { "GLM-5.3-Flash": LIGHT, "GLM-5.3$high": STRONG },
  1375. trace: traceFor("script-models-routed"),
  1376. });
  1377. await settle(harness, runId);
  1378. expect((await harness.service.getTask(runId))?.runStatus).toBe("completed");
  1379. const launched = launchedOf(harness, runId);
  1380. expect(launched).toMatchObject({
  1381. modelBindings: {
  1382. "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash",
  1383. "GLM-5.3$high": "zhipu/GLM-5.3$high",
  1384. },
  1385. });
  1386. // 工厂收到的是整条选择(档位在内),没点名模型的子代理没有这一键。
  1387. const byActor = new Map(
  1388. harness.actorRuntimeInputs.map((input) => [refToString(input.actor), input]),
  1389. );
  1390. expect(byActor.get("actor#1@1")?.actorModel).toEqual(LIGHT);
  1391. expect(byActor.get("actor#2@1")?.actorModel).toEqual(STRONG);
  1392. expect("actorModel" in byActor.get("actor#3@1")!).toBe(false);
  1393. // 落库的是 runtime 实际拿到的那一个:persona 的模型压过 run 的子代理模型。
  1394. expect(harness.journal.getActor(runId, "actor#1", 1)?.resolvedModel).toBe(
  1395. "zhipu/GLM-5.3-Flash",
  1396. );
  1397. expect(harness.journal.getActor(runId, "actor#2", 1)?.resolvedModel).toBe("zhipu/GLM-5.3");
  1398. expect(harness.journal.getActor(runId, "actor#3", 1)?.resolvedModel).toBe("anthropic/haiku");
  1399. // persona 里记的是脚本逐字写下的名字(ModelRef 在 lowering 里已抹成名字)。
  1400. expect(harness.journal.getActor(runId, "actor#2", 1)?.persona).toMatchObject({
  1401. model: "GLM-5.3$high",
  1402. });
  1403. });
  1404. it("actor-created 载荷派生出子代理的规范模型串;没点名模型的不带", async () => {
  1405. const harness = makeHarness();
  1406. const runId = await submitRun(harness, {
  1407. cwd: TEST_CWD,
  1408. scriptText: ROUTED_SCRIPT,
  1409. modelBindings: { "GLM-5.3-Flash": LIGHT, "GLM-5.3$high": STRONG },
  1410. trace: traceFor("script-models-payload"),
  1411. });
  1412. await settle(harness, runId);
  1413. const created = harness.runEvents.filter(
  1414. (event) => event.runId === runId && event.eventType === "actor-created",
  1415. );
  1416. expect(created.map((event) => event.payload.model)).toEqual([
  1417. "zhipu/GLM-5.3-Flash",
  1418. "zhipu/GLM-5.3$high",
  1419. undefined,
  1420. ]);
  1421. expect("model" in created[2]!.payload).toBe(false);
  1422. // 派发重复出生事实:引擎带 persona 的名字(actorPersonaModel),宿主派生规范串(actorModel),
  1423. // 读面据它把派发时收回表的子代理连模型一起建出来。
  1424. const dispatched = harness.runEvents.filter(
  1425. (event) =>
  1426. event.runId === runId &&
  1427. event.eventType === "node-dispatched" &&
  1428. event.payload.kind === "ask",
  1429. );
  1430. expect(
  1431. dispatched.map((event) => [event.payload.actorPersonaModel, event.payload.actorModel]),
  1432. ).toEqual([
  1433. ["GLM-5.3-Flash", "zhipu/GLM-5.3-Flash"],
  1434. ["GLM-5.3$high", "zhipu/GLM-5.3$high"],
  1435. [undefined, undefined],
  1436. ]);
  1437. });
  1438. it("绑定表里没有的名字(只有绕过 9010 的断言做得到)让那一问以 DriverError 失败,不退回别的模型", async () => {
  1439. const harness = makeHarness();
  1440. const runId = await submitRun(harness, {
  1441. cwd: TEST_CWD,
  1442. scriptText: [
  1443. "interface Answer { text: string }",
  1444. 'const name = "GLM-9" as unknown as ModelRef;',
  1445. 'const a = await agent("评审员", { model: name }).ask<Answer>("judge");',
  1446. "return a.text;",
  1447. ].join("\n"),
  1448. subagentModel: RUN_DEFAULT,
  1449. trace: traceFor("script-models-unbound"),
  1450. });
  1451. await settle(harness, runId);
  1452. const snapshot = await harness.service.getTask(runId);
  1453. expect(snapshot?.runStatus).toBe("errored");
  1454. expect(JSON.stringify(snapshot)).toContain('\\"GLM-9\\"');
  1455. expect(harness.actorRuntimeInputs).toHaveLength(0);
  1456. });
  1457. const TABLE = { "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash", "GLM-5.3$high": "zhipu/GLM-5.3$high" };
  1458. it("快照与详情带出绑定表:热路径读条目,冷行扫事件头", async () => {
  1459. await withSqliteJournal(async (journal) => {
  1460. const harness = makeHarness({ journal });
  1461. const runId = await submitRun(harness, {
  1462. cwd: projectCwd,
  1463. parentSessionId: HARNESS_PARENT_SESSION,
  1464. scriptText: ROUTED_SCRIPT,
  1465. modelBindings: { "GLM-5.3-Flash": LIGHT, "GLM-5.3$high": STRONG },
  1466. trace: traceFor("script-models-read"),
  1467. });
  1468. await settle(harness, runId);
  1469. expect(await harness.service.getTask(runId)).toMatchObject({ modelBindings: TABLE });
  1470. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  1471. modelBindings: TABLE,
  1472. });
  1473. // 冷行(另一个进程,没有条目):从 run-launched 读回同一张表。
  1474. const cold = makeHarness({ journal });
  1475. expect(await cold.service.getTask(runId)).toMatchObject({ modelBindings: TABLE });
  1476. expect(await introspectionOf(cold).getRunDetail(runId)).toMatchObject({
  1477. modelBindings: TABLE,
  1478. });
  1479. });
  1480. });
  1481. it("resume 从 run-launched 读回同一张表交给工厂,并抄进注册表条目", async () => {
  1482. const harness = makeHarness({ hangActors: true });
  1483. const runId = await submitRun(harness, {
  1484. cwd: TEST_CWD,
  1485. scriptText: ROUTED_SCRIPT,
  1486. modelBindings: { "GLM-5.3-Flash": LIGHT, "GLM-5.3$high": STRONG },
  1487. trace: traceFor("script-models-resume"),
  1488. });
  1489. await vi.waitFor(() => {
  1490. expect(harness.actorRuntimeInputs).toHaveLength(1);
  1491. });
  1492. expect(await harness.service.cancel(runId)).toBe(true);
  1493. await settle(harness, runId);
  1494. const resumed = await harness.service.resume!(runId);
  1495. expect(resumed).toMatchObject({ ok: true, runId });
  1496. await vi.waitFor(() => {
  1497. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(1);
  1498. });
  1499. expect(harness.actorRuntimeInputs.at(-1)?.actorModel).toEqual(LIGHT);
  1500. expect(await harness.service.getTask(runId)).toMatchObject({ modelBindings: TABLE });
  1501. expect(await harness.service.cancel(runId)).toBe(true);
  1502. await settle(harness, runId);
  1503. });
  1504. it("不点名模型的 run:事件、快照、载荷与工厂输入里都没有这些键", async () => {
  1505. const harness = makeHarness();
  1506. const runId = await submitRun(harness, {
  1507. cwd: TEST_CWD,
  1508. scriptText: TYPED_SCRIPT,
  1509. trace: traceFor("script-models-absent"),
  1510. });
  1511. await settle(harness, runId);
  1512. expect("modelBindings" in launchedOf(harness, runId)!).toBe(false);
  1513. expect("modelBindings" in (await harness.service.getTask(runId))!).toBe(false);
  1514. expect("actorModel" in harness.actorRuntimeInputs.at(-1)!).toBe(false);
  1515. });
  1516. });
  1517. // ── 本 run 子代理的权限模式(docs/dynamic-workflow/launch.md「Permissions inside a run」)──
  1518. // 建 run 那一世把发起会话的权限模式记进 `run-launched.subagentPermissionMode`,resume 从同一条
  1519. // 事件读回;会话此后怎么换模式都不改变这个 run。plan 不带进 run。
  1520. describe("dynamic workflow run service — 本 run 子代理的权限模式", () => {
  1521. const launchedOf = (harness: Harness, runId: string): RunEvent | undefined =>
  1522. harness.journal
  1523. .listEvents(runId, { types: "all", reportItems: "all" })
  1524. .map((stored) => stored.event)
  1525. .find((event) => event.type === "run-launched");
  1526. it("发起会话的模式原样记下并交给 actor 工厂;旧 plan 值记为 build", async () => {
  1527. let mode: CollaborationMode = "guarded";
  1528. const harness = makeHarness({ permissionMode: () => mode });
  1529. const cases: ReadonlyArray<readonly [CollaborationMode, string]> = [
  1530. ["guarded", "guarded"],
  1531. ["build", "build"],
  1532. ["edit", "edit"],
  1533. ["yolo", "yolo"],
  1534. ["auto", "auto"],
  1535. ["plan", "build"],
  1536. ];
  1537. for (const [sessionMode, recorded] of cases) {
  1538. mode = sessionMode;
  1539. const runId = await submitRun(harness, {
  1540. cwd: TEST_CWD,
  1541. scriptText: TYPED_SCRIPT,
  1542. trace: traceFor(`permission-mode-${sessionMode}`),
  1543. });
  1544. await settle(harness, runId);
  1545. expect(launchedOf(harness, runId)).toMatchObject({ subagentPermissionMode: recorded });
  1546. expect(harness.actorRuntimeInputs.at(-1)?.subagentPermissionMode).toBe(recorded);
  1547. // 零 SQL:记录行上没有这条事实。
  1548. expect("subagentPermissionMode" in harness.journal.getRun(runId)!).toBe(false);
  1549. }
  1550. });
  1551. it("没接模式读取的宿主(CLI、测试装配)照旧 YOLO:键缺席", async () => {
  1552. const harness = makeHarness();
  1553. const runId = await submitRun(harness, {
  1554. cwd: TEST_CWD,
  1555. scriptText: TYPED_SCRIPT,
  1556. trace: traceFor("permission-mode-unwired"),
  1557. });
  1558. await settle(harness, runId);
  1559. expect("subagentPermissionMode" in launchedOf(harness, runId)!).toBe(false);
  1560. expect("subagentPermissionMode" in harness.actorRuntimeInputs.at(-1)!).toBe(false);
  1561. });
  1562. it("resume 以 run-launched 为准:会话已换到 yolo,续跑的子代理仍是 guarded", async () => {
  1563. let mode: CollaborationMode = "guarded";
  1564. const harness = makeHarness({ hangActors: true, permissionMode: () => mode });
  1565. const runId = await submitRun(harness, {
  1566. cwd: TEST_CWD,
  1567. scriptText: TYPED_SCRIPT,
  1568. trace: traceFor("permission-mode-resume"),
  1569. });
  1570. await vi.waitFor(() => {
  1571. expect(harness.actorRuntimeInputs).toHaveLength(1);
  1572. });
  1573. expect(await harness.service.cancel(runId)).toBe(true);
  1574. await settle(harness, runId);
  1575. mode = "yolo";
  1576. const resumed = await harness.service.resume!(runId);
  1577. expect(resumed).toMatchObject({ ok: true, runId });
  1578. await vi.waitFor(() => {
  1579. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(1);
  1580. });
  1581. expect(harness.actorRuntimeInputs.at(-1)?.subagentPermissionMode).toBe("guarded");
  1582. expect(await harness.service.cancel(runId)).toBe(true);
  1583. await settle(harness, runId);
  1584. });
  1585. it("amend 是新 run:取修订那一刻的会话模式,不继承前驱的", async () => {
  1586. let mode: CollaborationMode = "yolo";
  1587. const harness = makeHarness({ hangActors: true, permissionMode: () => mode });
  1588. const predecessor = await submitRun(harness, {
  1589. cwd: TEST_CWD,
  1590. scriptText: TYPED_SCRIPT,
  1591. trace: traceFor("permission-mode-amend-a"),
  1592. });
  1593. await vi.waitFor(() => {
  1594. expect(launchedOf(harness, predecessor)).toBeDefined();
  1595. });
  1596. expect(launchedOf(harness, predecessor)).toMatchObject({ subagentPermissionMode: "yolo" });
  1597. mode = "guarded";
  1598. const guarded = await amendRun(harness, {
  1599. cwd: TEST_CWD,
  1600. predecessorRunId: predecessor,
  1601. scriptText: TYPED_SCRIPT,
  1602. trace: traceFor("permission-mode-amend-b"),
  1603. });
  1604. await vi.waitFor(() => {
  1605. expect(launchedOf(harness, guarded.runId)).toMatchObject({
  1606. subagentPermissionMode: "guarded",
  1607. });
  1608. });
  1609. mode = "build";
  1610. const relaxed = await amendRun(harness, {
  1611. cwd: TEST_CWD,
  1612. predecessorRunId: guarded.runId,
  1613. scriptText: TYPED_SCRIPT,
  1614. trace: traceFor("permission-mode-amend-c"),
  1615. });
  1616. await vi.waitFor(() => {
  1617. expect(launchedOf(harness, relaxed.runId)).toBeDefined();
  1618. });
  1619. expect(launchedOf(harness, relaxed.runId)).toMatchObject({ subagentPermissionMode: "build" });
  1620. expect(await harness.service.cancel(relaxed.runId)).toBe(true);
  1621. await settle(harness, relaxed.runId);
  1622. });
  1623. });
  1624. // ── 本 run 的脚本文件(docs/dynamic-workflow/launch.md「Script files」的 Provenance)───────
  1625. // `scriptPath` 记的是「这个 run 的脚本从哪个文件来的」,绝对路径。与子代理模型逐条同规:
  1626. // 随 `run-launched` 记一次、引擎不读、零 SQL、两条读面读回(有条目读条目,冷行扫事件头)。
  1627. // 唯一的不同是它**没有三态**:修订记的永远是新脚本的文件,绝不沿用前驱的——前驱的路径
  1628. // 指向旧脚本,沿用它就是让模型下次去编辑一个已经不在跑的文件。
  1629. describe("dynamic workflow run service — 本 run 的脚本文件", () => {
  1630. const DRAFT = "/repo/.zcode/workflow-drafts/audit.dwf.ts";
  1631. const REVISED = "/repo/.zcode/workflow-drafts/audit-2.dwf.ts";
  1632. const launchedOf = (harness: Harness, runId: string): RunEvent | undefined =>
  1633. harness.journal
  1634. .listEvents(runId, { types: "all", reportItems: "all" })
  1635. .map((stored) => stored.event)
  1636. .find((event) => event.type === "run-launched");
  1637. const scriptPathOf = (harness: Harness, runId: string): string | undefined => {
  1638. const launched = launchedOf(harness, runId);
  1639. return launched?.type === "run-launched" ? launched.scriptPath : undefined;
  1640. };
  1641. it("submit 把绝对路径记进 run-launched,行上没有这条事实;不给即整个键缺席", async () => {
  1642. const harness = makeHarness();
  1643. const withFile = await submitRun(harness, {
  1644. cwd: TEST_CWD,
  1645. scriptText: TYPED_SCRIPT,
  1646. scriptPath: DRAFT,
  1647. trace: traceFor("script-path-submit"),
  1648. });
  1649. await settle(harness, withFile);
  1650. expect(scriptPathOf(harness, withFile)).toBe(DRAFT);
  1651. // 零 SQL:记录行上没有这条事实(用户裁决不做迁移),读侧一律走事件。
  1652. expect("scriptPath" in harness.journal.getRun(withFile)!).toBe(false);
  1653. const without = await submitRun(harness, {
  1654. cwd: TEST_CWD,
  1655. scriptText: TYPED_SCRIPT,
  1656. trace: traceFor("script-path-submit-absent"),
  1657. });
  1658. await settle(harness, without);
  1659. // 键缺席而不是 `undefined`:模型面据「在不在场」决定说哪一句下一步。
  1660. expect("scriptPath" in launchedOf(harness, without)!).toBe(false);
  1661. });
  1662. it("快照与详情给出同一个绝对路径;不给时两条读面都不带这个键(冷重启后照样)", async () => {
  1663. await withSqliteJournal(async (journal) => {
  1664. const harness = makeHarness({ journal });
  1665. const withFile = await submitRun(harness, {
  1666. cwd: projectCwd,
  1667. parentSessionId: HARNESS_PARENT_SESSION,
  1668. scriptText: TYPED_SCRIPT,
  1669. scriptPath: DRAFT,
  1670. trace: traceFor("script-path-read-set"),
  1671. });
  1672. await settle(harness, withFile);
  1673. const without = await submitRun(harness, {
  1674. cwd: projectCwd,
  1675. parentSessionId: HARNESS_PARENT_SESSION,
  1676. scriptText: TYPED_SCRIPT,
  1677. trace: traceFor("script-path-read-absent"),
  1678. });
  1679. await settle(harness, without);
  1680. const introspection = introspectionOf(harness);
  1681. expect(await harness.service.getTask(withFile)).toMatchObject({ scriptPath: DRAFT });
  1682. expect(await introspection.getRunDetail(withFile)).toMatchObject({ scriptPath: DRAFT });
  1683. expect("scriptPath" in (await harness.service.getTask(without))!).toBe(false);
  1684. expect("scriptPath" in (await introspection.getRunDetail(without))!).toBe(false);
  1685. // 列表行不带:与子代理模型、并发上界同规——只有 AmendWorkflow 用得上的字段不该把
  1686. // 枚举面的每一行都加宽。
  1687. const { runs } = await introspection.listRuns({ cwd: projectCwd, limit: 20 });
  1688. expect(runs).toHaveLength(2);
  1689. for (const row of runs) expect("scriptPath" in row).toBe(false);
  1690. // 重启(新服务、空注册表、同一个 journal):内存副本没有了,两条读面只能从
  1691. // `run-launched` 事件读回——「零 SQL 也能冷读」的证据。
  1692. const cold = makeHarness({ journal });
  1693. const coldIntrospection = introspectionOf(cold);
  1694. expect(await cold.service.getTask(withFile)).toMatchObject({ scriptPath: DRAFT });
  1695. expect(await coldIntrospection.getRunDetail(withFile)).toMatchObject({ scriptPath: DRAFT });
  1696. expect("scriptPath" in (await cold.service.getTask(without))!).toBe(false);
  1697. expect("scriptPath" in (await coldIntrospection.getRunDetail(without))!).toBe(false);
  1698. });
  1699. });
  1700. // 间隙(submit 已返回、dwf_run 行还没落):与子代理模型同一条论证——注册表副本必须与
  1701. // 落行后给出同一个答案。
  1702. it("间隙里的快照与详情读注册表副本,答案与落行后一致", async () => {
  1703. await withSqliteJournal(async (real) => {
  1704. const hidden = new Set<string>();
  1705. const journal = hideRunsFromReads(real, hidden);
  1706. const harness = makeHarness({ hangActors: true, journal });
  1707. const runId = await submitRun(harness, {
  1708. cwd: projectCwd,
  1709. parentSessionId: HARNESS_PARENT_SESSION,
  1710. scriptText: TYPED_SCRIPT,
  1711. scriptPath: DRAFT,
  1712. trace: traceFor("script-path-gap"),
  1713. });
  1714. hidden.add(runId);
  1715. expect(await harness.service.getTask(runId)).toMatchObject({ scriptPath: DRAFT });
  1716. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  1717. scriptPath: DRAFT,
  1718. });
  1719. hidden.delete(runId);
  1720. await vi.waitFor(async () => {
  1721. expect(await introspectionOf(harness).getRunDetail(runId)).toMatchObject({
  1722. scriptPath: DRAFT,
  1723. });
  1724. });
  1725. await harness.service.cancel(runId);
  1726. await settle(harness, runId);
  1727. });
  1728. });
  1729. it("amend 用请求里的路径,绝不继承前驱的(不给即缺席,不是沿用)", async () => {
  1730. const harness = makeHarness({ hangActors: true });
  1731. const predecessor = await submitRun(harness, {
  1732. cwd: TEST_CWD,
  1733. scriptText: TYPED_SCRIPT,
  1734. scriptPath: DRAFT,
  1735. trace: traceFor("script-path-amend-a"),
  1736. });
  1737. await vi.waitFor(() => {
  1738. expect(scriptPathOf(harness, predecessor)).toBe(DRAFT);
  1739. });
  1740. const amended = await amendRun(harness, {
  1741. cwd: TEST_CWD,
  1742. predecessorRunId: predecessor,
  1743. scriptText: TYPED_SCRIPT,
  1744. scriptPath: REVISED,
  1745. trace: traceFor("script-path-amend-b"),
  1746. });
  1747. await vi.waitFor(() => {
  1748. expect(scriptPathOf(harness, amended.runId)).toBe(REVISED);
  1749. });
  1750. expect(await harness.service.cancel(amended.runId)).toBe(true);
  1751. await settle(harness, amended.runId);
  1752. // 同一个前驱、这次不带字段:后继没有文件(缺席 ≠ 沿用前驱的 DRAFT)。前驱的路径指向的
  1753. // 是旧脚本,端口若在这里继承一次,模型下次就会去编辑一个已经不在跑的文件。
  1754. const cleared = await amendRun(harness, {
  1755. cwd: TEST_CWD,
  1756. predecessorRunId: predecessor,
  1757. scriptText: TYPED_SCRIPT,
  1758. trace: traceFor("script-path-amend-c"),
  1759. });
  1760. await vi.waitFor(() => {
  1761. expect(launchedOf(harness, cleared.runId)).toBeDefined();
  1762. });
  1763. expect("scriptPath" in launchedOf(harness, cleared.runId)!).toBe(false);
  1764. expect(await harness.service.cancel(cleared.runId)).toBe(true);
  1765. await settle(harness, cleared.runId);
  1766. });
  1767. it("resume 从 run-launched 事件读回路径抄进条目:读面照旧「有条目就读条目」", async () => {
  1768. const harness = makeHarness({ hangActors: true });
  1769. const runId = await submitRun(harness, {
  1770. cwd: TEST_CWD,
  1771. scriptText: TYPED_SCRIPT,
  1772. scriptPath: DRAFT,
  1773. trace: traceFor("script-path-resume"),
  1774. });
  1775. await vi.waitFor(() => {
  1776. expect(harness.actorRuntimeInputs).toHaveLength(1);
  1777. });
  1778. expect(await harness.service.cancel(runId)).toBe(true);
  1779. await settle(harness, runId);
  1780. expect(await harness.service.resume!(runId)).toMatchObject({ ok: true, runId });
  1781. await vi.waitFor(() => {
  1782. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(1);
  1783. });
  1784. // 续跑那一世的条目带上了这个路径(resume 入口根本没有这个形参,唯一来源是事件)。
  1785. // spy 是「有条目就读条目」的证据:快照答得出路径,却一次 listEvents 都没发。
  1786. const listEvents = vi.spyOn(harness.journal, "listEvents");
  1787. expect(await harness.service.getTask(runId)).toMatchObject({ scriptPath: DRAFT });
  1788. expect(listEvents).not.toHaveBeenCalled();
  1789. listEvents.mockRestore();
  1790. expect(await harness.service.cancel(runId)).toBe(true);
  1791. await settle(harness, runId);
  1792. });
  1793. });
  1794. describe("dynamic workflow run service — 发起锚点(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Token telemetry for subagents」)", () => {
  1795. const anchoredEvents = (harness: Harness) =>
  1796. harness.runEvents.filter(
  1797. (event) => event.eventType === "actor-created" || event.eventType === "run-settled",
  1798. );
  1799. it("活动轮命中 → journal 首条 run-launched 与 actor-created / run-settled 载荷带同一锚点", async () => {
  1800. const trace = traceFor("anchor-active");
  1801. const harness = makeHarness({
  1802. resolveLaunchInputId: (candidate) =>
  1803. candidate.turnId === trace.turnId ? "launch-input-active" : undefined,
  1804. });
  1805. const runId = await submitRun(harness, {
  1806. cwd: TEST_CWD,
  1807. parentSessionId: createSessionId("anchor-parent"),
  1808. scriptText: TYPED_SCRIPT,
  1809. toolCallId: "tool-anchor",
  1810. trace,
  1811. });
  1812. await settle(harness, runId);
  1813. const events = harness.journal.listEvents(runId, { types: "all", reportItems: "all" });
  1814. expect(events.slice(0, 2).map((stored) => stored.event.type)).toEqual([
  1815. "run-started",
  1816. "run-launched",
  1817. ]);
  1818. expect(events[1]?.event).toMatchObject({
  1819. inputId: "launch-input-active",
  1820. toolCallId: "tool-anchor",
  1821. });
  1822. const anchored = anchoredEvents(harness);
  1823. expect(anchored.map((event) => event.eventType)).toEqual(["actor-created", "run-settled"]);
  1824. expect(anchored.every((event) => event.launchInputId === "launch-input-active")).toBe(true);
  1825. // 其余事件不带派生字段:锚点只在归属的两个时刻需要。
  1826. expect(
  1827. harness.runEvents
  1828. .filter((event) => event.eventType === "node-queued")
  1829. .every((event) => event.launchInputId === undefined),
  1830. ).toBe(true);
  1831. });
  1832. it("submit 的 phaseNames 落进 run-launched(journal 是唯一副本,冷重放免费重建)", async () => {
  1833. const harness = makeHarness();
  1834. const runId = await submitRun(harness, {
  1835. cwd: TEST_CWD,
  1836. launchInputId: "launch-input-phases",
  1837. phaseNames: ["Research", "Write"],
  1838. scriptText: TYPED_SCRIPT,
  1839. trace: traceFor("anchor-phases"),
  1840. });
  1841. await settle(harness, runId);
  1842. expect(
  1843. harness.journal.listEvents(runId, { types: "all", reportItems: "all" })[1]?.event,
  1844. ).toEqual({
  1845. type: "run-launched",
  1846. inputId: "launch-input-phases",
  1847. phaseNames: ["Research", "Write"],
  1848. });
  1849. });
  1850. it("submit 的 phaseAlongside 与阶段表同车落 journal(service 只转发,不加工)", async () => {
  1851. const harness = makeHarness();
  1852. const runId = await submitRun(harness, {
  1853. cwd: TEST_CWD,
  1854. launchInputId: "launch-input-alongside",
  1855. phaseNames: ["A", "B", "C"],
  1856. phaseAlongside: [[], [0], []],
  1857. scriptText: TYPED_SCRIPT,
  1858. trace: traceFor("anchor-alongside"),
  1859. });
  1860. await settle(harness, runId);
  1861. expect(
  1862. harness.journal.listEvents(runId, { types: "all", reportItems: "all" })[1]?.event,
  1863. ).toEqual({
  1864. type: "run-launched",
  1865. inputId: "launch-input-alongside",
  1866. phaseNames: ["A", "B", "C"],
  1867. phaseAlongside: [[], [0], []],
  1868. });
  1869. });
  1870. it("显式 launchInputId(中枢直接启动)优先于活动轮解析", async () => {
  1871. const harness = makeHarness({ resolveLaunchInputId: () => "active-should-lose" });
  1872. const runId = await submitRun(harness, {
  1873. cwd: TEST_CWD,
  1874. launchInputId: "launch-input-direct",
  1875. scriptText: TYPED_SCRIPT,
  1876. trace: traceFor("anchor-direct"),
  1877. });
  1878. await settle(harness, runId);
  1879. expect(
  1880. harness.journal.listEvents(runId, { types: "all", reportItems: "all" })[1]?.event,
  1881. ).toMatchObject({
  1882. inputId: "launch-input-direct",
  1883. });
  1884. expect(
  1885. anchoredEvents(harness).every((event) => event.launchInputId === "launch-input-direct"),
  1886. ).toBe(true);
  1887. });
  1888. it("没有解析器也没有显式值 → 铸 UUID v7 锚点", async () => {
  1889. const harness = makeHarness();
  1890. const runId = await submitRun(harness, {
  1891. cwd: TEST_CWD,
  1892. scriptText: TYPED_SCRIPT,
  1893. trace: traceFor("anchor-minted"),
  1894. });
  1895. await settle(harness, runId);
  1896. const launched = harness.journal.listEvents(runId, { types: "all", reportItems: "all" })[1]
  1897. ?.event;
  1898. expect(launched?.type).toBe("run-launched");
  1899. const inputId = launched?.type === "run-launched" ? launched.inputId : "";
  1900. expect(inputId).toMatch(
  1901. /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
  1902. );
  1903. expect(anchoredEvents(harness).every((event) => event.launchInputId === inputId)).toBe(true);
  1904. });
  1905. });
  1906. describe("dynamic workflow run service — 产物存储的接线", () => {
  1907. /** 记录写入参数的 fake store(只需文本写:脚本发的是 markdown)。 */
  1908. function recordingArtifactStore(): {
  1909. store: ToolArtifactStorePort;
  1910. writes: ToolArtifactWriteRequest[];
  1911. } {
  1912. const writes: ToolArtifactWriteRequest[] = [];
  1913. return {
  1914. writes,
  1915. store: {
  1916. writeToolResultArtifact: async (request) => {
  1917. writes.push(request);
  1918. return {
  1919. id: "artifact-1",
  1920. uri: "zcode-artifact://harness/artifact-1",
  1921. bytes: Buffer.byteLength(request.content, "utf8"),
  1922. contentType: request.contentType ?? "text/plain",
  1923. createdAt: new Date(0),
  1924. };
  1925. },
  1926. readToolResultArtifact: async () => {
  1927. throw new Error("readToolResultArtifact 不应被本用例触及");
  1928. },
  1929. },
  1930. };
  1931. }
  1932. it("store 经 service → launch → driver 送达,会话作用域是本服务的父会话", async () => {
  1933. const { store, writes } = recordingArtifactStore();
  1934. const harness = makeHarness({ artifactStore: store });
  1935. const runId = await submitRun(harness, {
  1936. cwd: TEST_CWD,
  1937. parentSessionId: createSessionId("some-other-session"),
  1938. scriptText: ARTIFACT_SCRIPT,
  1939. trace: traceFor("artifact-wiring"),
  1940. });
  1941. await settle(harness, runId);
  1942. expect(harness.journal.getRun(runId)?.status).toBe("completed");
  1943. expect(writes).toHaveLength(1);
  1944. expect(writes[0]).toMatchObject({
  1945. // **本服务的**父会话,不是 submit 请求里那个可选的 parentSessionId:生产里两者同值,
  1946. // 而只有前者是必填的(字节写进哪个会话的目录不该有 undefined 分支)。
  1947. sessionId: HARNESS_PARENT_SESSION,
  1948. toolName: "CreateWorkflow",
  1949. retention: "project",
  1950. contentType: "text/markdown",
  1951. });
  1952. expect(String(writes[0]?.toolCallId)).toBe(`${runId}:artifact#1@1`);
  1953. });
  1954. it("不接 store 的装配里,发布以 ArtifactStoreUnavailable 拒绝而 run 照常结算", async () => {
  1955. const harness = makeHarness();
  1956. const runId = await submitRun(harness, {
  1957. cwd: TEST_CWD,
  1958. // 脚本 catch 住拒绝并把错误码当结果交出来:这正是 spec 的门控习语。
  1959. scriptText: [
  1960. "let code = 'none';",
  1961. 'try { await artifact.markdown("summary", "# 结论"); }',
  1962. "catch (error) { code = (error as { code?: string }).code ?? 'unknown'; }",
  1963. "return code;",
  1964. ].join("\n"),
  1965. trace: traceFor("artifact-no-store"),
  1966. });
  1967. await settle(harness, runId);
  1968. const snapshot = await harness.service.getTask(runId);
  1969. expect(snapshot?.status).toBe("completed");
  1970. expect(snapshot?.output).toBe("ArtifactStoreUnavailable");
  1971. });
  1972. });
  1973. // ── 用户面产物的读面(docs/dynamic-workflow/authoring.md「How the user sees them」)──────────────
  1974. // ⚠ 术语:artifact = 脚本经 `artifact.*` 发布给**用户**看的产出,不是端口上的 `output`
  1975. // (脚本顶层返回值,引擎内部对它的同名叫法)。
  1976. //
  1977. // 三个端口方法:listArtifacts(清单)/ listArtifactItems(看板取数)/ readArtifact(字节)。
  1978. // readArtifact 的授权链是本节的重点:run 属于本会话 ∧ journal 有该版本的 completed 行 ⇒
  1979. // 才拿**行上的** uri 去 store 读。每一条负例都断言 store **一次都没被碰过**。
  1980. describe("dynamic workflow run service — 用户面产物的读面", () => {
  1981. /** 记录读写的 fake store;`readToolResultBinaryArtifact` 按 uri 回它写过的字节。 */
  1982. function readableArtifactStore(): {
  1983. store: ToolArtifactStorePort;
  1984. reads: string[];
  1985. } {
  1986. const bytesByUri = new Map<string, Uint8Array>();
  1987. const reads: string[] = [];
  1988. let next = 0;
  1989. return {
  1990. reads,
  1991. store: {
  1992. writeToolResultArtifact: async (request) => {
  1993. next += 1;
  1994. const uri = `zcode-artifact://harness/artifact-${next}`;
  1995. bytesByUri.set(uri, new TextEncoder().encode(request.content));
  1996. return {
  1997. id: `artifact-${next}`,
  1998. uri,
  1999. bytes: Buffer.byteLength(request.content, "utf8"),
  2000. contentType: request.contentType ?? "text/plain",
  2001. createdAt: new Date(0),
  2002. };
  2003. },
  2004. readToolResultArtifact: async () => {
  2005. throw new Error(
  2006. "字节读回必须走 readToolResultBinaryArtifact(文本读会毁掉 office 文件)",
  2007. );
  2008. },
  2009. readToolResultBinaryArtifact: async (request) => {
  2010. reads.push(request.uri);
  2011. const bytes = bytesByUri.get(request.uri);
  2012. if (bytes === undefined) throw new Error(`unknown uri: ${request.uri}`);
  2013. // store 侧按文件名再推一次 contentType,故意给一个**错的**:读面必须用 journal
  2014. // 记录上的那一份(UI 分派渲染器的精确匹配契约)。
  2015. return { uri: request.uri, bytes, contentType: "application/json" };
  2016. },
  2017. },
  2018. };
  2019. }
  2020. /** 声明一块看板、喂它两条标签 report,再发布两版 markdown。 */
  2021. const MIXED_SCRIPT = [
  2022. 'artifact.chart("perf", { x: { field: "round" }, y: { field: "ms" } });',
  2023. 'report({ round: 1, ms: 40 }, "perf");',
  2024. 'report({ round: 2, ms: 31 }, "perf");',
  2025. "report({ untagged: true });",
  2026. 'await artifact.markdown("summary", "# 第一版");',
  2027. 'await artifact.markdown("summary", "# 第二版");',
  2028. 'return "done";',
  2029. ].join("\n");
  2030. async function runMixed(overrides: { parentSessionId?: SessionId } = {}) {
  2031. const { store, reads } = readableArtifactStore();
  2032. const harness = makeHarness({ artifactStore: store });
  2033. const runId = await submitRun(harness, {
  2034. cwd: TEST_CWD,
  2035. parentSessionId: overrides.parentSessionId ?? HARNESS_PARENT_SESSION,
  2036. scriptText: MIXED_SCRIPT,
  2037. trace: traceFor("artifact-reads"),
  2038. });
  2039. await settle(harness, runId);
  2040. expect(harness.journal.getRun(runId)?.status).toBe("completed");
  2041. return { harness, runId, reads };
  2042. }
  2043. it("listArtifacts 按 id 分组、版本升序,顶层取最新版;看板带 itemCount、内容产物恒 0", async () => {
  2044. const { harness, runId } = await runMixed();
  2045. const artifacts = await harness.service.listArtifacts!(runId);
  2046. expect(artifacts).toHaveLength(2);
  2047. // 顺序 = 首次出现顺序:看板先声明,markdown 后发布。
  2048. const [chart, summary] = artifacts!;
  2049. // 未打标签的那条 report 不算进任何产物。
  2050. expect(chart).toMatchObject({ id: "perf", kind: "chart", version: 1, itemCount: 2 });
  2051. expect(chart?.versions).toHaveLength(1);
  2052. expect(summary).toMatchObject({
  2053. id: "summary",
  2054. kind: "markdown",
  2055. version: 2,
  2056. contentType: "text/markdown",
  2057. itemCount: 0,
  2058. });
  2059. expect(summary?.versions.map((entry) => entry.version)).toEqual([1, 2]);
  2060. });
  2061. it("listArtifactItems 按 sequence 升序分页,afterSequence 严格大于,hasMore 由存储层判定", async () => {
  2062. const { harness, runId } = await runMixed();
  2063. const read = (page: { afterSequence?: number; limit: number }, artifactId = "perf") =>
  2064. harness.service.listArtifactItems!(runId, artifactId, { ...page, maxBytes: 1 << 30 });
  2065. const all = await read({ limit: 10 });
  2066. expect(all.items.map((entry) => entry.item)).toEqual([
  2067. { round: 1, ms: 40 },
  2068. { round: 2, ms: 31 },
  2069. ]);
  2070. expect(all.items[0]?.siteId).toBe("report#1");
  2071. expect(all.hasMore).toBe(false);
  2072. // limit 精确:存储层绝不自己钳,且说得出页之后还有没有。
  2073. const firstPage = await read({ limit: 1 });
  2074. expect(firstPage.items).toHaveLength(1);
  2075. expect(firstPage.hasMore).toBe(true);
  2076. // 游标严格大于。
  2077. const secondPage = await read({ afterSequence: firstPage.items[0]!.sequence, limit: 10 });
  2078. expect(secondPage.items.map((entry) => entry.item)).toEqual([{ round: 2, ms: 31 }]);
  2079. // 越界 cursor 得到空页,不是错误——翻到尾巴是正常的翻页结局。
  2080. expect(await read({ afterSequence: 9_999, limit: 10 })).toEqual({ items: [], hasMore: false });
  2081. // 未知 id 同样是空页(未打标签的那条 report 不属于任何 id)。
  2082. expect(await read({ limit: 10 }, "ghost")).toEqual({ items: [], hasMore: false });
  2083. });
  2084. it("readArtifact 回字节 + **journal 记录上的** contentType(不是 store 再推的那份)", async () => {
  2085. const { harness, runId, reads } = await runMixed();
  2086. const first = await harness.service.readArtifact!(runId, "summary", 1);
  2087. const second = await harness.service.readArtifact!(runId, "summary", 2);
  2088. expect(new TextDecoder().decode(first!.bytes)).toBe("# 第一版");
  2089. expect(new TextDecoder().decode(second!.bytes)).toBe("# 第二版");
  2090. // store 的替身故意回 application/json;记录上的 text/markdown 才是 UI 的分派契约。
  2091. expect(first!.contentType).toBe("text/markdown");
  2092. // 两个版本各自的 uri——版本历史是真的,不是同一份字节换个号。
  2093. expect(new Set(reads).size).toBe(2);
  2094. });
  2095. it("授权负例:run 的父会话不是本服务的 ⇒ 拒绝,且 store 一次都没被碰", async () => {
  2096. // 这是 spec 行 177 的授权链第 ② 步。服务实例按父会话构造,一个别的会话的 run 的字节
  2097. // 绝不能经本服务流出去。
  2098. const { harness, runId, reads } = await runMixed({
  2099. parentSessionId: createSessionId("some-other-session"),
  2100. });
  2101. expect(await harness.service.readArtifact!(runId, "summary", 1)).toBeUndefined();
  2102. expect(reads).toEqual([]);
  2103. });
  2104. it("授权负例:未知 runId / 未知 artifactId / 未知版本 ⇒ 拒绝,store 未被碰", async () => {
  2105. const { harness, runId, reads } = await runMixed();
  2106. expect(await harness.service.readArtifact!("dwfrun-nope", "summary", 1)).toBeUndefined();
  2107. expect(await harness.service.readArtifact!(runId, "ghost", 1)).toBeUndefined();
  2108. // 只发布过两版,第 3 版不存在——版本号是授权链的一部分,不是一个可以越过的提示。
  2109. expect(await harness.service.readArtifact!(runId, "summary", 3)).toBeUndefined();
  2110. expect(reads).toEqual([]);
  2111. });
  2112. it("授权负例:预置看板没有字节 ⇒ 拒绝(它的数据是 journal 里的标签 report 行)", async () => {
  2113. const { harness, runId, reads } = await runMixed();
  2114. expect(await harness.service.readArtifact!(runId, "perf", 1)).toBeUndefined();
  2115. expect(reads).toEqual([]);
  2116. });
  2117. it("store 缺席 / 不带二进制读回 ⇒ 整条读回缺席,绝不退回文本读再解码", async () => {
  2118. // 退回文本读正是 2026-09-04 记录在 ToolBinaryArtifactReadResult 上的那条 bug:
  2119. // store 按文件名推 contentType,office 扩展名落到 application/json 被当 utf8 解码即损坏。
  2120. const textOnly: ToolArtifactStorePort = {
  2121. writeToolResultArtifact: async (request) => ({
  2122. id: "a1",
  2123. uri: "zcode-artifact://harness/a1",
  2124. bytes: Buffer.byteLength(request.content, "utf8"),
  2125. contentType: request.contentType ?? "text/plain",
  2126. createdAt: new Date(0),
  2127. }),
  2128. readToolResultArtifact: async () => {
  2129. throw new Error("不带二进制能力的 store 不得被退回文本读");
  2130. },
  2131. };
  2132. const harness = makeHarness({ artifactStore: textOnly });
  2133. const runId = await submitRun(harness, {
  2134. cwd: TEST_CWD,
  2135. parentSessionId: HARNESS_PARENT_SESSION,
  2136. scriptText: ARTIFACT_SCRIPT,
  2137. trace: traceFor("artifact-read-textonly"),
  2138. });
  2139. await settle(harness, runId);
  2140. expect(await harness.service.readArtifact!(runId, "summary", 1)).toBeUndefined();
  2141. });
  2142. it("引擎发出的事件真的能被共享 reducer 归约成 workflowRuns.artifacts(两半的接缝)", async () => {
  2143. // 这条钉的是**接缝**,不是任何一半:reducer 假设 `artifact-published` 的载荷是
  2144. // `{ instance, artifact: ArtifactVersionRecord }`,而载荷实际由引擎发、经
  2145. // toProgressPayload 有界化。两边各自的单测都绿、形状却对不上,是这类分层最典型的
  2146. // 静默失败——症状是侧板永远空着,而没有任何一处报错。
  2147. const { harness, runId } = await runMixed();
  2148. const published = harness.runEvents.filter((event) => event.eventType === "artifact-published");
  2149. // 一块看板声明 + 两版 markdown = 三条;失败的发布才走 artifact-failed(本脚本没有)。
  2150. expect(published).toHaveLength(3);
  2151. expect(harness.runEvents.some((event) => event.eventType === "artifact-failed")).toBe(false);
  2152. // 产物站点不发任何节点生命周期事件(slice 1 的裁决:否则投影会把它归约进 nodes[],
  2153. // 侧板上就多出一个没人能等的 untracked 节点)。
  2154. expect(
  2155. published.every((event) => (event.payload as { instance?: unknown }).instance !== undefined),
  2156. ).toBe(true);
  2157. let state: WorkflowRunsState | undefined;
  2158. for (const event of harness.runEvents) {
  2159. state = reduceWorkflowRunsState(state, event as WorkflowRunProgressEnvelope) ?? state;
  2160. }
  2161. expect(state?.runs[0]?.artifacts).toEqual([
  2162. { id: "perf", kind: "chart", version: 1, itemCount: 2 },
  2163. // bytes 随记录带上来(卡片要显示大小);11 = "# 第二版" 的 UTF-8 字节数。
  2164. { id: "summary", kind: "markdown", version: 2, contentType: "text/markdown", bytes: 11 },
  2165. ]);
  2166. // 归约出来的状态过 strict schema——线上那一帧不会因为多带/少带一个键被整帧丢掉。
  2167. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  2168. // 打了标签的 report 仍然进 Results 区(一条通道一套上限),未打标签的也在。
  2169. expect(state?.runs[0]?.reports?.map((report) => report.artifactId)).toEqual([
  2170. "perf",
  2171. "perf",
  2172. undefined,
  2173. ]);
  2174. });
  2175. it("零产物的 run:listArtifacts 整个缺席(不是空数组)", async () => {
  2176. const harness = makeHarness();
  2177. const runId = await submitRun(harness, {
  2178. cwd: TEST_CWD,
  2179. parentSessionId: HARNESS_PARENT_SESSION,
  2180. scriptText: TYPED_SCRIPT,
  2181. trace: traceFor("artifact-none"),
  2182. });
  2183. await settle(harness, runId);
  2184. expect(await harness.service.listArtifacts!(runId)).toBeUndefined();
  2185. });
  2186. });
  2187. describe("dynamic workflow run service — actor sessions", () => {
  2188. it("两个持久化调用都发生,且 task link 在会话落库之后", async () => {
  2189. const harness = makeHarness();
  2190. const runId = await submitRun(harness, {
  2191. cwd: TEST_CWD,
  2192. parentSessionId: createSessionId("actor-parent"),
  2193. scriptText: TYPED_SCRIPT,
  2194. trace: traceFor("actor-persist"),
  2195. });
  2196. await settle(harness, runId);
  2197. // 1. ensureSessionPersistedForExternalActivity
  2198. expect(harness.persistedTitles).toHaveLength(1);
  2199. expect(harness.persistedTitles[0]).toContain("actor#1@1");
  2200. // 2. createSessionTaskLink
  2201. expect(harness.taskLinks).toHaveLength(1);
  2202. const link = harness.taskLinks[0]!;
  2203. expect(link.role).toBe("workflow_actor");
  2204. expect(link.parentSessionId).toBe(createSessionId("actor-parent"));
  2205. // run 身份走无 FK 的 path 列:rootWorkflowRunId 对 legacy workflow_run(id) 有 FK,
  2206. // 填 dwf runId 会以 FOREIGN KEY constraint failed 拒掉每一个 link。
  2207. expect(link.rootWorkflowRunId).toBeUndefined();
  2208. expect(link.path).toContain(runId);
  2209. });
  2210. /**
  2211. * 生产接线的绊线(amend-resume):转录面从 service deps 一路交到 driver 手上,边界才写得下来。
  2212. * 中间任何一环忘了透传,都不会有编译错误、run 照常跑完——只是这个 run 从此**不能作修订的
  2213. * 前驱**(service 的「无 marker 前驱整体拒绝」门会挡下来),而症状离成因很远。所以这条用例
  2214. * 走真库:actor 的消息真的落库,边界必须等于同一个存取面数出来的长度。
  2215. */
  2216. it("接上会话存储后,ask 节点带上消息数边界(service → launch → driver 的透传)", async () => {
  2217. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-boundary-"));
  2218. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  2219. try {
  2220. const harness = makeHarness({ sessionStore: store as never });
  2221. const runId = await submitRun(harness, {
  2222. cwd: TEST_CWD,
  2223. scriptText: TYPED_SCRIPT,
  2224. trace: traceFor("actor-boundary"),
  2225. });
  2226. await settle(harness, runId);
  2227. const node = harness.journal.getNode(runId, "ask#1", 1);
  2228. const actorSessionId = harness.actorRuntimeInputs[0]!.sessionId;
  2229. const persisted = await store.messages({ sessionID: actorSessionId });
  2230. expect(persisted.length).toBeGreaterThan(0);
  2231. expect(node?.messageBoundary).toBe(persisted.length);
  2232. // 读改写:引擎写下的字段一个不许掉。
  2233. expect(node?.status).toBe("completed");
  2234. expect(node?.actorSeq).toBe(0);
  2235. expect(node?.stats?.tokens).toBeGreaterThan(0);
  2236. } finally {
  2237. store.close();
  2238. await rm(tempRoot, { force: true, recursive: true });
  2239. }
  2240. });
  2241. // transcript 直播只剩一条通道:child runtime 的**构造期** eventSink。run service 不再
  2242. // 自己订阅——旧的 `onActorSessionEvent` + `subscribeEvents` 装在 persist 之后,而
  2243. // persist 写下的 SessionTitleUpdated 就是 seq 1,v4 网关只排水连续 seq,于是那条
  2244. // 订阅从 seq 2 起永远等一个再也不会来的 seq 1(transcript 永久空白)。
  2245. // driver 的限流观察订阅(每 actor 恰好一次)不是直播通道:它只读 ModelNetworkStatus,
  2246. // 漏掉 seq 1 无关紧要——所以这里钉的是「恰好每 actor 一次」,而不是零。
  2247. it("actor 事件只经构造期 sink 直播,subscribeEvents 只有 driver 的两个观察面(每 actor 各一次)", async () => {
  2248. const harness = makeHarness();
  2249. const runId = await submitRun(harness, {
  2250. cwd: TEST_CWD,
  2251. scriptText: TYPED_SCRIPT,
  2252. trace: traceFor("actor-live-channel"),
  2253. });
  2254. await settle(harness, runId);
  2255. const actorSessionId = harness.actorRuntimeInputs[0]!.sessionId;
  2256. expect(harness.sessionEvents.length).toBeGreaterThan(0);
  2257. expect(
  2258. harness.sessionEvents.every(
  2259. (event) => (event as { sessionId: string }).sessionId === actorSessionId,
  2260. ),
  2261. ).toBe(true);
  2262. expect(harness.actorSubscribeCalls).toEqual([actorSessionId, actorSessionId]);
  2263. // 共享 store 的一面:actor 事件按自己的 sessionId 落在(生产里是父 runtime 的)store 里,
  2264. // 这正是 v4 `loadPersistedEvents(actorSessionId)` 读的地方。
  2265. const stored = await harness.actorEventStore.getEvents(actorSessionId);
  2266. expect(stored.length).toBe(harness.sessionEvents.length);
  2267. });
  2268. it("actor 会话 id 含 runId 且字符集安全", async () => {
  2269. const harness = makeHarness();
  2270. const runId = await submitRun(harness, {
  2271. cwd: TEST_CWD,
  2272. scriptText: TYPED_SCRIPT,
  2273. trace: traceFor("actor-session-id"),
  2274. });
  2275. await settle(harness, runId);
  2276. expect(harness.actorRuntimeInputs).toHaveLength(1);
  2277. const sessionId = harness.actorRuntimeInputs[0]!.sessionId;
  2278. expect(sessionId).toContain(runId);
  2279. // refToString(actor) 是 `actor#1@1`:# 与 @ 必须已被折叠掉。
  2280. expect(sessionId).not.toMatch(/[#@/]/);
  2281. });
  2282. // 持久化序列必须是**每 actor、创建时、原子**的:绝不批到 submit,也绝不推迟到第一次 ask 之后。
  2283. // 这条钉的正是那个退化——若将来有人把工厂改回 fire-and-forget,落库与建链就会与第一个
  2284. // turn 竞速,而 session_task_link.child_session_id 的 FK 要求会话行先存在。
  2285. it("持久化在该 actor 的首个 turn 之前完成(不是 fire-and-forget)", async () => {
  2286. const harness = makeHarness();
  2287. const runId = await submitRun(harness, {
  2288. cwd: TEST_CWD,
  2289. parentSessionId: createSessionId("order-parent"),
  2290. scriptText: TYPED_SCRIPT,
  2291. trace: traceFor("actor-order"),
  2292. });
  2293. await settle(harness, runId);
  2294. const persistIndex = harness.order.findIndex((entry) => entry.startsWith("persist:"));
  2295. const linkIndex = harness.order.findIndex((entry) => entry.startsWith("link:"));
  2296. const turnIndex = harness.order.findIndex((entry) => entry.startsWith("turn:"));
  2297. const constructIndex = harness.order.findIndex((entry) => entry.startsWith("construct:"));
  2298. expect(persistIndex).toBeGreaterThanOrEqual(0);
  2299. expect(linkIndex).toBeGreaterThanOrEqual(0);
  2300. expect(turnIndex).toBeGreaterThanOrEqual(0);
  2301. expect(constructIndex).toBeGreaterThanOrEqual(0);
  2302. // runtime 构造(= 直播 sink 装好)必须早于 persist:persist 写的 SessionTitleUpdated
  2303. // 是 seq 1,晚于它才生效的 sink 会让 v4 网关的连续排水从 seq 2 起永远等 seq 1。
  2304. expect(constructIndex).toBeLessThan(persistIndex);
  2305. // 落会话行 → 建 link(FK 顺序)→ 才允许第一个 turn 起跑。
  2306. expect(persistIndex).toBeLessThan(linkIndex);
  2307. expect(linkIndex).toBeLessThan(turnIndex);
  2308. });
  2309. it("dwf_actor.session_id 收到 driver 铸的会话 id", async () => {
  2310. const harness = makeHarness();
  2311. const runId = await submitRun(harness, {
  2312. cwd: TEST_CWD,
  2313. scriptText: TYPED_SCRIPT,
  2314. trace: traceFor("actor-journal"),
  2315. });
  2316. await settle(harness, runId);
  2317. const actors = harness.journal.listActors(runId, { withPersona: true });
  2318. expect(actors).toHaveLength(1);
  2319. expect(actors[0]!.sessionId).toBe(harness.actorRuntimeInputs[0]!.sessionId);
  2320. });
  2321. // 旧方案 `wf-actor-${refToString(actor)}` 不含 runId,并发两个 run 的同 site×ordinal
  2322. // actor 会撞成同一个会话 id。
  2323. it("并发两个 run 的同 site×ordinal actor 不撞会话 id", async () => {
  2324. const harness = makeHarness();
  2325. const [first, second] = await Promise.all([
  2326. submitRun(harness, {
  2327. cwd: TEST_CWD,
  2328. scriptText: TYPED_SCRIPT,
  2329. trace: traceFor("collide-a"),
  2330. }),
  2331. submitRun(harness, {
  2332. cwd: TEST_CWD,
  2333. scriptText: TYPED_SCRIPT,
  2334. trace: traceFor("collide-b"),
  2335. }),
  2336. ]);
  2337. await Promise.all([settle(harness, first), settle(harness, second)]);
  2338. expect(first).not.toBe(second);
  2339. const sessionIds = harness.actorRuntimeInputs.map((input) => input.sessionId);
  2340. expect(sessionIds).toHaveLength(2);
  2341. expect(new Set(sessionIds).size).toBe(2);
  2342. });
  2343. });
  2344. describe("dynamic workflow run service — cancellation", () => {
  2345. it("cancel 使 run 结算为 cancelled 而不是 failed,且保留已完结 journal 条目", async () => {
  2346. const harness = makeHarness({ hangActors: true });
  2347. const runId = await submitRun(harness, {
  2348. cwd: TEST_CWD,
  2349. scriptText: TYPED_SCRIPT,
  2350. trace: traceFor("cancel-run"),
  2351. });
  2352. // 等 actor 会话建起来(说明 ask 已派发、turn 在飞),再取消。
  2353. await vi.waitFor(() => {
  2354. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  2355. });
  2356. expect(await harness.service.cancel(runId)).toBe(true);
  2357. await settle(harness, runId);
  2358. const snapshot = await harness.service.getTask(runId);
  2359. // 失败绝不编码成停止,停止也绝不编码成失败:journal 里两者语义与 resume UX 不同。
  2360. // 快照基类的 status 是后台任务追踪器的通用词汇(stopped → cancelled);真实词在 runStatus。
  2361. expect(snapshot?.status).toBe("cancelled");
  2362. expect(snapshot?.runStatus).toBe("stopped");
  2363. expect(snapshot?.stopReason).toBe("user");
  2364. expect(harness.journal.getRun(runId)?.status).toBe("stopped");
  2365. expect(harness.journal.getRun(runId)?.stopReason).toBe("user");
  2366. // 已落库的 actor 记录保留(取消的 run 可 resume)。
  2367. expect(harness.journal.listActors(runId, { withPersona: true })).toHaveLength(1);
  2368. });
  2369. it("未知 run 的 cancel 返回 false", async () => {
  2370. const harness = makeHarness();
  2371. expect(await harness.service.cancel("dwfrun-does-not-exist")).toBe(false);
  2372. });
  2373. it("已结算 run 的 cancel 返回 false", async () => {
  2374. const harness = makeHarness();
  2375. const runId = await submitRun(harness, {
  2376. cwd: TEST_CWD,
  2377. scriptText: TYPED_SCRIPT,
  2378. trace: traceFor("cancel-settled"),
  2379. });
  2380. await settle(harness, runId);
  2381. expect(await harness.service.cancel(runId)).toBe(false);
  2382. });
  2383. });
  2384. /**
  2385. * 关闭(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Engine ownership」规则二)。
  2386. *
  2387. * 引擎是本 App 的闭包,App 一关它就没了宿主。所以关闭要主动停:以 `"interrupted"` abort 每个
  2388. * 在飞条目并等结算,那一笔**由引擎自己写**(updateRunStatus + run-settled + driver dispose),
  2389. * service 一个字都不补——绕过引擎写就会造出 dwf_run 的第二个写入者。
  2390. */
  2391. describe("dynamic workflow run service — close(Engine ownership 规则二)", () => {
  2392. /** journal 里该 run 目前的最大事件 sequence;用来证明「关闭之后不再有事件」。 */
  2393. function maxSequence(harness: Harness, runId: string): number {
  2394. return harness.journal
  2395. .listEvents(runId, { types: "all", reportItems: "all" })
  2396. .reduce((max, entry) => Math.max(max, entry.sequence), 0);
  2397. }
  2398. it("close 停下在飞 run:行为 stopped(interrupted) + Interrupted,且由引擎写下", async () => {
  2399. const harness = makeHarness({ hangActors: true });
  2400. const runId = await submitRun(harness, {
  2401. cwd: TEST_CWD,
  2402. parentSessionId: HARNESS_PARENT_SESSION,
  2403. scriptText: TYPED_SCRIPT,
  2404. trace: traceFor("close-live"),
  2405. });
  2406. await vi.waitFor(() => {
  2407. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  2408. });
  2409. expect(harness.service.countLiveRuns()).toBe(1);
  2410. await harness.service.close();
  2411. // close 解析时结算已经完成:不需要再等 waitForTask。
  2412. expect(harness.service.countLiveRuns()).toBe(0);
  2413. const record = harness.journal.getRun(runId);
  2414. expect(record?.status).toBe("stopped");
  2415. // interrupted 而不是 user:UI 上 user 读作「用户按了停止」,而这是宿主替它停的。
  2416. expect(record?.stopReason).toBe("interrupted");
  2417. expect(record?.failure?.code).toBe("Interrupted");
  2418. expect(record?.failure?.message).toContain("the owning session closed");
  2419. expect(record?.failure?.message).toContain(runId);
  2420. // 条目终态已就位,快照按 stopped 讲(可 resume)。
  2421. const snapshot = await harness.service.getTask(runId);
  2422. expect(snapshot?.runStatus).toBe("stopped");
  2423. expect(snapshot?.stopReason).toBe("interrupted");
  2424. // 引擎自己那一笔:journal 里有 run-settled,而不是 service 补写的一行裸状态。
  2425. const settled = harness.journal
  2426. .listEvents(runId, { types: "all", reportItems: "all" })
  2427. .filter(({ event }) => event.type === "run-settled");
  2428. expect(settled).toHaveLength(1);
  2429. // 关闭之后 journal 不再长:结算写在 close 解析之前,之后没有任何落后的事件。
  2430. const sequenceAtClose = maxSequence(harness, runId);
  2431. await new Promise((resolve) => setTimeout(resolve, 50));
  2432. expect(maxSequence(harness, runId)).toBe(sequenceAtClose);
  2433. });
  2434. it("close 等结算:在飞 run 未结算前 close 不解析", async () => {
  2435. const harness = makeHarness({ hangActors: true });
  2436. const runId = await submitRun(harness, {
  2437. cwd: TEST_CWD,
  2438. parentSessionId: HARNESS_PARENT_SESSION,
  2439. scriptText: TYPED_SCRIPT,
  2440. trace: traceFor("close-awaits"),
  2441. });
  2442. await vi.waitFor(() => {
  2443. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  2444. });
  2445. let settledFirst: string | undefined;
  2446. const unsubscribe = harness.service.subscribeRunSettled((notice) => {
  2447. settledFirst ??= `settled:${notice.runId}`;
  2448. });
  2449. let resolved = false;
  2450. const closing = harness.service.close().then(() => {
  2451. resolved = true;
  2452. });
  2453. // 结算靠真实的 abort → 引擎 stop → finishRun 链路,不是一个微任务就能走完。
  2454. expect(resolved).toBe(false);
  2455. await closing;
  2456. expect(resolved).toBe(true);
  2457. // 结算通知先于 close 解析:close 等的正是那条链路的末端。
  2458. expect(settledFirst).toBe(`settled:${runId}`);
  2459. unsubscribe();
  2460. });
  2461. it("关闭之后 submit / amend / resume 抛接线错误(而不是结构化拒绝)", async () => {
  2462. const harness = makeHarness();
  2463. const runId = await submitRun(harness, {
  2464. cwd: TEST_CWD,
  2465. parentSessionId: HARNESS_PARENT_SESSION,
  2466. scriptText: TYPED_SCRIPT,
  2467. trace: traceFor("close-refuses"),
  2468. });
  2469. await settle(harness, runId);
  2470. await harness.service.close();
  2471. await expect(
  2472. harness.service.submit({
  2473. cwd: TEST_CWD,
  2474. parentSessionId: HARNESS_PARENT_SESSION,
  2475. scriptText: TYPED_SCRIPT,
  2476. trace: traceFor("close-refuses-submit"),
  2477. }),
  2478. ).rejects.toThrow(/service is closed/);
  2479. await expect(harness.service.resume!(runId)).rejects.toThrow(/service is closed/);
  2480. await expect(
  2481. harness.service.amend!({
  2482. cwd: TEST_CWD,
  2483. parentSessionId: HARNESS_PARENT_SESSION,
  2484. predecessorRunId: runId,
  2485. scriptText: TYPED_SCRIPT,
  2486. trace: traceFor("close-refuses-amend"),
  2487. }),
  2488. ).rejects.toThrow(/service is closed/);
  2489. });
  2490. it("零在飞 run 时 close 直接解析;第二次 close 返回同一个 promise,不再 abort", async () => {
  2491. const harness = makeHarness();
  2492. const first = harness.service.close();
  2493. const second = harness.service.close();
  2494. // 幂等靠记住 promise,而不是靠再走一遍关闭流程。
  2495. expect(second).toBe(first);
  2496. await first;
  2497. const closing = harness.logs.filter(
  2498. (entry) => entry.context?.event === "dynamic_workflow.service.closing",
  2499. );
  2500. expect(closing).toHaveLength(1);
  2501. expect(closing[0]?.context?.liveRunCount).toBe(0);
  2502. });
  2503. });
  2504. /**
  2505. * 外来终态行(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Engine ownership」规则三)。
  2506. *
  2507. * Bug 根因(2026-09-04 / 2026-09-15):第二个桌面实例冷恢复了同一个会话,它的孤儿收敛在本进程
  2508. * 引擎**仍然活着**的 run 上写下终态行。本进程照单全收:追踪器拿到终态快照、通知模型 run 已
  2509. * 结束、把任务标完,真正的完成随后被丢弃,而行以 completed 收场却还带着那份陈旧失败。
  2510. *
  2511. * 装配用升级问答把 run 停在一个真活着的节点上(escalate 不终止 turn,答完继续干活),
  2512. * 因此同一个 run 既能被观察,也能被放行跑到 completed。
  2513. */
  2514. describe("dynamic workflow run service — 外来终态行(Engine ownership 规则三)", () => {
  2515. const FOREIGN_FAILURE = { code: "Interrupted" as const, message: "owning process exited" };
  2516. /** 起一个 run 并停在升级问答上;回 runId 与 qid。 */
  2517. async function parkedRun(
  2518. harness: Harness,
  2519. name: string,
  2520. ): Promise<{ runId: string; qid: string }> {
  2521. const runId = await submitRun(harness, {
  2522. cwd: TEST_CWD,
  2523. parentSessionId: HARNESS_PARENT_SESSION,
  2524. scriptText: TYPED_SCRIPT,
  2525. trace: traceFor(name),
  2526. });
  2527. await vi.waitFor(async () => {
  2528. expect((await harness.service.getTask(runId))?.pendingQuestions).toHaveLength(1);
  2529. });
  2530. const qid = (await harness.service.getTask(runId))?.pendingQuestions?.[0]?.qid;
  2531. if (qid === undefined) throw new Error("停驻的问题没有出现在快照里");
  2532. return { runId, qid };
  2533. }
  2534. function parkedHarness(answer: string, journal?: JournalStorePort): Harness {
  2535. return makeHarness({
  2536. actorScripts: {
  2537. "actor#1@1": [
  2538. { kind: "escalate", question: "外来写入期间先停在这里" },
  2539. { kind: "submit", result: { text: answer } },
  2540. ],
  2541. },
  2542. ...(journal === undefined ? {} : { journal }),
  2543. });
  2544. }
  2545. // 走真库:四条读面里有两条(listRuns / getRunDetail)靠能力探测接上,替身里没有它们;
  2546. // 而这条用例要证的正是**四条读面同一个答案**。
  2547. it("四条读面都忽略活条目下的外来终态行,警告每个条目只记一次", async () => {
  2548. await withSqliteJournal(async (journal) => {
  2549. const harness = parkedHarness("真正的结果", journal);
  2550. const { runId } = await parkedRun(harness, "foreign-row");
  2551. // 第二个实例的孤儿收敛:直接在 journal 上写终态行,本进程的注册表毫不知情。
  2552. harness.journal.updateRunStatus(runId, "stopped", {
  2553. stopReason: "interrupted",
  2554. failure: FOREIGN_FAILURE,
  2555. });
  2556. expect(harness.journal.getRun(runId)?.status).toBe("stopped");
  2557. // (1) 快照:仍然在跑,三个终态字段一个都不出。
  2558. const snapshot = await harness.service.getTask(runId);
  2559. expect(snapshot?.status).toBe("running");
  2560. expect(snapshot).not.toHaveProperty("runStatus");
  2561. expect(snapshot).not.toHaveProperty("stopReason");
  2562. expect(snapshot).not.toHaveProperty("failure");
  2563. expect(snapshot).not.toHaveProperty("error");
  2564. // (2) 列表与 (3) 详情:与快照同一个答案(三处分叉比三处都错更难查)。
  2565. const introspection = introspectionOf(harness);
  2566. const { runs: listed } = await introspection.listRuns({ cwd: TEST_CWD, limit: 20 });
  2567. const row = listed.find((item) => item.runId === runId);
  2568. expect(row?.status).toBe("running");
  2569. expect(row).not.toHaveProperty("stopReason");
  2570. const detail = await introspection.getRunDetail(runId);
  2571. expect(detail?.status).toBe("running");
  2572. expect(detail).not.toHaveProperty("stopReason");
  2573. expect(detail).not.toHaveProperty("error");
  2574. expect(detail).not.toHaveProperty("result");
  2575. // (4) 会话枚举面(它自己没有注册表,靠 service 把条目递进去)。
  2576. const sessionRows = await harness.service.listRunsForSession(20);
  2577. const sessionRow = sessionRows.find((item) => item.runId === runId);
  2578. expect(sessionRow?.status).toBe("running");
  2579. expect(sessionRow).not.toHaveProperty("stopReason");
  2580. expect(sessionRow).not.toHaveProperty("failureCode");
  2581. expect(sessionRow?.resumable).toBe(false);
  2582. // 留痕但不刷屏:追踪器每秒轮询,警告每个条目只记一次。
  2583. await harness.service.getTask(runId);
  2584. await harness.service.getTask(runId);
  2585. const warns = harness.logs.filter(
  2586. (entry) => entry.context?.event === "dynamic_workflow.run.foreign_terminal_row",
  2587. );
  2588. expect(warns).toHaveLength(1);
  2589. expect(warns[0]?.context).toMatchObject({
  2590. journalStatus: "stopped",
  2591. runId,
  2592. stopReason: "interrupted",
  2593. });
  2594. // 收尾:让 run 真的结束,别把一个在飞引擎留给下一条用例。
  2595. await harness.service.cancel(runId);
  2596. await settle(harness, runId);
  2597. });
  2598. });
  2599. it("引擎自己的结算改写那一行:completed 且不带陈旧失败", async () => {
  2600. const harness = parkedHarness("真正的结果");
  2601. const { runId, qid } = await parkedRun(harness, "foreign-row-then-settle");
  2602. harness.journal.updateRunStatus(runId, "stopped", {
  2603. stopReason: "interrupted",
  2604. failure: FOREIGN_FAILURE,
  2605. });
  2606. // 放行:actor 拿到答案继续干活并提交。
  2607. expect(await harness.service.resolveQuestion(qid, "继续")).toMatchObject({ ok: true });
  2608. await settle(harness, runId);
  2609. const snapshot = await harness.service.getTask(runId);
  2610. expect(snapshot?.status).toBe("completed");
  2611. expect(snapshot?.runStatus).toBe("completed");
  2612. expect(snapshot?.output).toBe("真正的结果");
  2613. expect(snapshot).not.toHaveProperty("failure");
  2614. // 存储侧的另一半(journal 契约的「clears a stale failure…」):completed 的行不带失败。
  2615. const record = harness.journal.getRun(runId);
  2616. expect(record?.status).toBe("completed");
  2617. expect(record?.failure).toBeUndefined();
  2618. expect(record?.stopReason).toBeUndefined();
  2619. });
  2620. it("外来终态行期间 waitForTask 仍然等真正的结算", async () => {
  2621. const harness = parkedHarness("等到了");
  2622. const { runId, qid } = await parkedRun(harness, "foreign-row-wait");
  2623. harness.journal.updateRunStatus(runId, "stopped", {
  2624. stopReason: "interrupted",
  2625. failure: FOREIGN_FAILURE,
  2626. });
  2627. let resolved = false;
  2628. const waiting = harness.service.waitForTask(runId).then((snapshot) => {
  2629. resolved = true;
  2630. return snapshot;
  2631. });
  2632. // 行已经是终态,但等的是条目的结算 promise——它还没有兑现。
  2633. await Promise.resolve();
  2634. expect(resolved).toBe(false);
  2635. expect(await harness.service.resolveQuestion(qid, "继续")).toMatchObject({ ok: true });
  2636. expect((await waiting)?.status).toBe("completed");
  2637. expect(resolved).toBe(true);
  2638. });
  2639. });
  2640. describe("dynamic workflow run service — observation", () => {
  2641. it("未知 run 的 getTask 返回 undefined", async () => {
  2642. const harness = makeHarness();
  2643. expect(await harness.service.getTask("dwfrun-unknown")).toBeUndefined();
  2644. });
  2645. // submit 返回后追踪器会立刻轮询,而 dwf_run 行要等引擎构造。这一刻快照必须是 running,
  2646. // 否则第一次轮询就把刚启动的 run 判成 lost。
  2647. it("submit 刚返回时快照已是 running", async () => {
  2648. const harness = makeHarness({ hangActors: true });
  2649. const runId = await submitRun(harness, {
  2650. cwd: TEST_CWD,
  2651. scriptText: TYPED_SCRIPT,
  2652. trace: traceFor("snapshot-immediate"),
  2653. });
  2654. const snapshot = await harness.service.getTask(runId);
  2655. expect(snapshot?.status).toBe("running");
  2656. expect(snapshot?.runId).toBe(runId);
  2657. await harness.service.cancel(runId);
  2658. await settle(harness, runId);
  2659. });
  2660. // 桌面实测 bug 的重启恢复面:进程重启后注册表为空,快照只能由 journal 记录合成。
  2661. // completed 记录带 result 时必须把它当 output 回出来,否则 TaskOutput 在重启后永远拿不到产物。
  2662. it("重启恢复:注册表为空时 completed 记录的 result 作为 output 回出", async () => {
  2663. const journal = new SweepableJournalStore();
  2664. preloadRun(journal, { runId: "dwfrun-restart", status: "running" });
  2665. journal.updateRunStatus("dwfrun-restart", "completed", {
  2666. result: { report: "final answer", steps: 3 },
  2667. });
  2668. const harness = makeHarness({ journal });
  2669. const snapshot = await harness.service.getTask("dwfrun-restart");
  2670. expect(snapshot?.status).toBe("completed");
  2671. expect(snapshot?.output).toEqual({ report: "final answer", steps: 3 });
  2672. });
  2673. it("重启恢复:非 record 产物(字符串)同样回出", async () => {
  2674. const journal = new SweepableJournalStore();
  2675. preloadRun(journal, { runId: "dwfrun-restart-string", status: "running" });
  2676. journal.updateRunStatus("dwfrun-restart-string", "completed", { result: "plain answer" });
  2677. const harness = makeHarness({ journal });
  2678. expect((await harness.service.getTask("dwfrun-restart-string"))?.output).toBe("plain answer");
  2679. });
  2680. it("重启恢复:completed 但记录无 result 时 output 缺席", async () => {
  2681. const journal = new SweepableJournalStore();
  2682. preloadRun(journal, { runId: "dwfrun-restart-empty", status: "running" });
  2683. journal.updateRunStatus("dwfrun-restart-empty", "completed");
  2684. const harness = makeHarness({ journal });
  2685. const snapshot = await harness.service.getTask("dwfrun-restart-empty");
  2686. expect(snapshot?.status).toBe("completed");
  2687. expect(snapshot && "output" in snapshot).toBe(false);
  2688. });
  2689. it("重启恢复:failed 记录不回 output", async () => {
  2690. const journal = new SweepableJournalStore();
  2691. preloadRun(journal, { runId: "dwfrun-restart-failed", status: "running" });
  2692. journal.updateRunStatus("dwfrun-restart-failed", "errored", {
  2693. failure: { code: "DriverError", message: "script threw" },
  2694. });
  2695. const harness = makeHarness({ journal });
  2696. const snapshot = await harness.service.getTask("dwfrun-restart-failed");
  2697. expect(snapshot?.status).toBe("failed");
  2698. expect(snapshot?.runStatus).toBe("errored");
  2699. expect(snapshot && "output" in snapshot).toBe(false);
  2700. expect(snapshot?.error).toBe("script threw");
  2701. });
  2702. // ── 终态快照携带渐进产物(完成通知的数据源)──
  2703. //
  2704. // 条目取自 journal 的 kind="report" 行,而不是 memory-only 的 workflowRuns 投影:那是这些
  2705. // 条目的持久家,重启后依然在。通知因此在 failed / cancelled 上也能捞回半途的产物。
  2706. function preloadReports(journal: JournalStorePort, runId: string, items: unknown[]): void {
  2707. items.forEach((item, index) => {
  2708. journal.putNode({
  2709. runId,
  2710. siteId: "report#1",
  2711. ordinal: index + 1,
  2712. kind: "report",
  2713. inputHash: `hash-${index}`,
  2714. status: "completed",
  2715. result: item,
  2716. });
  2717. });
  2718. }
  2719. it("终态快照带 journal 里的 report 条目,按报告顺序", async () => {
  2720. const journal = new SweepableJournalStore();
  2721. preloadRun(journal, { runId: "dwfrun-reports", status: "running" });
  2722. preloadReports(journal, "dwfrun-reports", ["first finding", { file: "a.ts" }]);
  2723. journal.updateRunStatus("dwfrun-reports", "completed", { result: "done" });
  2724. const harness = makeHarness({ journal });
  2725. const snapshot = await harness.service.getTask("dwfrun-reports");
  2726. expect(snapshot?.reports).toEqual(["first finding", { file: "a.ts" }]);
  2727. expect(snapshot?.output).toBe("done");
  2728. });
  2729. it("失败与取消的 run 一样带 reports(这条是 report 特性的目的)", async () => {
  2730. for (const [status, taskStatus] of [
  2731. ["errored", "failed"],
  2732. ["stopped", "cancelled"],
  2733. ] as const) {
  2734. const journal = new SweepableJournalStore();
  2735. const runId = `dwfrun-reports-${status}`;
  2736. preloadRun(journal, { runId, status: "running" });
  2737. preloadReports(journal, runId, ["finding before the end"]);
  2738. journal.updateRunStatus(journal.getRun(runId)!.runId, status, {
  2739. ...(status === "stopped" ? { stopReason: "user" as const } : {}),
  2740. failure: { code: "DriverError", message: "boom" },
  2741. });
  2742. const harness = makeHarness({ journal });
  2743. const snapshot = await harness.service.getTask(runId);
  2744. expect(snapshot?.status).toBe(taskStatus);
  2745. expect(snapshot?.runStatus).toBe(status);
  2746. expect(snapshot?.reports).toEqual(["finding before the end"]);
  2747. }
  2748. });
  2749. it("ask / world-read 节点不混进 reports;零条时字段整个缺席", async () => {
  2750. const journal = new SweepableJournalStore();
  2751. preloadRun(journal, { runId: "dwfrun-reports-mixed", status: "running" });
  2752. journal.putNode({
  2753. runId: "dwfrun-reports-mixed",
  2754. siteId: "ask#1",
  2755. ordinal: 1,
  2756. kind: "ask",
  2757. inputHash: "hash-ask",
  2758. status: "completed",
  2759. result: "an ask result, not a report",
  2760. });
  2761. journal.updateRunStatus("dwfrun-reports-mixed", "completed");
  2762. const harness = makeHarness({ journal });
  2763. const snapshot = await harness.service.getTask("dwfrun-reports-mixed");
  2764. expect(snapshot?.status).toBe("completed");
  2765. // 缺席而不是空数组:通知端据此让整节 <reports> 消失,不发空节。
  2766. expect(snapshot && "reports" in snapshot).toBe(false);
  2767. });
  2768. /**
  2769. * 在飞时不读:`getTask` 会被后台追踪器反复轮询,而 `listNodes` 是一次全表扫。唯一的消费者
  2770. * 是终态通知,运行中读它没有读者、只有成本。
  2771. */
  2772. it("running 的快照不读 report 节点(避免每次轮询扫全表)", async () => {
  2773. const journal = new SweepableJournalStore();
  2774. preloadRun(journal, { runId: "dwfrun-reports-running", status: "running" });
  2775. preloadReports(journal, "dwfrun-reports-running", ["mid-run finding"]);
  2776. const harness = makeHarness({ journal });
  2777. const listNodes = vi.spyOn(journal, "listNodes");
  2778. const snapshot = await harness.service.getTask("dwfrun-reports-running");
  2779. expect(snapshot?.status).toBe("running");
  2780. expect(snapshot && "reports" in snapshot).toBe(false);
  2781. expect(listNodes).not.toHaveBeenCalled();
  2782. });
  2783. // 内存终态优先:本进程刚结算的 run 以引擎交回的 artifact 为准,不退回 journal 记录。
  2784. it("内存终态的 artifact 优先于 journal 记录的 result", async () => {
  2785. const journal = new SweepableJournalStore();
  2786. const harness = makeHarness({ journal });
  2787. const runId = await submitRun(harness, {
  2788. cwd: TEST_CWD,
  2789. scriptText: TYPED_SCRIPT,
  2790. trace: traceFor("in-memory-wins"),
  2791. });
  2792. await settle(harness, runId);
  2793. // journal 侧被改写成另一个值;内存终态仍然是权威。
  2794. journal.updateRunStatus(runId, "completed", { result: "journal-side value" });
  2795. const snapshot = await harness.service.getTask(runId);
  2796. expect(snapshot?.status).toBe("completed");
  2797. expect(snapshot?.output).toBe("done");
  2798. });
  2799. it("listEvents 按 cursor 分页且越界返回空页", async () => {
  2800. const harness = makeHarness();
  2801. const runId = await submitRun(harness, {
  2802. cwd: TEST_CWD,
  2803. scriptText: TYPED_SCRIPT,
  2804. trace: traceFor("list-events"),
  2805. });
  2806. await settle(harness, runId);
  2807. const { events: all, hasMore: allHasMore } = await harness.service.listEvents(runId, {});
  2808. expect(allHasMore).toBe(false);
  2809. expect(all.length).toBeGreaterThan(0);
  2810. // sequence 单调,payload 是事件对象去掉 type 后的其余字段。
  2811. expect(all[0]!.type).toBe("run-started");
  2812. expect(all[0]!.payload).toMatchObject({ runId });
  2813. expect(all.map((event) => event.sequence)).toEqual(
  2814. [...all.map((event) => event.sequence)].sort((a, b) => a - b),
  2815. );
  2816. const { events: firstPage, hasMore } = await harness.service.listEvents(runId, { limit: 2 });
  2817. expect(firstPage).toHaveLength(2);
  2818. expect(hasMore).toBe(true);
  2819. const { events: secondPage } = await harness.service.listEvents(runId, {
  2820. afterSequence: firstPage[1]!.sequence,
  2821. limit: 2,
  2822. });
  2823. // 页边界不重不漏。
  2824. expect(secondPage[0]!.sequence).toBeGreaterThan(firstPage[1]!.sequence);
  2825. const beyond = await harness.service.listEvents(runId, {
  2826. afterSequence: all[all.length - 1]!.sequence + 1000,
  2827. });
  2828. expect(beyond).toEqual({ events: [], hasMore: false });
  2829. });
  2830. it("listEvents 不给 limit 时一页 500 条(事件日志从不一次读完)", async () => {
  2831. // docs/execution-engine.md「Reading the journal」:v4 workflowRunEvents 的 limit 是可选的,
  2832. // 缺省曾经意味着整条事件日志一次读完——一个报满 report 的 run 是 GiB 量级的 item。
  2833. const harness = makeHarness();
  2834. const runId = await submitRun(harness, {
  2835. cwd: TEST_CWD,
  2836. scriptText: TYPED_SCRIPT,
  2837. trace: traceFor("list-events-page-cap"),
  2838. });
  2839. await settle(harness, runId);
  2840. for (let i = 0; i < 600; i += 1) {
  2841. harness.journal.appendEvent(runId, { type: "log", message: `line ${i}` });
  2842. }
  2843. const page = await harness.service.listEvents(runId, {});
  2844. expect(page.events).toHaveLength(500);
  2845. expect(page.hasMore).toBe(true);
  2846. // 显式 limit 原样尊重(v4 网关已按 schema 钳过)。
  2847. const asked = await harness.service.listEvents(runId, { limit: 501 });
  2848. expect(asked.events).toHaveLength(501);
  2849. const small = await harness.service.listEvents(runId, { limit: 3 });
  2850. expect(small.events).toHaveLength(3);
  2851. });
  2852. it("journal 能按字节翻页时,listEvents 走它并带上协议的两道缺省界", async () => {
  2853. // 字节界只有 SQLite 的 listEventPage 兑现得了(它从行头读载荷长度,不读载荷);
  2854. // 调用方不给界时,服务按协议上限给全两者,hasMore 原样取存储层的判定。
  2855. const calls: Array<{ afterSequence?: number; limit: number; maxBytes: number }> = [];
  2856. class PagingJournal extends SweepableJournalStore {
  2857. listEventPage(
  2858. runId: string,
  2859. query: { afterSequence?: number; limit: number; maxBytes: number },
  2860. ) {
  2861. calls.push(query);
  2862. const events = this.listEvents(runId, { types: "all", reportItems: "all" }).slice(0, 1);
  2863. return { events, hasMore: true };
  2864. }
  2865. }
  2866. const harness = makeHarness({ journal: new PagingJournal() });
  2867. const runId = await submitRun(harness, {
  2868. cwd: TEST_CWD,
  2869. scriptText: TYPED_SCRIPT,
  2870. trace: traceFor("list-events-byte-pages"),
  2871. });
  2872. await settle(harness, runId);
  2873. const page = await harness.service.listEvents(runId, {});
  2874. expect(calls).toEqual([
  2875. {
  2876. limit: WORKFLOW_RUN_EVENTS_PAGE_LIMITS.maxEvents,
  2877. maxBytes: WORKFLOW_RUN_EVENTS_PAGE_LIMITS.maxBytes,
  2878. },
  2879. ]);
  2880. expect(page.events).toHaveLength(1);
  2881. expect(page.hasMore).toBe(true);
  2882. });
  2883. it("run 事件经 onRunEvent 钩子扇出", async () => {
  2884. const harness = makeHarness();
  2885. const runId = await submitRun(harness, {
  2886. cwd: TEST_CWD,
  2887. scriptText: TYPED_SCRIPT,
  2888. trace: traceFor("run-events"),
  2889. });
  2890. await settle(harness, runId);
  2891. expect(harness.runEvents.every((event) => event.runId === runId)).toBe(true);
  2892. const types = harness.runEvents.map((event) => event.eventType);
  2893. expect(types).toContain("run-started");
  2894. expect(types).toContain("run-settled");
  2895. });
  2896. // ── 进度投影的接缝(docs/dynamic-workflow/presentation.md「The run state the pane draws」)──
  2897. // 钩子交出的是**已经准备好的会话事件载荷**:journal sequence、有界载荷、以及两个
  2898. // Boundary C 上不存在的派生字段。create-app 只负责把它追加到父会话。
  2899. it("钩子携带的 sequence 就是 journal sequence(与 listEvents 同一把尺)", async () => {
  2900. const harness = makeHarness();
  2901. const runId = await submitRun(harness, {
  2902. cwd: TEST_CWD,
  2903. scriptText: TYPED_SCRIPT,
  2904. toolCallId: createToolCallId(),
  2905. trace: traceFor("run-progress-sequence"),
  2906. });
  2907. await settle(harness, runId);
  2908. const { events: journalPage } = await harness.service.listEvents(runId, {});
  2909. // 逐条对齐:同一条事件在两个消费者那里必须是同一个 sequence 与同一个种类。
  2910. expect(harness.runEvents.map((event) => [event.sequence, event.eventType])).toEqual(
  2911. journalPage.map((event) => [event.sequence, event.type]),
  2912. );
  2913. // 单调且从 0 起(appendEvent 的分配语义)。
  2914. expect(harness.runEvents.map((event) => event.sequence)).toEqual(
  2915. harness.runEvents.map((_, index) => index),
  2916. );
  2917. });
  2918. it("actor-created 携带 actor 会话 id,且与 driver 真正使用的那个一致", async () => {
  2919. const harness = makeHarness();
  2920. const runId = await submitRun(harness, {
  2921. cwd: TEST_CWD,
  2922. scriptText: TYPED_SCRIPT,
  2923. trace: traceFor("run-progress-actor"),
  2924. });
  2925. await settle(harness, runId);
  2926. const created = harness.runEvents.find((event) => event.eventType === "actor-created");
  2927. // 这条断言是"确定性铸造"与"driver 实际铸造"之间的绊线:会话 id 是 phase 5 下钻的入口,
  2928. // 两边一旦漂移,详情页会打开一个不存在的会话。
  2929. expect(created?.actorSessionId).toBe(harness.actorRuntimeInputs[0]?.sessionId);
  2930. expect(created?.actorSessionId).toContain(runId);
  2931. });
  2932. it("usage-updated 载荷自带已花 token,且等于 journal 列值(同一同步步骤产生)", async () => {
  2933. const harness = makeHarness();
  2934. const runId = await submitRun(harness, {
  2935. cwd: TEST_CWD,
  2936. scriptText: TYPED_SCRIPT,
  2937. trace: traceFor("run-progress-usage"),
  2938. });
  2939. await settle(harness, runId);
  2940. const usage = harness.runEvents.filter((event) => event.eventType === "usage-updated");
  2941. expect(usage.length).toBeGreaterThan(0);
  2942. const last = usage.at(-1)!;
  2943. // docs/dynamic-workflow/authoring.md「Usage, not budget」:事件载荷与 dwf_run.spent_tokens 永远相等。
  2944. expect(last.payload.spentTokens).toBe(harness.journal.getRun(runId)?.spentTokens);
  2945. expect(last.payload.spentTokens).toBeGreaterThan(0);
  2946. // 不再有派生字段:载荷就是引擎发的原样。
  2947. expect("spentTokens" in last).toBe(false);
  2948. });
  2949. it("载荷有界:超长 persona system prompt 被截断并置 truncated", async () => {
  2950. const harness = makeHarness();
  2951. const longPrompt = "x".repeat(5_000);
  2952. const runId = await submitRun(harness, {
  2953. cwd: TEST_CWD,
  2954. scriptText: [
  2955. "interface Answer { text: string }",
  2956. `const a = await agent("worker", ${JSON.stringify(longPrompt)}).ask<Answer>("go");`,
  2957. "return a.text;",
  2958. ].join("\n"),
  2959. trace: traceFor("run-progress-bounds"),
  2960. });
  2961. await settle(harness, runId);
  2962. const created = harness.runEvents.find((event) => event.eventType === "actor-created");
  2963. const persona = created?.payload.persona as { system?: string } | undefined;
  2964. expect(created?.truncated).toBe(true);
  2965. expect(persona?.system?.length).toBe(DYNAMIC_WORKFLOW_RUN_EVENT_PAYLOAD_LIMITS.maxStringLength);
  2966. // 同一次序列化也喂给 listEvents:两个消费者拿到同一份有界载荷。
  2967. const { events: page } = await harness.service.listEvents(runId, {});
  2968. const pageCreated = page.find((event) => event.type === "actor-created");
  2969. expect((pageCreated?.payload.persona as { system?: string }).system?.length).toBe(
  2970. DYNAMIC_WORKFLOW_RUN_EVENT_PAYLOAD_LIMITS.maxStringLength,
  2971. );
  2972. expect(pageCreated?.truncated).toBe(true);
  2973. });
  2974. it("终态事件永远落地:run-settled 是权威收口", async () => {
  2975. const harness = makeHarness();
  2976. const runId = await submitRun(harness, {
  2977. cwd: TEST_CWD,
  2978. scriptText: TYPED_SCRIPT,
  2979. trace: traceFor("run-progress-terminal"),
  2980. });
  2981. await settle(harness, runId);
  2982. const settled = harness.runEvents.at(-1);
  2983. expect(settled?.eventType).toBe("run-settled");
  2984. expect(settled?.payload.status).toBe("completed");
  2985. });
  2986. it("钩子的 routing 携带 parentSessionId:事件必须落在发起该 run 的会话里", async () => {
  2987. // 身份闸门的另一半在 createDynamicWorkflowRunProgressSink 里;这里证明 run service
  2988. // 真的把身份交了出去(否则闸门只能靠"缺席即本会话"的宽松分支放行,形同没有闸门)。
  2989. const harness = makeHarness();
  2990. const parentSessionId = createSessionId("run-progress-routing-parent");
  2991. const runId = await submitRun(harness, {
  2992. cwd: TEST_CWD,
  2993. parentSessionId,
  2994. scriptText: TYPED_SCRIPT,
  2995. trace: traceFor("run-progress-routing"),
  2996. });
  2997. await settle(harness, runId);
  2998. expect(harness.runEventRoutings.length).toBe(harness.runEvents.length);
  2999. expect(new Set(harness.runEventRoutings.map((routing) => routing.parentSessionId))).toEqual(
  3000. new Set([parentSessionId]),
  3001. );
  3002. });
  3003. it("submit 未带 parentSessionId 时 routing 里就没有它(缺席,不是空串)", async () => {
  3004. const harness = makeHarness();
  3005. const runId = await submitRun(harness, {
  3006. cwd: TEST_CWD,
  3007. scriptText: TYPED_SCRIPT,
  3008. trace: traceFor("run-progress-routing-absent"),
  3009. });
  3010. await settle(harness, runId);
  3011. expect(harness.runEventRoutings.every((routing) => !("parentSessionId" in routing))).toBe(true);
  3012. });
  3013. it("钩子抛错不打挂 run(观察者边界吞异常)", async () => {
  3014. const harness = makeHarness({
  3015. onRunEvent: () => {
  3016. throw new Error("hook blew up");
  3017. },
  3018. });
  3019. const runId = await submitRun(harness, {
  3020. cwd: TEST_CWD,
  3021. scriptText: TYPED_SCRIPT,
  3022. trace: traceFor("run-progress-hook-throws"),
  3023. });
  3024. await settle(harness, runId);
  3025. expect((await harness.service.getTask(runId))?.status).toBe("completed");
  3026. });
  3027. });
  3028. describe("dynamic workflow run service — 孤儿 run 收敛", () => {
  3029. // 桌面实测 bug(2026-08-19,dwfrun-734d1f9d):run-started 之后进程被关掉,dwf_run 行
  3030. // **永远停在 running**——getTask/waitForTask 对不在本进程注册表里的 run 直接回 journal
  3031. // 快照,于是恢复会话后每个 journal 读面都被告知「还在跑」,永不自愈。收敛的时机是下一次
  3032. // 这个父会话的 app 构造:那一刻本服务实例名下零个在飞 run,journal 里本会话的任何非终态行
  3033. // 都只可能是死进程的遗物。
  3034. it("构造时把本会话的非终态 run 收敛成 failed(interrupted 编码)", () => {
  3035. const journal = new SweepableJournalStore();
  3036. preloadRun(journal, {
  3037. parentSessionId: HARNESS_PARENT_SESSION,
  3038. runId: "dwfrun-orphan-running",
  3039. status: "running",
  3040. });
  3041. preloadRun(journal, {
  3042. parentSessionId: HARNESS_PARENT_SESSION,
  3043. runId: "dwfrun-orphan-pending",
  3044. status: "pending",
  3045. });
  3046. makeHarness({ journal });
  3047. for (const runId of ["dwfrun-orphan-running", "dwfrun-orphan-pending"]) {
  3048. const record = journal.getRun(runId);
  3049. expect(record?.status).toBe("stopped");
  3050. expect(record?.stopReason).toBe("interrupted");
  3051. // 失败编码沿用引擎的 WorkflowErrorJson 形态,且 code 必须同时区别于「脚本真失败」
  3052. // (harness 把脚本抛错编码成 DriverError)与「用户取消」(stopped(user),可 resume)。
  3053. expect(record?.failure?.code).toBe("Interrupted");
  3054. expect(record?.failure?.message).toContain(runId);
  3055. }
  3056. });
  3057. it("每个被收敛的 run 记一条 warn(带 runId)", () => {
  3058. const journal = new SweepableJournalStore();
  3059. preloadRun(journal, {
  3060. parentSessionId: HARNESS_PARENT_SESSION,
  3061. runId: "dwfrun-orphan-logged",
  3062. status: "running",
  3063. });
  3064. const harness = makeHarness({ journal });
  3065. const warnings = harness.logs.filter(
  3066. (entry) => entry.level === "warn" && entry.context?.runId === "dwfrun-orphan-logged",
  3067. );
  3068. expect(warnings).toHaveLength(1);
  3069. });
  3070. it("本会话的终态 run 一律不动", () => {
  3071. const journal = new SweepableJournalStore();
  3072. for (const status of ["completed", "errored", "stopped"] as const) {
  3073. preloadRun(journal, {
  3074. parentSessionId: HARNESS_PARENT_SESSION,
  3075. runId: `dwfrun-terminal-${status}`,
  3076. status,
  3077. });
  3078. }
  3079. makeHarness({ journal });
  3080. for (const status of ["completed", "errored", "stopped"] as const) {
  3081. const record = journal.getRun(`dwfrun-terminal-${status}`);
  3082. expect(record?.status).toBe(status);
  3083. // 终态行连失败原因都不许被补写:stopped 是「用户取消、可 resume」,不是 interrupted。
  3084. expect(record?.failure).toBeUndefined();
  3085. }
  3086. });
  3087. // 绝不全局清扫:run service 是 per-app(= per 父会话)构造的,同进程兄弟会话各有各的
  3088. // 内存注册表、共用同一个 sqlite。不带 parentSessionId 的清扫会把别的会话**正在飞**的 run
  3089. // 标死。父会话缺席的行同理不属于本会话。
  3090. it("别的会话(以及无父会话)的非终态 run 不动", () => {
  3091. const journal = new SweepableJournalStore();
  3092. preloadRun(journal, {
  3093. parentSessionId: createSessionId("sibling-session"),
  3094. runId: "dwfrun-sibling-live",
  3095. status: "running",
  3096. });
  3097. preloadRun(journal, { runId: "dwfrun-orphaned-parentless", status: "running" });
  3098. makeHarness({ journal });
  3099. expect(journal.getRun("dwfrun-sibling-live")?.status).toBe("running");
  3100. expect(journal.getRun("dwfrun-orphaned-parentless")?.status).toBe("running");
  3101. });
  3102. it("构造后 submit 的 run 不受收敛影响", async () => {
  3103. const journal = new SweepableJournalStore();
  3104. preloadRun(journal, {
  3105. parentSessionId: HARNESS_PARENT_SESSION,
  3106. runId: "dwfrun-orphan-before-submit",
  3107. status: "running",
  3108. });
  3109. const harness = makeHarness({ journal });
  3110. const runId = await submitRun(harness, {
  3111. cwd: TEST_CWD,
  3112. parentSessionId: HARNESS_PARENT_SESSION,
  3113. scriptText: TYPED_SCRIPT,
  3114. trace: traceFor("sweep-then-submit"),
  3115. });
  3116. await settle(harness, runId);
  3117. expect((await harness.service.getTask(runId))?.status).toBe("completed");
  3118. expect(journal.getRun(runId)?.failure).toBeUndefined();
  3119. expect(journal.getRun("dwfrun-orphan-before-submit")?.status).toBe("stopped");
  3120. });
  3121. // 这条就是 bug 的用户可见面:journal 快照回什么,恢复会话后的 TaskOutput 就显示什么。
  3122. it("getTask 对被收敛的 run 回 stopped(interrupted) 并带失败原因", async () => {
  3123. const journal = new SweepableJournalStore();
  3124. preloadRun(journal, {
  3125. parentSessionId: HARNESS_PARENT_SESSION,
  3126. runId: "dwfrun-orphan-snapshot",
  3127. status: "running",
  3128. });
  3129. const harness = makeHarness({ journal });
  3130. const snapshot = await harness.service.getTask("dwfrun-orphan-snapshot");
  3131. // 追踪器词汇:stopped → cancelled;真实词与原因在 runStatus / stopReason 上。
  3132. expect(snapshot?.status).toBe("cancelled");
  3133. expect(snapshot?.runStatus).toBe("stopped");
  3134. expect(snapshot?.stopReason).toBe("interrupted");
  3135. expect(snapshot?.failure?.code).toBe("Interrupted");
  3136. expect(snapshot?.error).toContain("dwfrun-orphan-snapshot");
  3137. });
  3138. // 不合成 dwf_event:事件日志的契约是「引擎发过什么」,状态权威在 run 行上。
  3139. // run-settled 是引擎的收口,不是清扫者的。
  3140. it("收敛不给事件日志添任何一条事件", async () => {
  3141. const journal = new SweepableJournalStore();
  3142. preloadRun(journal, {
  3143. parentSessionId: HARNESS_PARENT_SESSION,
  3144. runId: "dwfrun-orphan-events",
  3145. status: "running",
  3146. });
  3147. journal.appendEvent("dwfrun-orphan-events", {
  3148. caps: { maxConcurrency: 4 },
  3149. runId: "dwfrun-orphan-events",
  3150. type: "run-started",
  3151. });
  3152. const harness = makeHarness({ journal });
  3153. const { events } = await harness.service.listEvents("dwfrun-orphan-events", {});
  3154. expect(events.map((event) => event.type)).toEqual(["run-started"]);
  3155. });
  3156. it("二次构造幂等:没有可收敛项时一次写入都没有", () => {
  3157. const journal = new SweepableJournalStore();
  3158. preloadRun(journal, {
  3159. parentSessionId: HARNESS_PARENT_SESSION,
  3160. runId: "dwfrun-orphan-idempotent",
  3161. status: "running",
  3162. });
  3163. makeHarness({ journal });
  3164. expect(journal.getRun("dwfrun-orphan-idempotent")?.status).toBe("stopped");
  3165. const updateRunStatus = vi.spyOn(journal, "updateRunStatus");
  3166. makeHarness({ journal });
  3167. expect(updateRunStatus).not.toHaveBeenCalled();
  3168. });
  3169. // journal 实现不带窄查询时不能崩、也不能假装收敛过:跳过并记下原因(可见降级)。
  3170. it("journal 不带窄查询时跳过收敛并记原因", () => {
  3171. const journal = new InMemoryJournalStore();
  3172. preloadRun(journal, {
  3173. parentSessionId: HARNESS_PARENT_SESSION,
  3174. runId: "dwfrun-no-query",
  3175. status: "running",
  3176. });
  3177. const harness = makeHarness({ journal });
  3178. expect(journal.getRun("dwfrun-no-query")?.status).toBe("running");
  3179. expect(
  3180. harness.logs.some((entry) => JSON.stringify(entry.context ?? {}).includes("non_terminal")),
  3181. ).toBe(true);
  3182. });
  3183. // 生产接线的绊线。窄查询是**能力探测**出来的(它不在引擎的 JournalStorePort 上),所以
  3184. // 方法名或签名一旦漂移,不会有任何编译错误——只会让收敛静默跳过,退回「孤儿 run 永远
  3185. // running」那个 bug。这条用例因此走真实的 sqlite session store,即生产那条
  3186. // resolveDynamicWorkflowJournalStore 路径。
  3187. it("真实 sqlite journal 上收敛生效,且只碰本会话", async () => {
  3188. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-sweep-"));
  3189. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  3190. try {
  3191. const journal = resolveDynamicWorkflowJournalStore(store as never);
  3192. expect(journal).toBeDefined();
  3193. preloadRun(journal!, {
  3194. parentSessionId: HARNESS_PARENT_SESSION,
  3195. runId: "dwfrun-sqlite-orphan",
  3196. status: "running",
  3197. });
  3198. preloadRun(journal!, {
  3199. parentSessionId: createSessionId("sqlite-sibling"),
  3200. runId: "dwfrun-sqlite-sibling",
  3201. status: "running",
  3202. });
  3203. journal!.appendEvent("dwfrun-sqlite-orphan", {
  3204. caps: { maxConcurrency: 4 },
  3205. runId: "dwfrun-sqlite-orphan",
  3206. type: "run-started",
  3207. });
  3208. const harness = makeHarness({ journal: journal! });
  3209. const reconciled = journal!.getRun("dwfrun-sqlite-orphan");
  3210. expect(reconciled?.status).toBe("stopped");
  3211. expect(reconciled?.stopReason).toBe("interrupted");
  3212. expect(reconciled?.failure?.code).toBe("Interrupted");
  3213. expect(journal!.getRun("dwfrun-sqlite-sibling")?.status).toBe("running");
  3214. // 状态权威在 run 行上,事件日志仍然只有引擎发过的那一条。
  3215. expect((await harness.service.listEvents("dwfrun-sqlite-orphan", {})).events).toHaveLength(1);
  3216. } finally {
  3217. store.close();
  3218. await rm(tempRoot, { force: true, recursive: true });
  3219. }
  3220. });
  3221. });
  3222. // ————————————————————————————————————————————————————————————————
  3223. // run 内省(listRuns / getRunDetail)
  3224. // 见 docs/dynamic-workflow/launch.md
  3225. // ————————————————————————————————————————————————————————————————
  3226. /**
  3227. * 本项目的 cwd 与"别的项目"的 cwd(cwd 是字面等值匹配的项目键)。
  3228. *
  3229. * 必须是**真实存在的目录**:真跑起来的 run 会以它作为沙箱子进程的 cwd,不存在的路径让
  3230. * spawn 直接失败、run 结算 failed——那时被测的就不是真相合成了。(这一条是写这些用例时
  3231. * 真实踩到的:原先用两个字面量假路径,在飞用例里的 run 全部变成 failed。)
  3232. */
  3233. let projectCwd = "";
  3234. let otherCwd = "";
  3235. let introspectCwdRoot = "";
  3236. beforeAll(async () => {
  3237. introspectCwdRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-cwd-"));
  3238. projectCwd = join(introspectCwdRoot, "project");
  3239. otherCwd = join(introspectCwdRoot, "other");
  3240. await mkdir(projectCwd, { recursive: true });
  3241. await mkdir(otherCwd, { recursive: true });
  3242. });
  3243. afterAll(async () => {
  3244. await rm(introspectCwdRoot, { force: true, recursive: true });
  3245. });
  3246. /**
  3247. * 真实 sqlite journal 上跑内省用例。
  3248. *
  3249. * 这一族**必须走真库**:四条内省查询不在引擎的 JournalStorePort 上,是靠能力探测接上的,
  3250. * 在替身里用 JS 重写它们等于把被测语义换成复制品——而漂移的症状恰恰是「能力静默缺席」或
  3251. * 「计数/尾巴看起来对但 SQL 是另一回事」。查询自身的语义(cwd 下推、排序、limit 钳制)在
  3252. * `adapters/tests/dwf-journal-store.test.ts` 里对真库钉住;这里钉的是 service 侧的**真相合成**。
  3253. */
  3254. async function withSqliteJournal(
  3255. run: (journal: JournalStorePort & DwfRunIntrospectionQueries) => Promise<void>,
  3256. ): Promise<void> {
  3257. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-introspect-"));
  3258. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  3259. try {
  3260. const journal = resolveDynamicWorkflowJournalStore(store as never);
  3261. expect(journal).toBeDefined();
  3262. await run(journal as JournalStorePort & DwfRunIntrospectionQueries);
  3263. } finally {
  3264. store.close();
  3265. await rm(tempRoot, { force: true, recursive: true });
  3266. }
  3267. }
  3268. /** 端口的两个可选成员:能力在场时必须实现,缺席即用例失败(而不是静默跳过断言)。 */
  3269. function introspectionOf(harness: Harness): {
  3270. getRunDetail: (runId: string) => Promise<DynamicWorkflowRunDetail | undefined>;
  3271. listRuns: (query: DynamicWorkflowRunListQuery) => Promise<DynamicWorkflowRunListResult>;
  3272. } {
  3273. const { getRunDetail, listRuns } = harness.service;
  3274. return { getRunDetail: getRunDetail!, listRuns: listRuns! };
  3275. }
  3276. /**
  3277. * 把若干 runId 从**读面**藏起来的转发层:模拟 submit → createRun 的微任务间隙(注册表已有
  3278. * 条目、journal 还没有行)。
  3279. *
  3280. * 为什么是"藏读"而不是"扣住写":dwf_event / dwf_node 都对 dwf_run(id) 有 FK,真扣住 createRun
  3281. * 会让引擎的第一条 run-started 事件插入失败、run 直接变成 failed——那测的就不是间隙了。藏读
  3282. * 造出的正是间隙里 service 能看到的状态:注册表命中、`getRun` 与 `listRuns` 都不认识它。
  3283. *
  3284. * 逐方法显式转发(不用展开):两个 journal 实现都是 class,`{...journal}` 只拷自有属性,
  3285. * 原型上的方法会全部丢掉(createJournalSequenceCapture 的同一条论证)。
  3286. */
  3287. function hideRunsFromReads(
  3288. journal: JournalStorePort & DwfRunIntrospectionQueries,
  3289. hidden: ReadonlySet<string>,
  3290. ): JournalStorePort & DwfRunIntrospectionQueries {
  3291. return {
  3292. createRun: (record) => journal.createRun(record),
  3293. getRun: (runId) => (hidden.has(runId) ? undefined : journal.getRun(runId)),
  3294. updateRunStatus: (runId, status, settlement) =>
  3295. journal.updateRunStatus(runId, status, settlement),
  3296. updateRunUsage: (runId, spentTokens) => journal.updateRunUsage(runId, spentTokens),
  3297. updateRunCaps: (runId, caps) => journal.updateRunCaps(runId, caps),
  3298. putActor: (record) => journal.putActor(record),
  3299. getActor: (runId, siteId, ordinal) => journal.getActor(runId, siteId, ordinal),
  3300. listActors: (runId, opts) => journal.listActors(runId, opts),
  3301. putNode: (record) => journal.putNode(record),
  3302. getNode: (runId, siteId, ordinal, opts) => journal.getNode(runId, siteId, ordinal, opts),
  3303. listNodes: (runId, opts) => journal.listNodes(runId, opts),
  3304. countNodes: (runId, kind) => journal.countNodes(runId, kind),
  3305. appendEvent: (runId, event) => journal.appendEvent(runId, event),
  3306. listEvents: (runId, opts) => journal.listEvents(runId, opts),
  3307. countNodesByStatus: (runId) => journal.countNodesByStatus(runId),
  3308. getRunRow: (runId) => (hidden.has(runId) ? undefined : journal.getRunRow(runId)),
  3309. listRecentLogEvents: (runId, limit) => journal.listRecentLogEvents(runId, limit),
  3310. listRuns: (query) => journal.listRuns(query).filter((row) => !hidden.has(row.runId)),
  3311. // 产物读面(迁移 0029 之后 DwfRunIntrospectionQueries 的两条新查询)。这里必须**逐条
  3312. // 转发**而不能展开 `...journal`:两个 journal 实现都是 class,展开只拷自有属性、原型上的
  3313. // 方法会整片丢掉。hidden 不参与——这个替身只藏 run 行,产物按 runId 取数,被藏的 run
  3314. // 本就取不到自己的行。
  3315. listArtifactRows: (runId) => journal.listArtifactRows(runId),
  3316. countTaggedReports: (runId) => journal.countTaggedReports(runId),
  3317. listArtifactItems: (runId, artifactId, query) =>
  3318. journal.listArtifactItems(runId, artifactId, query),
  3319. listEventPage: (runId, query) => journal.listEventPage(runId, query),
  3320. };
  3321. }
  3322. describe("dynamic workflow run service — run name 落库", () => {
  3323. // input.name 此前只活在工具行与任务标题的兜底链上,不落 dwf_run,于是跨会话枚举出来的
  3324. // run 只能是一串裸 runId。这条钉的是 submit → EngineConfig → createRun 的整条路。
  3325. it("submit 带 name → dwf_run.name 落库", async () => {
  3326. const harness = makeHarness();
  3327. const runId = await submitRun(harness, {
  3328. cwd: TEST_CWD,
  3329. name: "nightly triage",
  3330. scriptText: TYPED_SCRIPT,
  3331. trace: traceFor("submit-name"),
  3332. });
  3333. await settle(harness, runId);
  3334. expect(harness.journal.getRun(runId)?.name).toBe("nightly triage");
  3335. });
  3336. it("未命名的 submit 不写 name(键缺席,读侧走脚本首行兜底)", async () => {
  3337. const harness = makeHarness();
  3338. const runId = await submitRun(harness, {
  3339. cwd: TEST_CWD,
  3340. scriptText: TYPED_SCRIPT,
  3341. trace: traceFor("submit-no-name"),
  3342. });
  3343. await settle(harness, runId);
  3344. expect("name" in harness.journal.getRun(runId)!).toBe(false);
  3345. });
  3346. });
  3347. describe("dynamic workflow run service — 内省能力探测", () => {
  3348. // 「没有 run」与「没有能力」必须可分辨:journal 不带内省查询时两个可选成员**整个缺席**,
  3349. // 工具层的 typeof 探测据此回业务失败,而不是一个看起来"这个项目没跑过 workflow"的空列表。
  3350. it("journal 不带内省查询时两个可选成员缺席", () => {
  3351. const harness = makeHarness({ journal: new InMemoryJournalStore() });
  3352. expect(harness.service.listRuns).toBeUndefined();
  3353. expect(harness.service.getRunDetail).toBeUndefined();
  3354. });
  3355. });
  3356. describe("dynamic workflow run service — listRuns 真相合成", () => {
  3357. it("本会话在飞的 run:running、归本会话、不标 possiblyInterrupted", async () => {
  3358. await withSqliteJournal(async (journal) => {
  3359. const harness = makeHarness({ hangActors: true, journal });
  3360. const runId = await submitRun(harness, {
  3361. cwd: projectCwd,
  3362. name: "in flight",
  3363. parentSessionId: HARNESS_PARENT_SESSION,
  3364. scriptText: TYPED_SCRIPT,
  3365. trace: traceFor("list-in-flight"),
  3366. });
  3367. await vi.waitFor(() => {
  3368. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  3369. });
  3370. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3371. expect(runs).toHaveLength(1);
  3372. expect(runs[0]).toMatchObject({
  3373. label: "in flight",
  3374. labelSource: "name",
  3375. ownedByThisSession: true,
  3376. runId,
  3377. status: "running",
  3378. });
  3379. // 在飞的 run 绝不能被标成「可能已中断」——那是列表面对模型说谎的第一种方式。
  3380. expect("possiblyInterrupted" in runs[0]!).toBe(false);
  3381. await harness.service.cancel(runId);
  3382. await settle(harness, runId);
  3383. });
  3384. });
  3385. // 注册表命中即归属,**哪怕 journal 行记着另一个会话**。这一档正是 possiblyInterrupted 不该
  3386. // 误标的那一档:同进程的兄弟会话共用一个 sqlite,各有各的注册表。
  3387. it("注册表命中即归本会话,即使 journal 行记的是别的会话", async () => {
  3388. await withSqliteJournal(async (journal) => {
  3389. const harness = makeHarness({ hangActors: true, journal });
  3390. const runId = await submitRun(harness, {
  3391. cwd: projectCwd,
  3392. parentSessionId: createSessionId("some-other-session"),
  3393. scriptText: TYPED_SCRIPT,
  3394. trace: traceFor("list-registry-owned"),
  3395. });
  3396. await vi.waitFor(() => {
  3397. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  3398. });
  3399. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3400. expect(runs[0]).toMatchObject({ ownedByThisSession: true, runId, status: "running" });
  3401. expect("possiblyInterrupted" in runs[0]!).toBe(false);
  3402. await harness.service.cancel(runId);
  3403. await settle(harness, runId);
  3404. });
  3405. });
  3406. // 状态优先级的第一档:内存终态 > journal 状态。内存里的结算是本进程刚从引擎手里接过的,
  3407. // journal 行可能还没写完(或被别的东西改过)。
  3408. it("内存终态优先于 journal 状态", async () => {
  3409. await withSqliteJournal(async (journal) => {
  3410. const harness = makeHarness({ journal });
  3411. const runId = await submitRun(harness, {
  3412. cwd: projectCwd,
  3413. parentSessionId: HARNESS_PARENT_SESSION,
  3414. scriptText: TYPED_SCRIPT,
  3415. trace: traceFor("list-memory-wins"),
  3416. });
  3417. await settle(harness, runId);
  3418. // 人为把 journal 行拨回非终态,制造两个真相源的分歧。
  3419. journal.updateRunStatus(runId, "running");
  3420. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3421. expect(runs[0]).toMatchObject({ runId, status: "completed" });
  3422. // 归本会话 + 有内存终态 ⇒ 无论 journal 说什么都不该带这个疑虑。
  3423. expect("possiblyInterrupted" in runs[0]!).toBe(false);
  3424. });
  3425. });
  3426. it("他会话的非终态 run 标 possiblyInterrupted 且不归本会话", async () => {
  3427. await withSqliteJournal(async (journal) => {
  3428. const harness = makeHarness({ journal });
  3429. preloadRun(journal, {
  3430. cwd: projectCwd,
  3431. parentSessionId: createSessionId("sibling-session"),
  3432. runId: "dwfrun-sibling-running",
  3433. status: "running",
  3434. });
  3435. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3436. expect(runs[0]).toMatchObject({
  3437. ownedByThisSession: false,
  3438. possiblyInterrupted: true,
  3439. runId: "dwfrun-sibling-running",
  3440. status: "running",
  3441. });
  3442. // 只标注、绝不改写:journal 行必须还是 running(替兄弟会话在飞的 run 收尸 = 把活着的
  3443. // run 标死;孤儿收敛的执行权只属于 owning 会话的构造时刻)。
  3444. expect(journal.getRun("dwfrun-sibling-running")?.status).toBe("running");
  3445. });
  3446. });
  3447. it("他会话的终态 run 不标 possiblyInterrupted", async () => {
  3448. await withSqliteJournal(async (journal) => {
  3449. const harness = makeHarness({ journal });
  3450. for (const status of ["completed", "errored", "stopped"] as const) {
  3451. preloadRun(journal, {
  3452. cwd: projectCwd,
  3453. parentSessionId: createSessionId("sibling-session"),
  3454. runId: `dwfrun-sibling-${status}`,
  3455. status,
  3456. ...(status === "stopped" ? { stopReason: "user" as const } : {}),
  3457. });
  3458. }
  3459. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3460. expect(runs).toHaveLength(3);
  3461. for (const item of runs) {
  3462. expect(item.ownedByThisSession).toBe(false);
  3463. expect("possiblyInterrupted" in item).toBe(false);
  3464. }
  3465. });
  3466. });
  3467. it("别的项目的 run 不可见(cwd 是字面等值的项目键)", async () => {
  3468. await withSqliteJournal(async (journal) => {
  3469. const harness = makeHarness({ journal });
  3470. preloadRun(journal, {
  3471. cwd: projectCwd,
  3472. runId: "dwfrun-here",
  3473. status: "completed",
  3474. });
  3475. preloadRun(journal, {
  3476. cwd: otherCwd,
  3477. runId: "dwfrun-elsewhere",
  3478. status: "completed",
  3479. });
  3480. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3481. expect(runs.map((item) => item.runId)).toEqual(["dwfrun-here"]);
  3482. });
  3483. });
  3484. it("statuses 过滤与 limit 都下推到查询", async () => {
  3485. await withSqliteJournal(async (journal) => {
  3486. const harness = makeHarness({ journal });
  3487. for (const status of ["completed", "errored"] as const) {
  3488. preloadRun(journal, { cwd: projectCwd, runId: `dwfrun-${status}`, status });
  3489. }
  3490. const introspection = introspectionOf(harness);
  3491. const filtered = await introspection.listRuns({
  3492. cwd: projectCwd,
  3493. limit: 20,
  3494. statuses: ["errored"],
  3495. });
  3496. expect(filtered.runs.map((item) => item.runId)).toEqual(["dwfrun-errored"]);
  3497. const limited = await introspection.listRuns({ cwd: projectCwd, limit: 1 });
  3498. expect(limited.runs).toHaveLength(1);
  3499. });
  3500. });
  3501. // truncated 的判据是「多取一条」而不是「取满 limit」:后者在条数正好等于 limit 时误报,
  3502. // 而误报会让模型去追一页不存在的历史。
  3503. describe("truncated", () => {
  3504. it("为真当且仅当还有 run 没进这一页", async () => {
  3505. await withSqliteJournal(async (journal) => {
  3506. const harness = makeHarness({ journal });
  3507. for (const index of [1, 2, 3]) {
  3508. preloadRun(journal, {
  3509. cwd: projectCwd,
  3510. runId: `dwfrun-page-${index}`,
  3511. status: "completed",
  3512. });
  3513. }
  3514. const introspection = introspectionOf(harness);
  3515. const firstPage = await introspection.listRuns({ cwd: projectCwd, limit: 2 });
  3516. expect(firstPage.runs).toHaveLength(2);
  3517. expect(firstPage.truncated).toBe(true);
  3518. // 条数正好等于 limit:一条都没落下,所以字段整个缺席(不是 false)。
  3519. const exactPage = await introspection.listRuns({ cwd: projectCwd, limit: 3 });
  3520. expect(exactPage.runs).toHaveLength(3);
  3521. expect("truncated" in exactPage).toBe(false);
  3522. const roomyPage = await introspection.listRuns({ cwd: projectCwd, limit: 20 });
  3523. expect("truncated" in roomyPage).toBe(false);
  3524. });
  3525. });
  3526. /**
  3527. * 钳制上限那一页。这条看着像是上一条的重复,其实钉的是一个别处测不到的耦合:truncated
  3528. * 的判定依赖存储查询接受「上限 + 1」。若将来有人在 SqliteDwfJournalStore.listRuns 里加一个
  3529. * `Math.min(50, limit)` 的防御性天花板,探测行会被吃掉,truncated 就在**恰好** limit = 50
  3530. * 时永久缺席——而 2 / 3 / 20 的边界用例一个都不会失败。上限取自契约常量,工具面调高上限
  3531. * 时这条用例自动跟着走。
  3532. */
  3533. it("在钳制上限那一页仍然标 truncated(探测行必须能过存储层)", async () => {
  3534. await withSqliteJournal(async (journal) => {
  3535. const harness = makeHarness({ journal });
  3536. const overflow = LIST_WORKFLOW_RUNS_MAX_LIMIT + 1;
  3537. for (let index = 0; index < overflow; index += 1) {
  3538. preloadRun(journal, {
  3539. cwd: projectCwd,
  3540. runId: `dwfrun-max-${String(index).padStart(3, "0")}`,
  3541. status: "completed",
  3542. });
  3543. }
  3544. const page = await introspectionOf(harness).listRuns({
  3545. cwd: projectCwd,
  3546. limit: LIST_WORKFLOW_RUNS_MAX_LIMIT,
  3547. });
  3548. expect(page.runs).toHaveLength(LIST_WORKFLOW_RUNS_MAX_LIMIT);
  3549. expect(page.truncated).toBe(true);
  3550. });
  3551. });
  3552. it("空项目与被 statuses 过滤空的页都不标 truncated", async () => {
  3553. await withSqliteJournal(async (journal) => {
  3554. const harness = makeHarness({ journal });
  3555. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-only", status: "completed" });
  3556. const introspection = introspectionOf(harness);
  3557. expect(await introspection.listRuns({ cwd: otherCwd, limit: 20 })).toEqual({ runs: [] });
  3558. expect(
  3559. await introspection.listRuns({ cwd: projectCwd, limit: 20, statuses: ["errored"] }),
  3560. ).toEqual({ runs: [] });
  3561. });
  3562. });
  3563. // 补集也算在页内:间隙里的 run 顶掉最旧的 journal 行时,被顶掉的那条就是「还有更多」。
  3564. it("注册表补集把 journal 行挤出页时标 truncated", async () => {
  3565. await withSqliteJournal(async (real) => {
  3566. const hidden = new Set<string>();
  3567. const journal = hideRunsFromReads(real, hidden);
  3568. const harness = makeHarness({ hangActors: true, journal });
  3569. preloadRun(real, { cwd: projectCwd, runId: "dwfrun-older", status: "completed" });
  3570. const runId = await submitRun(harness, {
  3571. cwd: projectCwd,
  3572. parentSessionId: HARNESS_PARENT_SESSION,
  3573. scriptText: TYPED_SCRIPT,
  3574. trace: traceFor("gap-truncates"),
  3575. });
  3576. hidden.add(runId);
  3577. const page = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 1 });
  3578. expect(page.runs.map((item) => item.runId)).toEqual([runId]);
  3579. expect(page.truncated).toBe(true);
  3580. await harness.service.cancel(runId);
  3581. await settle(harness, runId);
  3582. });
  3583. });
  3584. });
  3585. it("label 兜底:无 name 的老行取脚本首个非空行", async () => {
  3586. await withSqliteJournal(async (journal) => {
  3587. const harness = makeHarness({ journal });
  3588. preloadRun(journal, {
  3589. cwd: projectCwd,
  3590. runId: "dwfrun-unnamed",
  3591. scriptText: "\n // triage the failing tests\nreturn 1;",
  3592. status: "completed",
  3593. });
  3594. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3595. expect(runs[0]).toMatchObject({
  3596. label: "// triage the failing tests",
  3597. labelSource: "script",
  3598. });
  3599. // 读时派生,绝不回写:落库等于把一个展示启发式固化成数据。
  3600. expect("name" in journal.getRun("dwfrun-unnamed")!).toBe(false);
  3601. });
  3602. });
  3603. // 只读不变式的正面断言:两条读面之后 journal 上一次写入都没有发生过。
  3604. it("合成过程不写 journal(写入面零调用、行逐字段不变)", async () => {
  3605. await withSqliteJournal(async (journal) => {
  3606. const harness = makeHarness({ journal });
  3607. preloadRun(journal, {
  3608. cwd: projectCwd,
  3609. parentSessionId: createSessionId("sibling-session"),
  3610. runId: "dwfrun-readonly",
  3611. status: "running",
  3612. });
  3613. const before = journal.getRun("dwfrun-readonly");
  3614. const createRun = vi.spyOn(journal, "createRun");
  3615. const updateRunStatus = vi.spyOn(journal, "updateRunStatus");
  3616. const updateRunUsage = vi.spyOn(journal, "updateRunUsage");
  3617. const appendEvent = vi.spyOn(journal, "appendEvent");
  3618. const putNode = vi.spyOn(journal, "putNode");
  3619. const putActor = vi.spyOn(journal, "putActor");
  3620. const introspection = introspectionOf(harness);
  3621. await introspection.listRuns({ cwd: projectCwd, limit: 20 });
  3622. await introspection.getRunDetail("dwfrun-readonly");
  3623. for (const spy of [
  3624. createRun,
  3625. updateRunStatus,
  3626. updateRunUsage,
  3627. appendEvent,
  3628. putNode,
  3629. putActor,
  3630. ]) {
  3631. expect(spy).not.toHaveBeenCalled();
  3632. }
  3633. expect(journal.getRun("dwfrun-readonly")).toEqual(before);
  3634. });
  3635. });
  3636. });
  3637. describe("dynamic workflow run service — submit → createRun 的间隙", () => {
  3638. // journal 尚无行的 run 必须以 pending 出现在列表里:少了这一支,模型刚起的 run 会在自己
  3639. // 项目的列表里整个消失(而它明明刚拿到 runId)。
  3640. it("注册表-only 的 run 以 pending 附加,且排在 journal 行之前", async () => {
  3641. await withSqliteJournal(async (real) => {
  3642. const hidden = new Set<string>();
  3643. const journal = hideRunsFromReads(real, hidden);
  3644. const harness = makeHarness({ hangActors: true, journal });
  3645. preloadRun(real, {
  3646. cwd: projectCwd,
  3647. parentSessionId: createSessionId("sibling-session"),
  3648. runId: "dwfrun-already-journaled",
  3649. status: "completed",
  3650. });
  3651. const runId = await submitRun(harness, {
  3652. cwd: projectCwd,
  3653. name: "just submitted",
  3654. parentSessionId: HARNESS_PARENT_SESSION,
  3655. scriptText: TYPED_SCRIPT,
  3656. trace: traceFor("list-gap"),
  3657. });
  3658. hidden.add(runId);
  3659. const { runs } = await introspectionOf(harness).listRuns({ cwd: projectCwd, limit: 20 });
  3660. expect(runs.map((item) => item.runId)).toEqual([runId, "dwfrun-already-journaled"]);
  3661. expect(runs[0]).toMatchObject({
  3662. label: "just submitted",
  3663. labelSource: "name",
  3664. ownedByThisSession: true,
  3665. spentTokens: 0,
  3666. status: "pending",
  3667. });
  3668. expect("possiblyInterrupted" in runs[0]!).toBe(false);
  3669. await harness.service.cancel(runId);
  3670. await settle(harness, runId);
  3671. });
  3672. });
  3673. it("间隙里的 run 不受 cwd 与 statuses 过滤的豁免", async () => {
  3674. await withSqliteJournal(async (real) => {
  3675. const hidden = new Set<string>();
  3676. const journal = hideRunsFromReads(real, hidden);
  3677. const harness = makeHarness({ hangActors: true, journal });
  3678. const runId = await submitRun(harness, {
  3679. cwd: projectCwd,
  3680. parentSessionId: HARNESS_PARENT_SESSION,
  3681. scriptText: TYPED_SCRIPT,
  3682. trace: traceFor("list-gap-filters"),
  3683. });
  3684. hidden.add(runId);
  3685. const introspection = introspectionOf(harness);
  3686. // 别的项目问起时它不该出现(注册表条目自带 cwd)。
  3687. expect((await introspection.listRuns({ cwd: otherCwd, limit: 20 })).runs).toEqual([]);
  3688. // 显式的状态过滤器同样管得住它——补集不是过滤器的豁免通道。
  3689. expect(
  3690. (await introspection.listRuns({ cwd: projectCwd, limit: 20, statuses: ["completed"] }))
  3691. .runs,
  3692. ).toEqual([]);
  3693. await harness.service.cancel(runId);
  3694. await settle(harness, runId);
  3695. });
  3696. });
  3697. // 间隙里的 run 报 not_found 会是一句谎:它刚刚把 runId 交给了调用方。
  3698. it("getRunDetail 对间隙里的 run 回 pending 详情而不是 not_found", async () => {
  3699. await withSqliteJournal(async (real) => {
  3700. const hidden = new Set<string>();
  3701. const journal = hideRunsFromReads(real, hidden);
  3702. const harness = makeHarness({ hangActors: true, journal });
  3703. const runId = await submitRun(harness, {
  3704. cwd: projectCwd,
  3705. parentSessionId: HARNESS_PARENT_SESSION,
  3706. scriptText: TYPED_SCRIPT,
  3707. trace: traceFor("detail-gap"),
  3708. });
  3709. hidden.add(runId);
  3710. const detail = await introspectionOf(harness).getRunDetail(runId);
  3711. expect(detail).toMatchObject({
  3712. actors: [],
  3713. logTail: [],
  3714. ownedByThisSession: true,
  3715. runId,
  3716. status: "pending",
  3717. });
  3718. // 计数还没有权威来源时诚实地报 0。
  3719. expect(detail?.usage).toEqual({
  3720. nodesCompleted: 0,
  3721. nodesFailed: 0,
  3722. nodesObserved: 0,
  3723. nodesRunning: 0,
  3724. spentTokens: 0,
  3725. });
  3726. expect("result" in detail!).toBe(false);
  3727. expect("error" in detail!).toBe(false);
  3728. await harness.service.cancel(runId);
  3729. await settle(harness, runId);
  3730. });
  3731. });
  3732. });
  3733. describe("dynamic workflow run service — getRunDetail 组合", () => {
  3734. // ── 产物截面(docs/dynamic-workflow/authoring.md 的 `GetWorkflowRun` 行)─────────────
  3735. // ⚠ 术语:artifact = 脚本经 `artifact.*` 发布给**用户**看的产出,不是详情里的 `result`
  3736. // (脚本顶层返回值,引擎内部对它的同名叫法)。两者在同一个返回对象上并列,所以这里必须写明。
  3737. //
  3738. // getRunDetail 有**两条**返回分支,两条都要带产物:journal 行分支(常态)与注册表间隙分支
  3739. // (run 已提交、dwf_run 行还没落)。漏掉任一条的症状都是「模型看不见这个 run 产出了什么」,
  3740. // 而间隙那条最容易漏——它读起来像个纯兜底。
  3741. const DETAIL_ARTIFACT_SCRIPT = [
  3742. 'artifact.chart("perf", { x: { field: "round" }, y: { field: "ms" } });',
  3743. 'report({ round: 1, ms: 40 }, "perf");',
  3744. 'await artifact.markdown("summary", "# 结论");',
  3745. 'return "done";',
  3746. ].join("\n");
  3747. /** 只写文本的 fake store(脚本发的是 markdown)。 */
  3748. function detailArtifactStore(): ToolArtifactStorePort {
  3749. return {
  3750. writeToolResultArtifact: async (request) => ({
  3751. id: "artifact-1",
  3752. uri: "zcode-artifact://harness/artifact-1",
  3753. bytes: Buffer.byteLength(request.content, "utf8"),
  3754. contentType: request.contentType ?? "text/plain",
  3755. createdAt: new Date(0),
  3756. }),
  3757. readToolResultArtifact: async () => {
  3758. throw new Error("本用例不读字节");
  3759. },
  3760. };
  3761. }
  3762. it("journal 行分支带 artifacts 截面(看板 + 内容产物,版本与 itemCount 齐全)", async () => {
  3763. await withSqliteJournal(async (journal) => {
  3764. const harness = makeHarness({ artifactStore: detailArtifactStore(), journal });
  3765. const runId = await submitRun(harness, {
  3766. cwd: projectCwd,
  3767. parentSessionId: HARNESS_PARENT_SESSION,
  3768. scriptText: DETAIL_ARTIFACT_SCRIPT,
  3769. trace: traceFor("detail-artifacts"),
  3770. });
  3771. await settle(harness, runId);
  3772. const detail = await introspectionOf(harness).getRunDetail(runId);
  3773. expect(detail?.artifacts).toHaveLength(2);
  3774. expect(detail?.artifacts?.[0]).toMatchObject({
  3775. id: "perf",
  3776. kind: "chart",
  3777. version: 1,
  3778. itemCount: 1,
  3779. });
  3780. expect(detail?.artifacts?.[1]).toMatchObject({
  3781. id: "summary",
  3782. kind: "markdown",
  3783. version: 1,
  3784. contentType: "text/markdown",
  3785. itemCount: 0,
  3786. });
  3787. // 与端口的 listArtifacts 是**同一个** artifactsOf,所以两处逐字节相同——
  3788. // 三处各归并一份迟早会在「失败行算不算一版」这种地方分叉。
  3789. expect(detail?.artifacts).toEqual(await harness.service.listArtifacts!(runId));
  3790. });
  3791. });
  3792. it("间隙分支也带 artifacts:dwf_run 行还没落,节点行却可能已经落了", async () => {
  3793. // 引擎在 createRun 之后立刻就能 putNode 一条 artifact 行,所以「行还没落」不等于
  3794. // 「什么都没产出」。这条分支读起来像纯兜底,恰恰是最容易被漏掉产物的那条。
  3795. await withSqliteJournal(async (real) => {
  3796. const hidden = new Set<string>();
  3797. const journal = hideRunsFromReads(real, hidden);
  3798. const harness = makeHarness({ artifactStore: detailArtifactStore(), journal });
  3799. const runId = await submitRun(harness, {
  3800. cwd: projectCwd,
  3801. parentSessionId: HARNESS_PARENT_SESSION,
  3802. scriptText: DETAIL_ARTIFACT_SCRIPT,
  3803. trace: traceFor("detail-artifacts-gap"),
  3804. });
  3805. await settle(harness, runId);
  3806. // 藏掉 dwf_run 行:getRunRow 回 undefined,注册表条目仍在 ⇒ 走间隙分支。
  3807. hidden.add(runId);
  3808. const detail = await introspectionOf(harness).getRunDetail(runId);
  3809. // 间隙分支的招牌:计数诚实地为 0、actors / logTail 为空。
  3810. expect(detail?.usage).toMatchObject({ nodesObserved: 0, spentTokens: 0 });
  3811. expect(detail?.actors).toEqual([]);
  3812. // 但产物照样在。
  3813. expect(detail?.artifacts?.map((entry) => entry.id)).toEqual(["perf", "summary"]);
  3814. });
  3815. });
  3816. it("零产物的 run:两条分支都让 artifacts 整个字段缺席(不是空数组)", async () => {
  3817. await withSqliteJournal(async (journal) => {
  3818. const harness = makeHarness({ journal });
  3819. const runId = await submitRun(harness, {
  3820. cwd: projectCwd,
  3821. parentSessionId: HARNESS_PARENT_SESSION,
  3822. scriptText: TYPED_SCRIPT,
  3823. trace: traceFor("detail-artifacts-none"),
  3824. });
  3825. await settle(harness, runId);
  3826. const detail = await introspectionOf(harness).getRunDetail(runId);
  3827. expect(detail).toBeDefined();
  3828. expect("artifacts" in detail!).toBe(false);
  3829. });
  3830. });
  3831. it("未知 runId 回 undefined(工具层归一成 run_not_found)", async () => {
  3832. await withSqliteJournal(async (journal) => {
  3833. const harness = makeHarness({ journal });
  3834. expect(await introspectionOf(harness).getRunDetail("dwfrun-nope")).toBeUndefined();
  3835. });
  3836. });
  3837. it("节点三态计数、nodesObserved 为三者之和、用量直读 journal 行", async () => {
  3838. await withSqliteJournal(async (journal) => {
  3839. const harness = makeHarness({ journal });
  3840. preloadRun(journal, {
  3841. spentTokens: 4_321,
  3842. caps: { maxConcurrency: 4 },
  3843. cwd: projectCwd,
  3844. parentSessionId: HARNESS_PARENT_SESSION,
  3845. runId: "dwfrun-counts",
  3846. status: "completed",
  3847. });
  3848. const nodes: { ordinal: number; status: "completed" | "failed" | "running" }[] = [
  3849. { ordinal: 1, status: "completed" },
  3850. { ordinal: 2, status: "completed" },
  3851. { ordinal: 3, status: "failed" },
  3852. { ordinal: 4, status: "running" },
  3853. ];
  3854. for (const node of nodes) {
  3855. journal.putNode({
  3856. runId: "dwfrun-counts",
  3857. siteId: "ask#1",
  3858. ordinal: node.ordinal,
  3859. kind: "ask",
  3860. inputHash: `hash-${node.ordinal}`,
  3861. status: node.status,
  3862. });
  3863. }
  3864. const detail = await introspectionOf(harness).getRunDetail("dwfrun-counts");
  3865. expect(detail?.usage).toEqual({
  3866. nodesCompleted: 2,
  3867. nodesFailed: 1,
  3868. // 「已落库节点的行数」,不是「总步数」——动态工作流没有静态总数。
  3869. nodesObserved: 4,
  3870. nodesRunning: 1,
  3871. spentTokens: 4_321,
  3872. });
  3873. });
  3874. });
  3875. // ── 情势截面(docs/dynamic-workflow/launch.md「`GetWorkflowRun`」)────────────────
  3876. // 规则本身由 dynamic-workflow-run-roster.test.ts 手搓事件钉死;这里只证明**接线通了**:
  3877. // 真 journal 的事件、节点行、actor 行确实被读出来喂进了那套规则,而不是三个空字段。
  3878. it("journal 行分支带情势截面:子代理的当前 ask 带任务摘要与进度读数,阶段表按声明序", async () => {
  3879. await withSqliteJournal(async (journal) => {
  3880. const harness = makeHarness({ journal });
  3881. const runId = "dwfrun-roster-wired";
  3882. preloadRun(journal, {
  3883. cwd: projectCwd,
  3884. parentSessionId: HARNESS_PARENT_SESSION,
  3885. runId,
  3886. status: "running",
  3887. });
  3888. journal.putActor({ runId, siteId: "agent#1", ordinal: 1, name: "scout" });
  3889. journal.putNode({
  3890. runId,
  3891. siteId: "ask#1",
  3892. ordinal: 1,
  3893. kind: "ask",
  3894. actorSiteId: "agent#1",
  3895. actorOrdinal: 1,
  3896. actorSeq: 1,
  3897. inputHash: "hash-ask-1",
  3898. status: "running",
  3899. });
  3900. for (const event of [
  3901. { type: "run-started", runId, caps: { maxConcurrency: 4 } },
  3902. { type: "run-launched", inputId: "in-wired", phaseNames: ["collect", "verify"] },
  3903. { type: "phase-entered", name: "collect", ordinal: 1 },
  3904. { type: "actor-created", actor: { siteId: "agent#1", ordinal: 1 }, name: "scout" },
  3905. {
  3906. type: "node-queued",
  3907. instance: { siteId: "ask#1", ordinal: 1 },
  3908. kind: "ask",
  3909. actor: { siteId: "agent#1", ordinal: 1 },
  3910. actorSeq: 1,
  3911. phaseName: "collect",
  3912. instructionsHead: "Collect every regression named in the release notes.",
  3913. },
  3914. { type: "node-dispatched", instance: { siteId: "ask#1", ordinal: 1 } },
  3915. { type: "node-executing", instance: { siteId: "ask#1", ordinal: 1 } },
  3916. {
  3917. type: "node-progress",
  3918. instance: { siteId: "ask#1", ordinal: 1 },
  3919. turn: 2,
  3920. toolCalls: 7,
  3921. lastTool: { name: "Read", target: "docs/release.md" },
  3922. },
  3923. ] as RunEvent[]) {
  3924. journal.appendEvent(runId, event);
  3925. }
  3926. const detail = await introspectionOf(harness).getRunDetail(runId);
  3927. expect(detail?.subagents).toHaveLength(1);
  3928. expect(detail?.subagents[0]).toMatchObject({
  3929. siteId: "agent#1",
  3930. name: "scout",
  3931. state: "executing",
  3932. phaseName: "collect",
  3933. currentAsk: {
  3934. siteId: "ask#1",
  3935. ordinal: 1,
  3936. actorSeq: 1,
  3937. instructionsHead: "Collect every regression named in the release notes.",
  3938. turn: 2,
  3939. toolCalls: 7,
  3940. lastTool: { name: "Read", target: "docs/release.md" },
  3941. },
  3942. });
  3943. // 时刻来自 dwf_event.time_created,所以真库里它必须是一个真实的毫秒数。
  3944. expect(detail?.subagents[0]?.currentAsk?.startedAt).toBeGreaterThan(0);
  3945. expect(detail?.phases).toMatchObject([
  3946. { name: "collect", state: "current", rounds: 1, nodesRunning: 1 },
  3947. { name: "verify", state: "ahead", rounds: 0 },
  3948. ]);
  3949. // 行写着本会话是发起方,但本会话的注册表里没有它——也就是重启后的遗物:进程内那张
  3950. // 停驻表早随上一个进程没了,所以这次读**答不出**有没有问题在等,只能如实说不知道。
  3951. expect(detail?.ownedByThisSession).toBe(true);
  3952. expect(detail?.health).toMatchObject({
  3953. consecutiveFailures: 0,
  3954. cachedSteps: 0,
  3955. pendingQuestionsKnown: false,
  3956. });
  3957. });
  3958. });
  3959. it("终态 run:pendingQuestionsKnown 为真(没有人还在听),遗留的 running 行被数出来", async () => {
  3960. await withSqliteJournal(async (journal) => {
  3961. const harness = makeHarness({ journal });
  3962. const runId = "dwfrun-roster-terminal";
  3963. preloadRun(journal, {
  3964. cwd: projectCwd,
  3965. parentSessionId: HARNESS_PARENT_SESSION,
  3966. runId,
  3967. status: "stopped",
  3968. stopReason: "interrupted",
  3969. });
  3970. journal.putActor({ runId, siteId: "agent#1", ordinal: 1, name: "worker" });
  3971. journal.putNode({
  3972. runId,
  3973. siteId: "ask#1",
  3974. ordinal: 1,
  3975. kind: "ask",
  3976. actorSiteId: "agent#1",
  3977. actorOrdinal: 1,
  3978. actorSeq: 1,
  3979. inputHash: "hash-ask-1",
  3980. status: "running",
  3981. });
  3982. for (const event of [
  3983. { type: "run-started", runId, caps: { maxConcurrency: 4 } },
  3984. { type: "actor-created", actor: { siteId: "agent#1", ordinal: 1 }, name: "worker" },
  3985. {
  3986. type: "node-queued",
  3987. instance: { siteId: "ask#1", ordinal: 1 },
  3988. kind: "ask",
  3989. actor: { siteId: "agent#1", ordinal: 1 },
  3990. actorSeq: 1,
  3991. },
  3992. { type: "node-dispatched", instance: { siteId: "ask#1", ordinal: 1 } },
  3993. ] as RunEvent[]) {
  3994. journal.appendEvent(runId, event);
  3995. }
  3996. const detail = await introspectionOf(harness).getRunDetail(runId);
  3997. // 终态 run 按定义没有还在听的人,所以「没有待答问题」是一句确定的话。
  3998. expect(detail?.health).toMatchObject({ pendingQuestionsKnown: true, leftoverRunning: 1 });
  3999. expect(detail?.subagents[0]).toMatchObject({ name: "worker", state: "unfinished" });
  4000. // 脚本没有 phase() 标记、也没进过任何阶段 ⇒ 整个字段缺席。
  4001. expect("phases" in detail!).toBe(false);
  4002. });
  4003. });
  4004. it("actors 全列出(siteId / ordinal / name),persona 不出", async () => {
  4005. await withSqliteJournal(async (journal) => {
  4006. const harness = makeHarness({ journal });
  4007. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-actors", status: "completed" });
  4008. journal.putActor({
  4009. runId: "dwfrun-actors",
  4010. siteId: "actor#1",
  4011. ordinal: 1,
  4012. name: "worker",
  4013. persona: { system: "a very long system prompt" },
  4014. });
  4015. journal.putActor({ runId: "dwfrun-actors", siteId: "actor#2", ordinal: 3 });
  4016. const detail = await introspectionOf(harness).getRunDetail("dwfrun-actors");
  4017. expect(detail?.actors).toEqual([
  4018. { siteId: "actor#1", ordinal: 1, name: "worker" },
  4019. { siteId: "actor#2", ordinal: 3 },
  4020. ]);
  4021. });
  4022. });
  4023. it("logTail:只取 log 事件、末 20 条、按时序、逐条 2048 字符界", async () => {
  4024. await withSqliteJournal(async (journal) => {
  4025. const harness = makeHarness({ journal });
  4026. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-logs", status: "completed" });
  4027. journal.appendEvent("dwfrun-logs", {
  4028. caps: { maxConcurrency: 4 },
  4029. runId: "dwfrun-logs",
  4030. type: "run-started",
  4031. });
  4032. for (let index = 1; index <= 25; index += 1) {
  4033. journal.appendEvent("dwfrun-logs", { message: `step ${index}`, type: "log" });
  4034. }
  4035. const overlong = "x".repeat(5_000);
  4036. journal.appendEvent("dwfrun-logs", { message: overlong, type: "log" });
  4037. const detail = await introspectionOf(harness).getRunDetail("dwfrun-logs");
  4038. const logTail = detail!.logTail;
  4039. expect(logTail).toHaveLength(20);
  4040. // 时序(sequence 升序),且尾巴取的是**末** 20 条:最早保留的是 step 7。
  4041. expect(logTail.map((entry) => entry.sequence)).toEqual(
  4042. [...logTail].sort((left, right) => left.sequence - right.sequence).map((e) => e.sequence),
  4043. );
  4044. expect(logTail[0]?.message).toBe("step 7");
  4045. expect(logTail.at(-1)?.message).toHaveLength(
  4046. DYNAMIC_WORKFLOW_RUN_EVENT_PAYLOAD_LIMITS.maxStringLength,
  4047. );
  4048. // run-started 不是 log:类型过滤下推到 SQL,不能靠"反正模型看不懂"混进来。
  4049. expect(logTail.some((entry) => entry.message.includes("run-started"))).toBe(false);
  4050. // 每条叙事带着自己的落库时刻(dwf_event.time_created):读面据它算「多久以前」,
  4051. // 而不是用读时的 Date.now() 把一周前的历史全标成「刚刚」。
  4052. for (const entry of logTail) {
  4053. expect(typeof entry.at).toBe("number");
  4054. expect(entry.at).toBeLessThanOrEqual(Date.now());
  4055. }
  4056. });
  4057. });
  4058. it("没有 log 事件时 logTail 是空数组", async () => {
  4059. await withSqliteJournal(async (journal) => {
  4060. const harness = makeHarness({ journal });
  4061. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-nologs", status: "completed" });
  4062. expect((await introspectionOf(harness).getRunDetail("dwfrun-nologs"))?.logTail).toEqual([]);
  4063. });
  4064. });
  4065. // 时间戳直读 journal 行,刻意绕开快照面的 new Date(0) 兜底:内存条目蒸发后那个起始时间
  4066. // 是假的,而模型据它判断「这个 run 是多久以前的」。
  4067. it("createdAt / updatedAt 来自 journal 行", async () => {
  4068. await withSqliteJournal(async (journal) => {
  4069. const harness = makeHarness({ journal });
  4070. const before = Date.now();
  4071. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-times", status: "running" });
  4072. journal.updateRunStatus("dwfrun-times", "completed");
  4073. const after = Date.now();
  4074. const detail = await introspectionOf(harness).getRunDetail("dwfrun-times");
  4075. expect(detail!.createdAt).toBeGreaterThanOrEqual(before);
  4076. expect(detail!.updatedAt).toBeGreaterThanOrEqual(detail!.createdAt);
  4077. expect(detail!.updatedAt).toBeLessThanOrEqual(after);
  4078. });
  4079. });
  4080. it("running 的 run 既无 result 也无 error", async () => {
  4081. await withSqliteJournal(async (journal) => {
  4082. const harness = makeHarness({ journal });
  4083. preloadRun(journal, {
  4084. cwd: projectCwd,
  4085. parentSessionId: createSessionId("sibling-session"),
  4086. runId: "dwfrun-running",
  4087. status: "running",
  4088. });
  4089. const detail = await introspectionOf(harness).getRunDetail("dwfrun-running");
  4090. expect("result" in detail!).toBe(false);
  4091. expect("error" in detail!).toBe(false);
  4092. });
  4093. });
  4094. it("completed:内存终态的产物原样交出(不序列化)", async () => {
  4095. await withSqliteJournal(async (journal) => {
  4096. const harness = makeHarness({
  4097. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "the answer" } }] },
  4098. journal,
  4099. });
  4100. const runId = await submitRun(harness, {
  4101. cwd: projectCwd,
  4102. parentSessionId: HARNESS_PARENT_SESSION,
  4103. scriptText: TYPED_SCRIPT,
  4104. trace: traceFor("detail-result-memory"),
  4105. });
  4106. await settle(harness, runId);
  4107. const detail = await introspectionOf(harness).getRunDetail(runId);
  4108. expect(detail?.status).toBe("completed");
  4109. // 原值,不是 JSON 文本:面向模型的序列化在 core 有唯一实现(完成通知与 TaskOutput
  4110. // 共用它),端口再做一次就会出现"同一个产物两种长相"。
  4111. expect(detail?.result).toBe("the answer");
  4112. expect("error" in detail!).toBe(false);
  4113. });
  4114. });
  4115. it("completed:注册表蒸发后退回 journal 的 result_json", async () => {
  4116. await withSqliteJournal(async (journal) => {
  4117. const harness = makeHarness({ journal });
  4118. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-result-json", status: "running" });
  4119. journal.updateRunStatus("dwfrun-result-json", "completed", {
  4120. result: { report: "final answer", steps: 3 },
  4121. });
  4122. const detail = await introspectionOf(harness).getRunDetail("dwfrun-result-json");
  4123. expect(detail?.result).toEqual({ report: "final answer", steps: 3 });
  4124. });
  4125. });
  4126. it("completed 但产物是 undefined → result 整字段缺席", async () => {
  4127. await withSqliteJournal(async (journal) => {
  4128. const harness = makeHarness({ journal });
  4129. preloadRun(journal, { cwd: projectCwd, runId: "dwfrun-void", status: "completed" });
  4130. expect("result" in (await introspectionOf(harness).getRunDetail("dwfrun-void"))!).toBe(false);
  4131. });
  4132. });
  4133. // 模型必须能分辨「进程死了」(Interrupted)与「脚本真失败」(DriverError):code 原样透出,
  4134. // 绝不折叠成一个通用失败。
  4135. it("errored / stopped(interrupted):failure_json 的 code 原样透出(含 Interrupted)", async () => {
  4136. await withSqliteJournal(async (journal) => {
  4137. const harness = makeHarness({ journal });
  4138. for (const code of ["Interrupted", "DriverError"] as const) {
  4139. preloadRun(journal, {
  4140. cwd: projectCwd,
  4141. failure: { code, message: `failed with ${code}` },
  4142. runId: `dwfrun-failed-${code}`,
  4143. ...(code === "Interrupted"
  4144. ? { status: "stopped" as const, stopReason: "interrupted" as const }
  4145. : { status: "errored" as const }),
  4146. });
  4147. }
  4148. const introspection = introspectionOf(harness);
  4149. expect((await introspection.getRunDetail("dwfrun-failed-Interrupted"))?.error).toEqual({
  4150. code: "Interrupted",
  4151. message: "failed with Interrupted",
  4152. });
  4153. expect((await introspection.getRunDetail("dwfrun-failed-DriverError"))?.error).toEqual({
  4154. code: "DriverError",
  4155. message: "failed with DriverError",
  4156. });
  4157. });
  4158. });
  4159. it("cancelled:带 error(失败编码在场时)", async () => {
  4160. await withSqliteJournal(async (journal) => {
  4161. const harness = makeHarness({ journal });
  4162. preloadRun(journal, {
  4163. cwd: projectCwd,
  4164. failure: { code: "Cancelled", message: "cancelled by user" },
  4165. runId: "dwfrun-cancelled",
  4166. status: "stopped",
  4167. stopReason: "user",
  4168. });
  4169. expect((await introspectionOf(harness).getRunDetail("dwfrun-cancelled"))?.error).toEqual({
  4170. code: "Cancelled",
  4171. message: "cancelled by user",
  4172. });
  4173. });
  4174. });
  4175. });
  4176. describe("resolveDynamicWorkflowJournalStore", () => {
  4177. // 没有 journal 就不构造服务:一个静默丢失持久化的 run 比没有 run 更糟。
  4178. it("store 缺少 workflowJournalStore 时返回 undefined 并记原因", () => {
  4179. const messages: string[] = [];
  4180. const resolved = resolveDynamicWorkflowJournalStore(
  4181. {} as never,
  4182. {
  4183. info: (message: string) => {
  4184. messages.push(message);
  4185. },
  4186. } as never,
  4187. );
  4188. expect(resolved).toBeUndefined();
  4189. expect(messages.join(" ")).toContain("dwf journal");
  4190. });
  4191. it("store 提供 workflowJournalStore 时透出该 journal", () => {
  4192. const journal = new InMemoryJournalStore();
  4193. const resolved = resolveDynamicWorkflowJournalStore({
  4194. workflowJournalStore: () => journal,
  4195. } as never);
  4196. expect(resolved).toBe(journal);
  4197. });
  4198. });
  4199. describe("dynamic workflow run service — resume", () => {
  4200. const TWO_ASK_SCRIPT = [
  4201. "interface Answer { text: string }",
  4202. 'const worker = agent("worker");',
  4203. 'const first = await worker.ask<Answer>("step one");',
  4204. "const second = await worker.ask(`step two after ${first.text}`);",
  4205. "return `${first.text}+${second}`;",
  4206. ].join("\n");
  4207. const RESUME_TOOL_CALL = createToolCallId("resume-origin");
  4208. /**
  4209. * 阶段一:把一个 run 跑到「ask#1 已完结、ask#2 在飞」再取消。
  4210. * journal 里留下:actor(带会话 id)、completed 的 ask#1、running 的 ask#2——
  4211. * 正是 resume 要接手的形态。options 对象被 makeHarness 闭包持有,测试可在两阶段之间
  4212. * 改写 actorScripts(阶段二的 fresh runtime 按当时的值取剧本)。
  4213. */
  4214. async function cancelledMidFlight(options: HarnessOptions = {}) {
  4215. options.actorScripts = {
  4216. "actor#1@1": [{ kind: "submit", result: { text: "one" } }, { kind: "hang" }],
  4217. };
  4218. const harness = makeHarness(options);
  4219. const runId = await submitRun(harness, {
  4220. cwd: TEST_CWD,
  4221. parentSessionId: HARNESS_PARENT_SESSION,
  4222. scriptText: TWO_ASK_SCRIPT,
  4223. toolCallId: RESUME_TOOL_CALL,
  4224. trace: traceFor("resume-phase1"),
  4225. });
  4226. await vi.waitFor(() => {
  4227. expect(harness.journal.getNode(runId, "ask#2", 1)?.status).toBe("running");
  4228. });
  4229. expect(await harness.service.cancel(runId)).toBe(true);
  4230. await settle(harness, runId);
  4231. expect(harness.journal.getRun(runId)?.status).toBe("stopped");
  4232. expect(harness.journal.getNode(runId, "ask#1", 1)?.status).toBe("completed");
  4233. expect(harness.journal.getActor(runId, "actor#1", 1)?.sessionId).toBeDefined();
  4234. return { harness, runId };
  4235. }
  4236. it("恢复被取消的 run:完结节点短路、在飞节点重派发、run 跑到 completed", async () => {
  4237. const options: HarnessOptions = {};
  4238. const { harness, runId } = await cancelledMidFlight(options);
  4239. const linksAfterPhaseOne = harness.taskLinks.length;
  4240. const persistsAfterPhaseOne = harness.persistedTitles.length;
  4241. // 阶段二剧本:fresh runtime 只需要应答重派发的 ask#2(untyped → 一段文本)。
  4242. options.actorScripts = { "actor#1@1": [{ kind: "text", text: "two" }] };
  4243. const result = await harness.service.resume?.(runId);
  4244. expect(result).toMatchObject({ ok: true, runId, toolCallId: RESUME_TOOL_CALL });
  4245. await settle(harness, runId);
  4246. const snapshot = await harness.service.getTask(runId);
  4247. expect(snapshot?.status).toBe("completed");
  4248. expect(snapshot?.output).toBe("one+two");
  4249. expect(harness.journal.getRun(runId)?.status).toBe("completed");
  4250. // ask#1 未重跑:两阶段共 3 次模型请求(submit + hang + 阶段二的 text),
  4251. // 若 ask#1 被重派发会是 4 次。actor runtime 每阶段各构造一次。
  4252. expect(harness.order.filter((entry) => entry.startsWith("turn:")).length).toBe(3);
  4253. expect(harness.order.filter((entry) => entry.startsWith("construct:")).length).toBe(2);
  4254. // 重水化:journaled actor 经 resumeFromStore 重挂;会话行与 task link 不再重建。
  4255. expect(harness.resumeCalls).toHaveLength(1);
  4256. expect(harness.taskLinks.length).toBe(linksAfterPhaseOne);
  4257. expect(harness.persistedTitles.length).toBe(persistsAfterPhaseOne);
  4258. // 事件面:sequence 跨两阶段单调续编;run-started 出现两次;ask#1 以 cached 短路结算。
  4259. const sequences = harness.runEvents.map((event) => event.sequence);
  4260. for (let i = 1; i < sequences.length; i++) {
  4261. expect(sequences[i]!).toBeGreaterThan(sequences[i - 1]!);
  4262. }
  4263. expect(harness.runEvents.filter((event) => event.eventType === "run-started")).toHaveLength(2);
  4264. const cachedSettles = harness.runEvents.filter(
  4265. (event) =>
  4266. event.eventType === "node-settled" &&
  4267. (event.payload as { cached?: boolean }).cached === true,
  4268. );
  4269. expect(cachedSettles.length).toBeGreaterThanOrEqual(1);
  4270. });
  4271. it("恢复后 cancel 依然可用(注册表条目被替换成新的 AbortController)", async () => {
  4272. const options: HarnessOptions = {};
  4273. const { harness, runId } = await cancelledMidFlight(options);
  4274. options.actorScripts = { "actor#1@1": [{ kind: "hang" }] };
  4275. const result = await harness.service.resume?.(runId);
  4276. expect(result).toMatchObject({ ok: true });
  4277. // 等重派发的 ask#2 真正在飞(阶段二的第 3 次模型请求)。
  4278. await vi.waitFor(() => {
  4279. expect(harness.order.filter((entry) => entry.startsWith("turn:")).length).toBe(3);
  4280. });
  4281. expect(await harness.service.cancel(runId)).toBe(true);
  4282. await settle(harness, runId);
  4283. expect((await harness.service.getTask(runId))?.status).toBe("cancelled");
  4284. expect(harness.journal.getRun(runId)?.status).toBe("stopped");
  4285. });
  4286. it("resume 返回后 getTask 立即报 running(journal 状态已翻回)", async () => {
  4287. const options: HarnessOptions = {};
  4288. const { harness, runId } = await cancelledMidFlight(options);
  4289. options.actorScripts = { "actor#1@1": [{ kind: "hang" }] };
  4290. await harness.service.resume?.(runId);
  4291. // 不等结算:launch 的同步前缀已让引擎构造走完 resume 分支(updateRunStatus running)。
  4292. expect((await harness.service.getTask(runId))?.status).toBe("running");
  4293. await harness.service.cancel(runId);
  4294. await settle(harness, runId);
  4295. });
  4296. it("孤儿收敛出的 stopped(interrupted) run 可恢复,且恢复清掉陈旧 failure", async () => {
  4297. const { createHash } = await import("node:crypto");
  4298. const journal = new SweepableJournalStore();
  4299. const runId = "dwfrun-interrupted";
  4300. journal.createRun({
  4301. runId,
  4302. parentSessionId: HARNESS_PARENT_SESSION,
  4303. cwd: TEST_CWD,
  4304. scriptText: TYPED_SCRIPT,
  4305. scriptHash: createHash("sha256").update(TYPED_SCRIPT, "utf8").digest("hex"),
  4306. toolCallId: "call-interrupted",
  4307. caps: { maxConcurrency: 4 },
  4308. spentTokens: 0,
  4309. status: "stopped",
  4310. stopReason: "interrupted",
  4311. failure: { code: "Interrupted", message: "owning process exited" },
  4312. });
  4313. const harness = makeHarness({
  4314. journal,
  4315. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "revived" } }] },
  4316. });
  4317. const result = await harness.service.resume?.(runId);
  4318. expect(result).toMatchObject({ ok: true, runId, toolCallId: "call-interrupted" });
  4319. await settle(harness, runId);
  4320. const record = harness.journal.getRun(runId);
  4321. expect(record?.status).toBe("completed");
  4322. // 非终态翻转清掉了 Interrupted 残留(updateRunStatus 的新语义走真实路径)。
  4323. expect(record?.failure).toBeUndefined();
  4324. expect(record?.stopReason).toBeUndefined();
  4325. expect((await harness.service.getTask(runId))?.output).toBe("revived");
  4326. // 空 journal(无 actor 记录)→ 全新持久化路径,不走重水化。
  4327. expect(harness.resumeCalls).toHaveLength(0);
  4328. expect(harness.persistedTitles).toHaveLength(1);
  4329. });
  4330. it("回退:resumeFromStore 抛 SessionNotFound 时退回全新持久化路径", async () => {
  4331. const options: HarnessOptions = { resumeSessionMissing: true };
  4332. const { harness, runId } = await cancelledMidFlight(options);
  4333. const persistsAfterPhaseOne = harness.persistedTitles.length;
  4334. options.actorScripts = { "actor#1@1": [{ kind: "text", text: "two" }] };
  4335. const result = await harness.service.resume?.(runId);
  4336. expect(result).toMatchObject({ ok: true });
  4337. await settle(harness, runId);
  4338. expect((await harness.service.getTask(runId))?.status).toBe("completed");
  4339. // 重水化被尝试过(journaled actor),失败后回退:会话重新持久化了一次。
  4340. expect(harness.resumeCalls).toHaveLength(1);
  4341. expect(harness.persistedTitles.length).toBe(persistsAfterPhaseOne + 1);
  4342. // 回退有迹可循(warn),而不是静默。
  4343. expect(
  4344. harness.logs.some(
  4345. (log) =>
  4346. log.level === "warn" &&
  4347. log.context?.event === "dynamic_workflow.actor.rehydrate_fallback",
  4348. ),
  4349. ).toBe(true);
  4350. });
  4351. });
  4352. /**
  4353. * 实参的持久与重放(docs/dynamic-workflow/launch.md「Running a saved workflow」)。
  4354. *
  4355. * 这一组守的是一句话:**resume 重放存下来的实参,永不接受新的**。失败形态很安静——一个
  4356. * 恢复出来的 run 带着 `{}` 再跑一遍,脚本走进另一条分支,而 run 面板上什么都看不出来。
  4357. */
  4358. describe("dynamic workflow run service — run args", () => {
  4359. // 产物里带上实参:这样「实参有没有到沙箱」是一个可以从 getTask 直接看到的事实,
  4360. // 而不是一个要靠间接计数去推断的东西。
  4361. const ARGS_SCRIPT = [
  4362. "interface Answer { text: string }",
  4363. 'const a = await agent("worker").ask<Answer>(`work on ${String(args.target)}`);',
  4364. "return `${String(args.target)}:${a.text}`;",
  4365. ].join("\n");
  4366. it("落库 submit 收到的实参,并把它注入沙箱", async () => {
  4367. const harness = makeHarness({
  4368. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "done" } }] },
  4369. });
  4370. const runId = await submitRun(harness, {
  4371. args: { target: "packages/core" },
  4372. cwd: TEST_CWD,
  4373. parentSessionId: HARNESS_PARENT_SESSION,
  4374. scriptText: ARGS_SCRIPT,
  4375. trace: traceFor("args-submit"),
  4376. });
  4377. await settle(harness, runId);
  4378. expect(harness.journal.getRun(runId)?.args).toEqual({ target: "packages/core" });
  4379. // 落库只是一半:产物证明这份实参真的被注入了沙箱、被脚本读到了。
  4380. const snapshot = await harness.service.getTask(runId);
  4381. expect(snapshot?.status).toBe("completed");
  4382. expect(snapshot?.output).toBe("packages/core:done");
  4383. });
  4384. it("内联 run 不落实参列(老行与无参 run 走同一条缺席路径)", async () => {
  4385. const harness = makeHarness({
  4386. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "x" } }] },
  4387. });
  4388. const runId = await submitRun(harness, {
  4389. cwd: TEST_CWD,
  4390. parentSessionId: HARNESS_PARENT_SESSION,
  4391. scriptText: TYPED_SCRIPT,
  4392. trace: traceFor("args-absent"),
  4393. });
  4394. await settle(harness, runId);
  4395. expect(harness.journal.getRun(runId)?.args).toBeUndefined();
  4396. });
  4397. it("resume 重放持久化的实参,且 resume 入口根本收不下新实参", async () => {
  4398. const options: HarnessOptions = {
  4399. actorScripts: { "actor#1@1": [{ kind: "hang" }] },
  4400. };
  4401. const harness = makeHarness(options);
  4402. const runId = await submitRun(harness, {
  4403. args: { target: "original-target" },
  4404. cwd: TEST_CWD,
  4405. parentSessionId: HARNESS_PARENT_SESSION,
  4406. scriptText: ARGS_SCRIPT,
  4407. trace: traceFor("args-resume"),
  4408. });
  4409. await vi.waitFor(() => {
  4410. expect(harness.journal.getNode(runId, "ask#1", 1)?.status).toBe("running");
  4411. });
  4412. expect(await harness.service.cancel(runId)).toBe(true);
  4413. await settle(harness, runId);
  4414. options.actorScripts = { "actor#1@1": [{ kind: "submit", result: { text: "resumed" } }] };
  4415. // resume 的签名只收 runId:换实参在这条入口上**无从表达**,而那正是设计——
  4416. // 换实参 = 一次新的 run = 一次新的确认窗。
  4417. expect(await harness.service.resume?.(runId)).toMatchObject({ ok: true, runId });
  4418. await settle(harness, runId);
  4419. // 恢复出来的 run 用的还是被批准的那一份实参,且记录没有被 resume 改写。
  4420. expect(harness.journal.getRun(runId)?.args).toEqual({ target: "original-target" });
  4421. const resumed = await harness.service.getTask(runId);
  4422. expect(resumed?.status).toBe("completed");
  4423. // 产物里的实参就是**第一次批准的**那一份:resume 重放它,不重新征集。
  4424. expect(resumed?.output).toBe("original-target:resumed");
  4425. });
  4426. // GUI「配置」重跑前驱自己的脚本(docs/dynamic-workflow/launch.md「Changing a run's settings from the
  4427. // GUI」):`inheritArgs` 让修订沿用前驱落库的实参;工具路径不传,修订照旧不带实参。
  4428. it("amend 默认不带实参;inheritArgs 沿用前驱落库的那一份并注入沙箱", async () => {
  4429. const options: HarnessOptions = {
  4430. actorScripts: { "actor#1@1": [{ kind: "hang" }] },
  4431. };
  4432. const harness = makeHarness(options);
  4433. const runA = await submitRun(harness, {
  4434. args: { target: "packages/core" },
  4435. cwd: TEST_CWD,
  4436. parentSessionId: HARNESS_PARENT_SESSION,
  4437. scriptText: ARGS_SCRIPT,
  4438. trace: traceFor("args-amend-a"),
  4439. });
  4440. await vi.waitFor(() => {
  4441. expect(harness.journal.getNode(runA, "ask#1", 1)?.status).toBe("running");
  4442. });
  4443. options.actorScripts = { "actor#1@1": [{ kind: "submit", result: { text: "kept" } }] };
  4444. const inherited = await amendRun(harness, {
  4445. cwd: TEST_CWD,
  4446. inheritArgs: true,
  4447. parentSessionId: HARNESS_PARENT_SESSION,
  4448. predecessorRunId: runA,
  4449. scriptText: ARGS_SCRIPT,
  4450. trace: traceFor("args-amend-b"),
  4451. });
  4452. await settle(harness, inherited.runId);
  4453. expect(harness.journal.getRun(inherited.runId)?.args).toEqual({ target: "packages/core" });
  4454. expect((await harness.service.getTask(inherited.runId))?.output).toBe("packages/core:kept");
  4455. // 工具路径(不传 inheritArgs):再从同一个前驱修订一次,新 run 不带实参。前驱挂起时没有已完成
  4456. // 的 ask,边界预检自然通过。
  4457. const plain = await amendRun(harness, {
  4458. cwd: TEST_CWD,
  4459. parentSessionId: HARNESS_PARENT_SESSION,
  4460. predecessorRunId: runA,
  4461. scriptText: ARGS_SCRIPT,
  4462. trace: traceFor("args-amend-c"),
  4463. });
  4464. await settle(harness, plain.runId);
  4465. expect(harness.journal.getRun(plain.runId)?.args).toBeUndefined();
  4466. });
  4467. });
  4468. describe("dynamic workflow run service — resume 门", () => {
  4469. it("未知 runId → not_found", async () => {
  4470. const harness = makeHarness();
  4471. await expect(harness.service.resume?.("dwfrun-nope")).resolves.toEqual({
  4472. ok: false,
  4473. reason: "not_found",
  4474. });
  4475. });
  4476. it("completed run → not_resumable", async () => {
  4477. const harness = makeHarness();
  4478. const runId = await submitRun(harness, {
  4479. cwd: TEST_CWD,
  4480. parentSessionId: HARNESS_PARENT_SESSION,
  4481. scriptText: TYPED_SCRIPT,
  4482. trace: traceFor("gate-completed"),
  4483. });
  4484. await settle(harness, runId);
  4485. await expect(harness.service.resume?.(runId)).resolves.toEqual({
  4486. ok: false,
  4487. reason: "not_resumable",
  4488. });
  4489. });
  4490. it("errored → not_resumable(脚本真失败 replay 只会逐字复现)", async () => {
  4491. const journal = new SweepableJournalStore();
  4492. journal.createRun({
  4493. runId: "dwfrun-script-failed",
  4494. parentSessionId: HARNESS_PARENT_SESSION,
  4495. scriptText: TYPED_SCRIPT,
  4496. caps: { maxConcurrency: 4 },
  4497. spentTokens: 0,
  4498. status: "errored",
  4499. failure: { code: "DriverError", message: "script threw" },
  4500. });
  4501. const harness = makeHarness({ journal });
  4502. await expect(harness.service.resume?.("dwfrun-script-failed")).resolves.toEqual({
  4503. ok: false,
  4504. reason: "not_resumable",
  4505. });
  4506. });
  4507. it("记录缺 scriptText → script_missing", async () => {
  4508. const journal = new SweepableJournalStore();
  4509. journal.createRun({
  4510. runId: "dwfrun-old",
  4511. parentSessionId: HARNESS_PARENT_SESSION,
  4512. caps: { maxConcurrency: 4 },
  4513. spentTokens: 0,
  4514. status: "stopped",
  4515. stopReason: "user",
  4516. });
  4517. const harness = makeHarness({ journal });
  4518. await expect(harness.service.resume?.("dwfrun-old")).resolves.toEqual({
  4519. ok: false,
  4520. reason: "script_missing",
  4521. });
  4522. });
  4523. it("scriptHash 与原文不自洽 → script_mismatch,journal 状态不被触碰", async () => {
  4524. const journal = new SweepableJournalStore();
  4525. journal.createRun({
  4526. runId: "dwfrun-tampered",
  4527. parentSessionId: HARNESS_PARENT_SESSION,
  4528. scriptText: TYPED_SCRIPT,
  4529. scriptHash: "bogus-hash",
  4530. caps: { maxConcurrency: 4 },
  4531. spentTokens: 0,
  4532. status: "stopped",
  4533. stopReason: "user",
  4534. });
  4535. const harness = makeHarness({ journal });
  4536. await expect(harness.service.resume?.("dwfrun-tampered")).resolves.toEqual({
  4537. ok: false,
  4538. reason: "script_mismatch",
  4539. });
  4540. // 拒绝不建注册表条目、不启动引擎:记录保持 stopped,仍可在修复记录后恢复。
  4541. expect(harness.journal.getRun("dwfrun-tampered")?.status).toBe("stopped");
  4542. });
  4543. // facade 重构后的老 run(2026-09-15):原文按当时的 facade 写,当前类型检查不再通过。
  4544. it("原文在当前 facade 下编不过 → compile_failed 携有界诊断,journal 状态不被触碰", async () => {
  4545. const journal = new SweepableJournalStore();
  4546. const legacyScript =
  4547. "const planner = agent('planner');\nawait planner.askWithOldFacade('x');\n";
  4548. journal.createRun({
  4549. runId: "dwfrun-legacy-facade",
  4550. parentSessionId: HARNESS_PARENT_SESSION,
  4551. scriptText: legacyScript,
  4552. caps: { maxConcurrency: 4 },
  4553. spentTokens: 0,
  4554. status: "stopped",
  4555. stopReason: "interrupted",
  4556. });
  4557. const harness = makeHarness({ journal });
  4558. const result = await harness.service.resume?.("dwfrun-legacy-facade");
  4559. expect(result).toMatchObject({ ok: false, reason: "compile_failed" });
  4560. expect((result as { message?: string }).message).toMatch(/no longer compiles/);
  4561. expect((result as { message?: string }).message).toMatch(/L\d+:C\d+/);
  4562. expect(harness.journal.getRun("dwfrun-legacy-facade")?.status).toBe("stopped");
  4563. });
  4564. it("同 runId 在飞 → already_running", async () => {
  4565. const harness = makeHarness({
  4566. actorScripts: { "actor#1@1": [{ kind: "hang" }] },
  4567. });
  4568. const runId = await submitRun(harness, {
  4569. cwd: TEST_CWD,
  4570. parentSessionId: HARNESS_PARENT_SESSION,
  4571. scriptText: TYPED_SCRIPT,
  4572. trace: traceFor("gate-inflight"),
  4573. });
  4574. await vi.waitFor(() => {
  4575. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  4576. });
  4577. await expect(harness.service.resume?.(runId)).resolves.toEqual({
  4578. ok: false,
  4579. reason: "already_running",
  4580. });
  4581. await harness.service.cancel(runId);
  4582. await settle(harness, runId);
  4583. });
  4584. });
  4585. // 冷回放(docs/dynamic-workflow/presentation.md):journal → 与 live 同一种进度载荷。
  4586. // 「重启前后一致」在这里成为可断言的事实:同一份 sqlite journal 上跑完一个 run,live 时 onRunEvent
  4587. // 交出的载荷序列,与一个**新** service 实例(注册表为空 = 重启)的回放序列逐字节相等;两者经共享
  4588. // reducer 归约出的 workflowRuns 自然也相等。
  4589. describe("dynamic workflow run service — replayProgressForSession(冷回放)", () => {
  4590. const REPLAY_SCRIPT = [
  4591. "interface Answer { text: string }",
  4592. 'const a = await agent("worker").ask<Answer>("do the thing");',
  4593. 'await artifact.markdown("summary", a.text);',
  4594. "return a.text;",
  4595. ].join("\n");
  4596. /** 最小产物存储:只为让 `artifact.markdown` 能发布(读面不在本组用例的范围里)。 */
  4597. function artifactStore(): ToolArtifactStorePort {
  4598. let next = 0;
  4599. return {
  4600. writeToolResultArtifact: async (request) => {
  4601. next += 1;
  4602. return {
  4603. id: `artifact-${next}`,
  4604. uri: `zcode-artifact://replay/artifact-${next}`,
  4605. bytes: Buffer.byteLength(request.content, "utf8"),
  4606. contentType: request.contentType ?? "text/plain",
  4607. createdAt: new Date(0),
  4608. };
  4609. },
  4610. readToolResultArtifact: async () => {
  4611. throw new Error("not read in replay tests");
  4612. },
  4613. readToolResultBinaryArtifact: async () => {
  4614. throw new Error("not read in replay tests");
  4615. },
  4616. };
  4617. }
  4618. function reduceAll(payloads: readonly DynamicWorkflowRunProgressPayload[]) {
  4619. let state: WorkflowRunsState | undefined;
  4620. for (const payload of payloads) {
  4621. state = reduceWorkflowRunsState(state, payload as WorkflowRunProgressEnvelope) ?? state;
  4622. }
  4623. return state;
  4624. }
  4625. it("跑完一个 run 后,新实例的回放载荷与 live 载荷逐字节相等,归约态深等且过 strict schema", async () => {
  4626. await withSqliteJournal(async (journal) => {
  4627. const live = makeHarness({ artifactStore: artifactStore(), journal });
  4628. const toolCallId = createToolCallId("call-replay");
  4629. const runId = await submitRun(live, {
  4630. cwd: projectCwd,
  4631. name: "replay me",
  4632. parentSessionId: HARNESS_PARENT_SESSION,
  4633. scriptText: REPLAY_SCRIPT,
  4634. toolCallId,
  4635. trace: traceFor("replay-live"),
  4636. });
  4637. await settle(live, runId);
  4638. expect(journal.getRun(runId)?.status).toBe("completed");
  4639. // 有东西可比:actor、节点、用量、产物、settle 都在这条 run 上。
  4640. const kinds = new Set(live.runEvents.map((event) => event.eventType));
  4641. for (const kind of [
  4642. "run-started",
  4643. "actor-created",
  4644. "node-settled",
  4645. "usage-updated",
  4646. "artifact-published",
  4647. "run-settled",
  4648. ]) {
  4649. expect(kinds.has(kind)).toBe(true);
  4650. }
  4651. // 「重启」= 同一份 journal 上再造一个 service:注册表为空,内存里没有任何事件。
  4652. const cold = makeHarness({ artifactStore: artifactStore(), journal });
  4653. const replayed = await cold.service.replayProgressForSession!({ excludeRunIds: new Set() });
  4654. expect(replayed).toEqual(live.runEvents);
  4655. // 宿主派生字段也要两侧一致:`concurrencyCeiling` 只活在载荷里(引擎不知道机器有几个核),
  4656. // 冷回放少铸一个键就是一次静默的投影分叉——上面那条相等断言正是它的护栏,这里把「它确实
  4657. // 在场且是默认并发」单独钉住,免得两侧一起缺席时相等断言依然通过。
  4658. const startedCeiling = (event: DynamicWorkflowRunProgressPayload | undefined) =>
  4659. (event?.payload as { concurrencyCeiling?: number } | undefined)?.concurrencyCeiling;
  4660. const liveStarted = live.runEvents.find((event) => event.eventType === "run-started");
  4661. const coldStarted = replayed.find((event) => event.eventType === "run-started");
  4662. expect(startedCeiling(liveStarted)).toBe(resolveWorkflowDefaultConcurrency());
  4663. expect(startedCeiling(coldStarted)).toBe(startedCeiling(liveStarted));
  4664. const liveState = reduceAll(live.runEvents);
  4665. const coldState = reduceAll(replayed);
  4666. expect(coldState).toEqual(liveState);
  4667. expect(coldState?.runs[0]).toMatchObject({
  4668. runId,
  4669. status: "completed",
  4670. toolCallId: String(toolCallId),
  4671. });
  4672. expect(coldState?.runs[0]?.actors.length).toBeGreaterThan(0);
  4673. expect(coldState?.runs[0]?.nodes.length).toBeGreaterThan(0);
  4674. expect(coldState?.runs[0]?.usage.spentTokens).toBeGreaterThan(0);
  4675. expect(workflowRunsStateSchema.parse(coldState)).toEqual(coldState);
  4676. });
  4677. });
  4678. it("cancelled 行同样携 resumable;行终态且事件流已含 run-settled 时不再合成第二条", async () => {
  4679. const journal = new SweepableJournalStore();
  4680. preloadRun(journal, {
  4681. runId: "dwfrun-cancelled",
  4682. parentSessionId: HARNESS_PARENT_SESSION,
  4683. scriptText: TYPED_SCRIPT,
  4684. status: "stopped",
  4685. stopReason: "user",
  4686. });
  4687. journal.appendEvent("dwfrun-cancelled", {
  4688. type: "run-started",
  4689. caps: { maxConcurrency: 4 },
  4690. } as never);
  4691. journal.appendEvent("dwfrun-cancelled", {
  4692. type: "run-settled",
  4693. status: "stopped",
  4694. stopReason: "user",
  4695. } as never);
  4696. preloadRun(journal, {
  4697. runId: "dwfrun-crashed",
  4698. parentSessionId: HARNESS_PARENT_SESSION,
  4699. scriptText: TYPED_SCRIPT,
  4700. status: "errored",
  4701. failure: { code: "DriverError", message: "script threw" },
  4702. });
  4703. journal.appendEvent("dwfrun-crashed", {
  4704. type: "run-started",
  4705. caps: { maxConcurrency: 4 },
  4706. } as never);
  4707. const harness = makeHarness({ journal });
  4708. const replayed = await harness.service.replayProgressForSession!({ excludeRunIds: new Set() });
  4709. const byRun = new Map<string, DynamicWorkflowRunProgressPayload[]>();
  4710. for (const event of replayed) {
  4711. byRun.set(event.runId, [...(byRun.get(event.runId) ?? []), event]);
  4712. }
  4713. // 已含 settle:恰一条,且按行谓词补上 resumable(老 journal 的 settle 事件不带该位)。
  4714. const cancelled = byRun.get("dwfrun-cancelled") ?? [];
  4715. expect(cancelled.filter((event) => event.eventType === "run-settled")).toHaveLength(1);
  4716. expect(cancelled.at(-1)?.payload).toMatchObject({
  4717. status: "stopped",
  4718. stopReason: "user",
  4719. resumable: true,
  4720. });
  4721. // 脚本真失败:合成 settle 不带 resumable。
  4722. const crashed = byRun.get("dwfrun-crashed") ?? [];
  4723. expect(crashed.at(-1)?.payload).toEqual({
  4724. status: "errored",
  4725. error: { code: "DriverError", message: "script threw" },
  4726. });
  4727. });
  4728. it("排除集:内存里已有的 runId 与注册表在飞的 run 不回放;兄弟会话的 run 不进;上界 8 且最旧优先", async () => {
  4729. const journal = new SweepableJournalStore();
  4730. for (let index = 1; index <= 10; index += 1) {
  4731. preloadRun(journal, {
  4732. runId: `dwfrun-old-${index}`,
  4733. parentSessionId: HARNESS_PARENT_SESSION,
  4734. scriptText: TYPED_SCRIPT,
  4735. status: "completed",
  4736. });
  4737. journal.appendEvent(`dwfrun-old-${index}`, {
  4738. type: "run-started",
  4739. caps: { maxConcurrency: 4 },
  4740. } as never);
  4741. journal.appendEvent(`dwfrun-old-${index}`, {
  4742. type: "run-settled",
  4743. status: "completed",
  4744. } as never);
  4745. }
  4746. preloadRun(journal, {
  4747. runId: "dwfrun-sibling",
  4748. parentSessionId: "ses_other",
  4749. scriptText: TYPED_SCRIPT,
  4750. status: "completed",
  4751. });
  4752. journal.appendEvent("dwfrun-sibling", {
  4753. type: "run-started",
  4754. caps: { maxConcurrency: 4 },
  4755. } as never);
  4756. const harness = makeHarness({ hangActors: true, journal });
  4757. const inFlight = await submitRun(harness, {
  4758. cwd: projectCwd,
  4759. parentSessionId: HARNESS_PARENT_SESSION,
  4760. scriptText: TYPED_SCRIPT,
  4761. trace: traceFor("replay-in-flight"),
  4762. });
  4763. await vi.waitFor(() => {
  4764. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  4765. });
  4766. const replayed = await harness.service.replayProgressForSession!({
  4767. excludeRunIds: new Set(["dwfrun-old-10"]),
  4768. });
  4769. const order: string[] = [];
  4770. for (const event of replayed) {
  4771. if (order.at(-1) !== event.runId) order.push(event.runId);
  4772. }
  4773. // 枚举面给最近 8 条(old-3..old-10 与在飞的那条里最近的 8 条),回放最旧优先;
  4774. // 在飞的与被排除的都不在,兄弟会话的更不在。
  4775. expect(order).not.toContain(inFlight);
  4776. expect(order).not.toContain("dwfrun-old-10");
  4777. expect(order).not.toContain("dwfrun-sibling");
  4778. expect(order).toEqual([
  4779. "dwfrun-old-4",
  4780. "dwfrun-old-5",
  4781. "dwfrun-old-6",
  4782. "dwfrun-old-7",
  4783. "dwfrun-old-8",
  4784. "dwfrun-old-9",
  4785. ]);
  4786. expect(await harness.service.cancel(inFlight)).toBe(true);
  4787. await settle(harness, inFlight);
  4788. });
  4789. it("内存 journal(无枚举面):回放回空", async () => {
  4790. const harness = makeHarness({ journal: new InMemoryJournalStore() });
  4791. await expect(
  4792. harness.service.replayProgressForSession!({ excludeRunIds: new Set() }),
  4793. ).resolves.toEqual([]);
  4794. });
  4795. });
  4796. describe("dynamic workflow run service — listRunsForSession", () => {
  4797. it("回本会话的 run 摘要,resumable 与 resume 门同源", async () => {
  4798. const journal = new SweepableJournalStore();
  4799. const seed = (input: {
  4800. runId: string;
  4801. status: RunStatus;
  4802. failure?: { code: string; message: string };
  4803. stopReason?: RunStopReason;
  4804. toolCallId?: string;
  4805. parentSessionId?: string;
  4806. }): void => {
  4807. journal.createRun({
  4808. runId: input.runId,
  4809. parentSessionId: input.parentSessionId ?? HARNESS_PARENT_SESSION,
  4810. scriptText: TYPED_SCRIPT,
  4811. caps: { maxConcurrency: 4 },
  4812. spentTokens: 0,
  4813. status: input.status,
  4814. ...(input.stopReason === undefined ? {} : { stopReason: input.stopReason }),
  4815. ...(input.failure === undefined ? {} : { failure: input.failure as never }),
  4816. ...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),
  4817. });
  4818. };
  4819. seed({ runId: "dwfrun-done", status: "completed", toolCallId: "call-done" });
  4820. seed({
  4821. runId: "dwfrun-stopped",
  4822. status: "stopped",
  4823. stopReason: "user",
  4824. toolCallId: "call-stopped",
  4825. });
  4826. seed({
  4827. runId: "dwfrun-interrupted",
  4828. status: "stopped",
  4829. stopReason: "interrupted",
  4830. failure: { code: "Interrupted", message: "owning process exited" },
  4831. });
  4832. seed({
  4833. runId: "dwfrun-crashed",
  4834. status: "errored",
  4835. failure: { code: "DriverError", message: "script threw" },
  4836. });
  4837. seed({
  4838. runId: "dwfrun-other",
  4839. status: "stopped",
  4840. stopReason: "user",
  4841. parentSessionId: "ses_other",
  4842. });
  4843. const harness = makeHarness({ journal });
  4844. const summaries = await harness.service.listRunsForSession?.();
  4845. expect(summaries?.map((summary) => summary.runId).sort()).toEqual([
  4846. "dwfrun-crashed",
  4847. "dwfrun-done",
  4848. "dwfrun-interrupted",
  4849. "dwfrun-stopped",
  4850. ]);
  4851. const byId = new Map(summaries?.map((summary) => [summary.runId, summary]));
  4852. expect(byId.get("dwfrun-stopped")).toMatchObject({
  4853. resumable: true,
  4854. status: "stopped",
  4855. stopReason: "user",
  4856. toolCallId: "call-stopped",
  4857. });
  4858. expect(byId.get("dwfrun-interrupted")).toMatchObject({
  4859. failureCode: "Interrupted",
  4860. resumable: true,
  4861. status: "stopped",
  4862. stopReason: "interrupted",
  4863. });
  4864. expect(byId.get("dwfrun-done")).toMatchObject({ resumable: false, status: "completed" });
  4865. expect(byId.get("dwfrun-crashed")).toMatchObject({
  4866. failureCode: "DriverError",
  4867. resumable: false,
  4868. });
  4869. });
  4870. it("journal 无枚举能力(内存实现)时回空列表而不是抛错", async () => {
  4871. const harness = makeHarness({ journal: new InMemoryJournalStore() });
  4872. await expect(harness.service.listRunsForSession?.()).resolves.toEqual([]);
  4873. });
  4874. // label 与工具面共用 resolveDynamicWorkflowRunLabel:枚举面自己拼一次兜底,同一个 run
  4875. // 就会在 /dwf list 与工具卡上显示两个名字(docs/dynamic-workflow/launch.md「`/dwf`」)。
  4876. it("label 走 name → 脚本首行 → runId 的同一条派生链", async () => {
  4877. const journal = new SweepableJournalStore();
  4878. const seed = (input: { runId: string; name?: string; scriptText?: string }): void => {
  4879. journal.createRun({
  4880. runId: input.runId,
  4881. parentSessionId: HARNESS_PARENT_SESSION,
  4882. ...(input.scriptText === undefined ? {} : { scriptText: input.scriptText }),
  4883. ...(input.name === undefined ? {} : { name: input.name }),
  4884. caps: { maxConcurrency: 4 },
  4885. spentTokens: 0,
  4886. status: "completed",
  4887. });
  4888. };
  4889. seed({ runId: "dwfrun-named", name: "nightly audit", scriptText: TYPED_SCRIPT });
  4890. seed({ runId: "dwfrun-unnamed", scriptText: TYPED_SCRIPT });
  4891. // 全空白的 name 与没起名等价——否则列表里是一行不可点的空白。
  4892. seed({ runId: "dwfrun-blank", name: " ", scriptText: TYPED_SCRIPT });
  4893. seed({ runId: "dwfrun-bare" });
  4894. const harness = makeHarness({ journal });
  4895. const byId = new Map(
  4896. (await harness.service.listRunsForSession?.())?.map((summary) => [summary.runId, summary]),
  4897. );
  4898. expect(byId.get("dwfrun-named")?.label).toBe("nightly audit");
  4899. expect(byId.get("dwfrun-unnamed")?.label).toBe("interface Answer { text: string }");
  4900. expect(byId.get("dwfrun-blank")?.label).toBe("interface Answer { text: string }");
  4901. expect(byId.get("dwfrun-bare")?.label).toBe("dwfrun-bare");
  4902. });
  4903. // updatedAt 直读 journal 行的 time_updated:`RunRecord` 不带时间,所以枚举面必须走窄投影
  4904. // 的行类型(DwfRunSessionListItem)——回退到 RunRecord 会让这个字段静默变成 undefined。
  4905. it("updatedAt 透传 journal 行的 time_updated", async () => {
  4906. const journal = new SweepableJournalStore();
  4907. preloadRun(journal, {
  4908. runId: "dwfrun-timed",
  4909. parentSessionId: HARNESS_PARENT_SESSION,
  4910. scriptText: TYPED_SCRIPT,
  4911. status: "completed",
  4912. });
  4913. const harness = makeHarness({ journal });
  4914. const [summary] = (await harness.service.listRunsForSession?.()) ?? [];
  4915. expect(summary?.updatedAt).toBe(journal.rowTimeOf("dwfrun-timed"));
  4916. });
  4917. // failure 必须活过窄投影:模型面要报 failureCode / failureMessage(「进程死了」这条事实
  4918. // 以 Interrupted 码为第二证据),resumable 由 status === "stopped" 判定。
  4919. it("窄投影仍带 failure,stopped(interrupted) 判可恢复", async () => {
  4920. const journal = new SweepableJournalStore();
  4921. preloadRun(journal, {
  4922. runId: "dwfrun-interrupted",
  4923. failure: { code: "Interrupted", message: "owning process exited" },
  4924. parentSessionId: HARNESS_PARENT_SESSION,
  4925. scriptText: TYPED_SCRIPT,
  4926. status: "stopped",
  4927. stopReason: "interrupted",
  4928. });
  4929. const harness = makeHarness({ journal });
  4930. const [summary] = (await harness.service.listRunsForSession?.()) ?? [];
  4931. expect(summary).toMatchObject({
  4932. failureCode: "Interrupted",
  4933. failureMessage: "owning process exited",
  4934. resumable: true,
  4935. status: "stopped",
  4936. stopReason: "interrupted",
  4937. });
  4938. });
  4939. });
  4940. // ————————————————————————————————————————————————————————————————
  4941. // amend-resume(修订续跑):apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  4942. // ————————————————————————————————————————————————————————————————
  4943. /**
  4944. * 一个具名 actor 问两次 + 一次 world-read 的脚本;`tail` 参数改的是**第二问**的正文,
  4945. * 因此 seq 0 恒命中、seq 1 恒分歧——这正是「前缀命中 / 分歧点起 live」要观察的形状。
  4946. */
  4947. function amendScript(tail: string): string {
  4948. return [
  4949. "interface Answer { text: string }",
  4950. 'const w = agent("worker");',
  4951. 'const paths = await files.glob("src/**/*.ts");',
  4952. 'const first = await w.ask<Answer>("first question");',
  4953. `const last = await w.ask<Answer>(${JSON.stringify(tail)});`,
  4954. "return `${first.text}|${last.text}|${paths.length}`;",
  4955. ].join("\n");
  4956. }
  4957. /**
  4958. * 两个具名 actor 各问一次:崩溃后重建用例靠它把「未消费的导入」留在 beta 上。
  4959. *
  4960. * 追记 2026-09-12:persona 不再声明工具档位,所以任一 ask 分歧转 live 都会**关闭**导入缓存
  4961. * (apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。修订 alpha 之后 beta 的导入永远作废——崩溃后重建
  4962. * 出来的表在这条路径上只用来证明「关门判定从事件恢复」,命中路径见 world 节点用例。
  4963. */
  4964. const TWO_ACTOR_SCRIPT = [
  4965. "interface Answer { text: string }",
  4966. 'const alpha = agent("alpha");',
  4967. 'const beta = agent("beta");',
  4968. 'const a = await alpha.ask<Answer>("alpha question");',
  4969. 'const b = await beta.ask<Answer>("beta question");',
  4970. "return `${a.text}|${b.text}`;",
  4971. ].join("\n");
  4972. /** 某个 run 的 node-settled 事件(含 cached 标志),按发生序。 */
  4973. function settledEvents(
  4974. harness: Harness,
  4975. runId: string,
  4976. ): { siteId: string; ordinal: number; cached: boolean }[] {
  4977. return harness.runEvents
  4978. .filter((event) => event.runId === runId && event.eventType === "node-settled")
  4979. .map((event) => {
  4980. const instance = event.payload.instance as { siteId: string; ordinal: number };
  4981. return { ...instance, cached: event.payload.cached === true };
  4982. });
  4983. }
  4984. /** 模型真的被调了几次(scriptedModelAdapter 的每一轮 turn)。 */
  4985. function turnCount(harness: Harness): number {
  4986. return harness.order.filter((entry) => entry.startsWith("turn:")).length;
  4987. }
  4988. /**
  4989. * 把某个 run 从 `getRun` 上藏起来(前驱被清理的情形)。内存 journal 没有删除面,而这条
  4990. * 降级路径的观察点恰好只有 getRun——Proxy 只改这一个方法,其余(含孤儿收敛 / 枚举的能力探测)
  4991. * 原样转发。
  4992. */
  4993. function withHiddenRun(journal: JournalStorePort, hiddenRunId: string): JournalStorePort {
  4994. return new Proxy(journal, {
  4995. get(target, prop) {
  4996. if (prop === "getRun") {
  4997. return (runId: string) => (runId === hiddenRunId ? undefined : journal.getRun(runId));
  4998. }
  4999. const value = Reflect.get(target, prop, target);
  5000. return typeof value === "function" ? (value as () => unknown).bind(target) : value;
  5001. },
  5002. }) as JournalStorePort;
  5003. }
  5004. // docs/dynamic-workflow/launch.md「Keeping the predecessor's script」:省略 `script` 的 AmendWorkflow
  5005. // 在 resolveInput 里经 getScript 读前驱存档的脚本——与 resume 重放的是同一份字节;`path` 修订的
  5006. // `script_unchanged` 预检读的也是它(要比**字节**,不是哈希)。它是一条单独的读面,
  5007. // 不进 getTask 快照:快照被后台追踪器轮询,脚本是端口上最大的字符串。
  5008. describe("dynamic workflow run service — getScript(修订沿用前驱的脚本)", () => {
  5009. it("回 journal 行上逐字节的 script_text(不 trim、不改换行)", async () => {
  5010. const journal = new SweepableJournalStore();
  5011. const harness = makeHarness({ journal });
  5012. const script = `${TYPED_SCRIPT}\r\n// 尾注:逐字节\n\n`;
  5013. preloadRun(journal, { runId: "dwfrun-stored", scriptText: script, status: "errored" });
  5014. expect(await harness.service.getScript!("dwfrun-stored")).toBe(script);
  5015. });
  5016. it("行上没有脚本(落库之前的老 run)与未知 run 都回 undefined", async () => {
  5017. const journal = new SweepableJournalStore();
  5018. const harness = makeHarness({ journal });
  5019. preloadRun(journal, { runId: "dwfrun-scriptless", status: "completed" });
  5020. expect(await harness.service.getScript!("dwfrun-scriptless")).toBeUndefined();
  5021. expect(await harness.service.getScript!("dwfrun-nope")).toBeUndefined();
  5022. });
  5023. it("submit → createRun 的间隙里读注册表条目上的脚本", async () => {
  5024. await withSqliteJournal(async (real) => {
  5025. const hidden = new Set<string>();
  5026. const harness = makeHarness({ hangActors: true, journal: hideRunsFromReads(real, hidden) });
  5027. const runId = await submitRun(harness, {
  5028. cwd: TEST_CWD,
  5029. scriptText: TYPED_SCRIPT,
  5030. trace: traceFor("get-script-gap"),
  5031. });
  5032. hidden.add(runId);
  5033. expect(await harness.service.getScript!(runId)).toBe(TYPED_SCRIPT);
  5034. await harness.service.cancel(runId);
  5035. await settle(harness, runId);
  5036. });
  5037. });
  5038. it("关闭之后仍可读:它是只读面,不是启动入口", async () => {
  5039. const journal = new SweepableJournalStore();
  5040. const harness = makeHarness({ journal });
  5041. preloadRun(journal, { runId: "dwfrun-closed", scriptText: TYPED_SCRIPT, status: "completed" });
  5042. await harness.service.close();
  5043. expect(await harness.service.getScript!("dwfrun-closed")).toBe(TYPED_SCRIPT);
  5044. });
  5045. });
  5046. describe("dynamic workflow run service — amend 的门", () => {
  5047. it("前驱不存在 → run_not_found,且不建任何 run", async () => {
  5048. const journal = new SweepableJournalStore();
  5049. const createRun = vi.spyOn(journal, "createRun");
  5050. const harness = makeHarness({ journal });
  5051. const result = await harness.service.amend!({
  5052. cwd: TEST_CWD,
  5053. predecessorRunId: "dwfrun-nope",
  5054. scriptText: TYPED_SCRIPT,
  5055. trace: traceFor("amend-missing"),
  5056. });
  5057. expect(result).toEqual({ ok: false, reason: "run_not_found" });
  5058. // 拒绝即零副作用:没有行、没有注册表条目、没有在飞引擎。
  5059. expect(createRun).not.toHaveBeenCalled();
  5060. expect(harness.actorRuntimeInputs).toEqual([]);
  5061. });
  5062. // docs/execution-engine.md「Amend-resume」:在飞的前驱不再被拒(旧 `not_amendable`),而是被 amend
  5063. // 以 `{ superseded: newRunId }` 停下、等它结算、再导入并启动后继——一次调用,没有「停止后轮询到
  5064. // stopped 再重提交」的竞态。
  5065. it("前驱仍在飞 → 停下成 stopped(superseded, supersededBy)、等结算、再启动后继", async () => {
  5066. const harness = makeHarness({ hangActors: true });
  5067. const runA = await submitRun(harness, {
  5068. cwd: TEST_CWD,
  5069. name: "triage",
  5070. scriptText: TYPED_SCRIPT,
  5071. trace: traceFor("amend-live-a"),
  5072. });
  5073. // 等 actor 会话建起来(ask 已派发、turn 在飞),再修订。
  5074. await vi.waitFor(() => {
  5075. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  5076. });
  5077. const amended = await amendRun(harness, {
  5078. cwd: TEST_CWD,
  5079. predecessorRunId: runA,
  5080. scriptText: TYPED_SCRIPT,
  5081. trace: traceFor("amend-live-b"),
  5082. });
  5083. const runB = amended.runId;
  5084. expect(runB).not.toBe(runA);
  5085. expect(amended.supersededRunId).toBe(runA);
  5086. // amend 返回时前驱已经结算(await 的是它自己的 settlement promise,不是超时)。
  5087. const a = harness.journal.getRun(runA);
  5088. expect(a).toMatchObject({ status: "stopped", stopReason: "superseded", supersededBy: runB });
  5089. expect(a?.failure).toBeUndefined();
  5090. const snapshotA = await harness.service.getTask(runA);
  5091. expect(snapshotA).toMatchObject({
  5092. runStatus: "stopped",
  5093. stopReason: "superseded",
  5094. supersededBy: runB,
  5095. });
  5096. // 被替代的 run 不可恢复;后继带 lineage 指针、沿用前驱的名字。
  5097. expect(await harness.service.resume(runA)).toEqual({ ok: false, reason: "superseded" });
  5098. expect((await harness.service.getTask(runB))?.resumedFrom).toBe(runA);
  5099. await vi.waitFor(() => {
  5100. expect(harness.journal.getRun(runB)).toMatchObject({ resumedFrom: runA, name: "triage" });
  5101. });
  5102. // 进度载荷:前驱的 run-settled 带 supersededBy 且**不带** resumable;后继的 run-started 带 resumedFrom。
  5103. const settledA = harness.runEvents.find(
  5104. (event) => event.runId === runA && event.eventType === "run-settled",
  5105. );
  5106. expect(settledA?.payload).toMatchObject({ stopReason: "superseded", supersededBy: runB });
  5107. expect(settledA?.payload).not.toHaveProperty("resumable");
  5108. const startedB = harness.runEvents.find(
  5109. (event) => event.runId === runB && event.eventType === "run-started",
  5110. );
  5111. expect(startedB?.payload).toMatchObject({ resumedFrom: runA });
  5112. // 收尾:后继也挂着(同一份挂住的 actor 脚本),用户取消它。
  5113. expect(await harness.service.cancel(runB)).toBe(true);
  5114. await settle(harness, runB);
  5115. });
  5116. it("预检失败时在飞前驱不被停下", async () => {
  5117. const harness = makeHarness({ hangActors: true });
  5118. const runA = await submitRun(harness, {
  5119. cwd: TEST_CWD,
  5120. scriptText: TYPED_SCRIPT,
  5121. trace: traceFor("amend-preflight-a"),
  5122. });
  5123. await vi.waitFor(() => {
  5124. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  5125. });
  5126. // 让前驱的一个已完结 ask 缺边界:预检必须在停止之前拒绝。
  5127. harness.journal.putNode({
  5128. runId: runA,
  5129. siteId: "ask#99",
  5130. ordinal: 99,
  5131. kind: "ask",
  5132. actorSiteId: "actor#1",
  5133. actorOrdinal: 1,
  5134. actorSeq: 7,
  5135. inputHash: "h99",
  5136. status: "completed",
  5137. result: { text: "done" },
  5138. });
  5139. const result = await harness.service.amend!({
  5140. cwd: TEST_CWD,
  5141. predecessorRunId: runA,
  5142. scriptText: TYPED_SCRIPT,
  5143. trace: traceFor("amend-preflight-b"),
  5144. });
  5145. expect(result).toEqual({ ok: false, reason: "missing_boundaries" });
  5146. expect(harness.journal.getRun(runA)?.status).toBe("running");
  5147. expect(harness.service.countLiveRuns()).toBe(1);
  5148. expect(await harness.service.cancel(runA)).toBe(true);
  5149. await settle(harness, runA);
  5150. });
  5151. it("前驱的已完结 ask 缺边界 marker → missing_boundaries", async () => {
  5152. const journal = new SweepableJournalStore();
  5153. const harness = makeHarness({ journal });
  5154. preloadRun(journal, { runId: "dwfrun-old", scriptText: TYPED_SCRIPT, status: "completed" });
  5155. journal.putActor({
  5156. runId: "dwfrun-old",
  5157. siteId: "actor#1",
  5158. ordinal: 1,
  5159. name: "worker",
  5160. persona: { name: "worker" },
  5161. sessionId: "sess-old",
  5162. });
  5163. journal.putNode({
  5164. runId: "dwfrun-old",
  5165. siteId: "ask#1",
  5166. ordinal: 1,
  5167. kind: "ask",
  5168. actorSiteId: "actor#1",
  5169. actorOrdinal: 1,
  5170. actorSeq: 0,
  5171. inputHash: "h0",
  5172. status: "completed",
  5173. result: { text: "done" },
  5174. });
  5175. const result = await harness.service.amend!({
  5176. cwd: TEST_CWD,
  5177. predecessorRunId: "dwfrun-old",
  5178. scriptText: TYPED_SCRIPT,
  5179. trace: traceFor("amend-no-marker"),
  5180. });
  5181. expect(result).toEqual({ ok: false, reason: "missing_boundaries" });
  5182. });
  5183. // 可修订集 = 任意终态。completed 与「脚本真失败」恰恰是 plain resume 排除、而修订最有用的两类。
  5184. it.each(["completed", "errored", "stopped"] as const)("终态 %s 的前驱通过门", async (status) => {
  5185. const journal = new SweepableJournalStore();
  5186. const harness = makeHarness({ journal });
  5187. preloadRun(journal, { runId: `dwfrun-${status}`, scriptText: TYPED_SCRIPT, status });
  5188. const result = await harness.service.amend!({
  5189. cwd: TEST_CWD,
  5190. predecessorRunId: `dwfrun-${status}`,
  5191. scriptText: TYPED_SCRIPT,
  5192. trace: traceFor(`amend-${status}`),
  5193. });
  5194. expect(result.ok).toBe(true);
  5195. if (!result.ok) return;
  5196. // 前驱早已结算:没有 supersededRunId。
  5197. expect(result.supersededRunId).toBeUndefined();
  5198. await settle(harness, result.runId);
  5199. expect(harness.journal.getRun(result.runId)?.resumedFrom).toBe(`dwfrun-${status}`);
  5200. });
  5201. });
  5202. describe("dynamic workflow run service — amend-resume 的温启动", () => {
  5203. // docs/dynamic-workflow/launch.md「Keeping the predecessor's script」的端到端证据:真实的 AmendWorkflow
  5204. // 工具(executor → resolveInput → getScript → prepareApproval → handler)接真实的 run service。
  5205. // 只改并发上界的修订跑的是前驱逐字节的脚本,所以每一问都命中缓存:零 turn,上界却换成了新值。
  5206. it("AmendWorkflow 省略 script:工具经 getScript 沿用前驱脚本,全部命中缓存、只换上界", async () => {
  5207. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-keep-"));
  5208. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5209. const journal = new SweepableJournalStore();
  5210. try {
  5211. const script = amendScript("second question");
  5212. const before = makeHarness({
  5213. actorScripts: {
  5214. "actor#1@1": [
  5215. { kind: "submit", result: { text: "one" } },
  5216. { kind: "submit", result: { text: "two" } },
  5217. ],
  5218. },
  5219. journal,
  5220. sessionStore: store as never,
  5221. });
  5222. const runA = await submitRun(before, {
  5223. cwd: TEST_CWD,
  5224. scriptText: script,
  5225. trace: traceFor("amend-keep-predecessor"),
  5226. });
  5227. await settle(before, runA);
  5228. expect(journal.getRun(runA)?.caps.maxConcurrency).not.toBe(1);
  5229. // 修订 run 的 actor 没有任何脚本化回答:只要有一问转 live,它就拿不到结果。
  5230. const after = makeHarness({ journal, sessionStore: store as never });
  5231. const registry = createToolRegistry();
  5232. const amendEntry = builtInTools.find((entry) => entry.metadata.name === "AmendWorkflow");
  5233. expect(amendEntry).toBeDefined();
  5234. registry.register(amendEntry!);
  5235. const sessionId = createSessionId("amend-keep-tool");
  5236. const turnId = createTurnId("amend-keep-tool");
  5237. const traceContext = createRootTraceContext({ sessionId, turnId });
  5238. const permissionAsks: string[] = [];
  5239. const executor = createToolExecutor({
  5240. emitEvent: async () => {},
  5241. dynamicWorkflowRunPort: after.service,
  5242. mode: "build",
  5243. // 前驱不属于本会话(submit 没带 parentSessionId):会弹窗,这里一律同意。
  5244. permissionBroker: {
  5245. async requestPermission(request) {
  5246. permissionAsks.push(JSON.stringify(request));
  5247. return { decision: "allow" as const };
  5248. },
  5249. },
  5250. permissionService: new PermissionService(defaultPermissionConfig),
  5251. registry,
  5252. sessionId,
  5253. turnId,
  5254. traceContext,
  5255. workingDirectory: TEST_CWD,
  5256. });
  5257. const result = await executor.execute(
  5258. {
  5259. id: createToolCallId("amend-keep-tool"),
  5260. input: { run_id: runA, max_concurrency: 1 },
  5261. name: "AmendWorkflow",
  5262. },
  5263. { traceContext },
  5264. );
  5265. expect(result.success).toBe(true);
  5266. // 确认窗审的是将要跑的那一份脚本(回填进入参),并带着「沿用」的 flag。
  5267. expect(permissionAsks).toHaveLength(1);
  5268. expect(permissionAsks[0]).toContain('"script_inherited":true');
  5269. const output = result.output as { backgroundTaskId?: string; response: string };
  5270. const runB = output.backgroundTaskId;
  5271. expect(runB).toBeDefined();
  5272. expect(output.response).toContain(`The script of run ${runA} started unchanged`);
  5273. await settle(after, runB!);
  5274. const rowB = journal.getRun(runB!);
  5275. expect(rowB?.scriptText).toBe(script);
  5276. expect(rowB?.caps.maxConcurrency).toBe(1);
  5277. expect(rowB?.resumedFrom).toBe(runA);
  5278. // 沿用的脚本也有家(docs/dynamic-workflow/launch.md「Provenance」):前驱没记过文件,所以工具
  5279. // 把存档的脚本落成草稿,新 run 记的就是它——下一次修订去编辑这个文件,不必内联重抄。
  5280. const recordedScriptPath = (await after.service.getTask(runB!))?.scriptPath;
  5281. expect(recordedScriptPath).toBeDefined();
  5282. expect(readFileSync(recordedScriptPath!, "utf8")).toBe(script);
  5283. expect((await after.service.getTask(runB!))?.output).toBe("one|two|0");
  5284. expect(turnCount(after)).toBe(0);
  5285. expect(settledEvents(after, runB!)).toEqual([
  5286. { siteId: "world-read#1", ordinal: 1, cached: true },
  5287. { siteId: "ask#1", ordinal: 1, cached: true },
  5288. { siteId: "ask#2", ordinal: 1, cached: true },
  5289. ]);
  5290. } finally {
  5291. store.close();
  5292. await rm(tempRoot, { force: true, recursive: true });
  5293. }
  5294. });
  5295. // docs/dynamic-workflow/presentation.md「Subagent transcripts」与「Reduction」的端到端证据:
  5296. // 修订 run 从空表开始,缓存命中又没有 node-queued——命中的结算必须自己点名子代理,否则 GUI 上
  5297. // 一个全部 ask 都命中的子代理是「待开始」,点开是「尚未启动」(2026-09-22 用户报告)。
  5298. it("修订 run 的缓存命中归到子代理名下,transcript 指向前驱里真有消息的那条会话;分歧后换回本 run 的", async () => {
  5299. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-attrib-"));
  5300. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5301. const journal = new SweepableJournalStore();
  5302. try {
  5303. const before = makeHarness({
  5304. actorScripts: {
  5305. "actor#1@1": [
  5306. { kind: "submit", result: { text: "one" } },
  5307. { kind: "submit", result: { text: "two" } },
  5308. ],
  5309. },
  5310. journal,
  5311. sessionStore: store as never,
  5312. });
  5313. const runA = await submitRun(before, {
  5314. cwd: TEST_CWD,
  5315. scriptText: amendScript("second question"),
  5316. trace: traceFor("amend-attrib-predecessor"),
  5317. });
  5318. await settle(before, runA);
  5319. const predecessorSession = before.runEvents.find(
  5320. (event) => event.runId === runA && event.eventType === "actor-created",
  5321. )?.actorSessionId;
  5322. expect(predecessorSession).toBeDefined();
  5323. expect((await store.messages({ sessionID: predecessorSession! })).length).toBeGreaterThan(0);
  5324. // —— 同一份脚本的修订:每一问都命中,零 turn。
  5325. const same = makeHarness({ journal, sessionStore: store as never });
  5326. const unchanged = await amendRun(same, {
  5327. cwd: TEST_CWD,
  5328. predecessorRunId: runA,
  5329. scriptText: amendScript("second question"),
  5330. trace: traceFor("amend-attrib-same"),
  5331. });
  5332. await settle(same, unchanged.runId);
  5333. expect(turnCount(same)).toBe(0);
  5334. const ownSession = same.runEvents.find(
  5335. (event) => event.runId === unchanged.runId && event.eventType === "actor-created",
  5336. )?.actorSessionId;
  5337. expect(ownSession).toBeDefined();
  5338. expect(ownSession).not.toBe(predecessorSession);
  5339. const cachedRun = reduceAll(same)?.runs.find((run) => run.runId === unchanged.runId);
  5340. expect(
  5341. cachedRun?.nodes.map((node) => [
  5342. node.siteId,
  5343. node.cached === true,
  5344. node.actorSiteId === undefined ? null : `${node.actorSiteId}@${node.actorOrdinal}`,
  5345. ]),
  5346. ).toEqual([
  5347. ["world-read#1", true, null],
  5348. ["ask#1", true, "actor#1@1"],
  5349. ["ask#2", true, "actor#1@1"],
  5350. ]);
  5351. expect(cachedRun?.nodes.find((node) => node.siteId === "ask#2")?.instructionsHead).toBe(
  5352. "second question",
  5353. );
  5354. // 本 run 从未给它建会话:transcript 要去前驱里读,而那条会话真有消息。
  5355. expect(cachedRun?.actors).toMatchObject([
  5356. { siteId: "actor#1", ordinal: 1, status: "completed", sessionId: predecessorSession },
  5357. ]);
  5358. // —— 改了第二问的修订:第一问命中(前驱会话),第二问 live(本 run 的会话,种子里有前缀)。
  5359. const diverged = makeHarness({
  5360. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "revised" } }] },
  5361. journal,
  5362. sessionStore: store as never,
  5363. });
  5364. const revised = await amendRun(diverged, {
  5365. cwd: TEST_CWD,
  5366. predecessorRunId: runA,
  5367. scriptText: amendScript("second question, revised"),
  5368. trace: traceFor("amend-attrib-revised"),
  5369. });
  5370. await settle(diverged, revised.runId);
  5371. const revisedSession = diverged.runEvents.find(
  5372. (event) => event.runId === revised.runId && event.eventType === "actor-created",
  5373. )?.actorSessionId;
  5374. const firstSettle = diverged.runEvents.find(
  5375. (event) =>
  5376. event.runId === revised.runId &&
  5377. event.eventType === "node-settled" &&
  5378. (event.payload.instance as { siteId: string }).siteId === "ask#1",
  5379. );
  5380. expect(firstSettle?.payload).toMatchObject({
  5381. cached: true,
  5382. kind: "ask",
  5383. actor: { siteId: "actor#1", ordinal: 1 },
  5384. sourceSessionId: predecessorSession,
  5385. });
  5386. const revisedRun = reduceAll(diverged)?.runs.find((run) => run.runId === revised.runId);
  5387. expect(revisedRun?.actors).toMatchObject([
  5388. { siteId: "actor#1", status: "completed", sessionId: revisedSession },
  5389. ]);
  5390. expect((await store.messages({ sessionID: revisedSession! })).length).toBeGreaterThan(0);
  5391. } finally {
  5392. store.close();
  5393. await rm(tempRoot, { force: true, recursive: true });
  5394. }
  5395. });
  5396. it("前缀零派发命中、分歧点起 live、边界与 lineage 落库", async () => {
  5397. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-"));
  5398. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5399. const journal = new SweepableJournalStore();
  5400. try {
  5401. // —— 前驱 run:两问都 live,边界与会话都真的落库。
  5402. const before = makeHarness({
  5403. actorScripts: {
  5404. "actor#1@1": [
  5405. { kind: "submit", result: { text: "one" } },
  5406. { kind: "submit", result: { text: "two" } },
  5407. ],
  5408. },
  5409. journal,
  5410. sessionStore: store as never,
  5411. });
  5412. const runA = await submitRun(before, {
  5413. cwd: TEST_CWD,
  5414. scriptText: amendScript("second question"),
  5415. trace: traceFor("amend-predecessor"),
  5416. });
  5417. await settle(before, runA);
  5418. expect((await before.service.getTask(runA))?.output).toBe("one|two|0");
  5419. expect(turnCount(before)).toBe(2);
  5420. // —— 修订 run:只改第二问。
  5421. const after = makeHarness({
  5422. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "revised" } }] },
  5423. journal,
  5424. sessionStore: store as never,
  5425. });
  5426. const submitted = await after.service.amend!({
  5427. cwd: TEST_CWD,
  5428. predecessorRunId: runA,
  5429. scriptText: amendScript("second question, revised"),
  5430. trace: traceFor("amend-run"),
  5431. });
  5432. expect(submitted.ok).toBe(true);
  5433. if (!submitted.ok) return;
  5434. const runB = submitted.runId;
  5435. await settle(after, runB);
  5436. // 第一问的答案原样来自前驱,第二问是新跑出来的。
  5437. expect((await after.service.getTask(runB))?.output).toBe("one|revised|0");
  5438. // 分歧之后的这一次派发是**唯一**一次:前缀零 token、零调用。
  5439. expect(turnCount(after)).toBe(1);
  5440. // world-read 与 seq 0 的 ask 都以 cached 结算;分歧的 seq 1 不是。
  5441. const settledB = settledEvents(after, runB);
  5442. expect(settledB).toEqual([
  5443. { siteId: "world-read#1", ordinal: 1, cached: true },
  5444. { siteId: "ask#1", ordinal: 1, cached: true },
  5445. { siteId: "ask#2", ordinal: 1, cached: false },
  5446. ]);
  5447. // 命中必落**真行**,且边界一起拷过去——否则 runB 自己就不能再被修订(链式修订的根基)。
  5448. const cachedNode = journal.getNode(runB, "ask#1", 1);
  5449. const sourceNode = journal.getNode(runA, "ask#1", 1);
  5450. expect(cachedNode?.status).toBe("completed");
  5451. expect(cachedNode?.result).toEqual({ text: "one" });
  5452. expect(cachedNode?.messageBoundary).toBe(sourceNode?.messageBoundary);
  5453. expect(cachedNode?.actorSeq).toBe(0);
  5454. // lineage 是行级事实:确认窗与详情页的「续自 run X」从它渲染。
  5455. expect(journal.getRun(runB)?.resumedFrom).toBe(runA);
  5456. // 前驱只读:runA 的行与节点一个字节没动。
  5457. expect(journal.getRun(runA)?.status).toBe("completed");
  5458. expect(journal.getRun(runA)?.resumedFrom).toBeUndefined();
  5459. // 分歧 actor 的会话是**截断复制**出来的:新会话 id、内容为源会话的前 N 条。
  5460. const sourceSession = journal.getActor(runA, "actor#1", 1)?.sessionId;
  5461. const amendedSession = after.actorRuntimeInputs[0]!.sessionId;
  5462. expect(amendedSession).not.toBe(sourceSession);
  5463. // 会话里先有复制来的前缀,再有分歧那一问自己产的消息,所以长度**严格大于**边界。
  5464. const seeded = await store.messages({ sessionID: amendedSession });
  5465. expect(seeded.length).toBeGreaterThan(sourceNode!.messageBoundary!);
  5466. // 记账在复制出来的前缀之上接着数:新 run 自己的边界 = 此刻的会话长度。count offset
  5467. // 跨前缀复制不变,正是这条让 runB 也能再作前驱(链式修订)。
  5468. expect(journal.getNode(runB, "ask#2", 1)?.messageBoundary).toBe(seeded.length);
  5469. // 复制之后走既有的重水化机器,而不是另造一条水化路径。
  5470. expect(after.resumeCalls).toContain(amendedSession);
  5471. // pin 承袭:修订 run 的第一次派发时本 run 还没有解析结果,pin 只能来自前驱。
  5472. expect(after.actorRuntimeInputs[0]!.pinnedModel).toBe(
  5473. journal.getActor(runA, "actor#1", 1)?.resolvedModel,
  5474. );
  5475. } finally {
  5476. store.close();
  5477. await rm(tempRoot, { force: true, recursive: true });
  5478. }
  5479. });
  5480. // ————————————————————————————————————————————————————————————————
  5481. // 在飞 ask 的接续(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  5482. // 「What is imported」「How the engine consumes the cache」)
  5483. // ————————————————————————————————————————————————————————————————
  5484. /** 一个会话里每条消息的「角色 + 正文」;种子复制会重铸 id,所以只有正文经得起跨会话比对。 */
  5485. async function transcriptOf(
  5486. store: { messages(input: { sessionID: SessionId }): Promise<MessageWithParts[]> },
  5487. sessionId: SessionId,
  5488. ): Promise<string[]> {
  5489. const messages = await store.messages({ sessionID: sessionId });
  5490. return messages.map((message) => {
  5491. const text = message.parts
  5492. .map((part) => (part.type === "text" ? part.text : `<${part.type}>`))
  5493. .join("");
  5494. return `${message.info.role}:${text}`;
  5495. });
  5496. }
  5497. /**
  5498. * 前驱跑到「第一问已完结、第二问在飞」再停下,用**逐字节相同**的脚本修订它。
  5499. *
  5500. * 这正是本特性要救的那半场对话:第二问从未结算、没有边界可导入,但它已经跑出来的那段转录
  5501. * 仍在前驱的会话里。修订在同一位置重发同一条指令(inputHash 相符),所以新会话要从那段
  5502. * 转录接着跑,而不是把它扔掉重来。
  5503. */
  5504. /**
  5505. * 「第一问已完结、第二问在飞」的前驱,跑在**同一个** service 上(修订一个在飞 run 只能由
  5506. * 拥有它的那个 service 停下,见 amendDynamicWorkflowRun 的在飞判定)。
  5507. *
  5508. * `plan` 是一张**可变**的计划表:前驱的 adapter 已经把它的挂起 promise 交出去了,不会再读;
  5509. * 修订 run 的 actor runtime 是新造的,从下标 0 重新读这张表。所以换掉表的内容,就等于给
  5510. * 后继换了一套回答。
  5511. */
  5512. async function liveMidAskPredecessor(input: {
  5513. journal: SweepableJournalStore;
  5514. label: string;
  5515. quiesceMs?: number;
  5516. script: string;
  5517. /** 第二问的挂法:理会取消(正常 provider)还是连取消都不理(会话永远写不完)。 */
  5518. stall: "hang-until-cancelled" | "hang";
  5519. store: Awaited<ReturnType<typeof createSqliteSessionStore>>;
  5520. }): Promise<{ harness: Harness; plan: ActorPlan[]; prefixBoundary: number; runA: string }> {
  5521. const { journal, label, script, stall, store } = input;
  5522. const plan: ActorPlan[] = [{ kind: "submit", result: { text: "one" } }, { kind: stall }];
  5523. const harness = makeHarness({
  5524. actorScripts: { "actor#1@1": plan },
  5525. journal,
  5526. ...(input.quiesceMs === undefined ? {} : { quiesceMs: input.quiesceMs }),
  5527. sessionStore: store as never,
  5528. });
  5529. const runA = await submitRun(harness, {
  5530. cwd: TEST_CWD,
  5531. scriptText: script,
  5532. trace: traceFor(`${label}-a`),
  5533. });
  5534. // 等到第二问真的派发出去(第二轮 turn 已经起了)且第一问的边界已经写下。
  5535. await vi.waitFor(() => {
  5536. expect(turnCount(harness)).toBe(2);
  5537. expect(journal.getNode(runA, "ask#1", 1)?.messageBoundary).toBeDefined();
  5538. });
  5539. // 在飞的那条 ask 有行、是 running、没有自己的边界——它正是要被接续的那一条。
  5540. expect(journal.getNode(runA, "ask#2", 1)).toMatchObject({ status: "running", actorSeq: 1 });
  5541. expect(journal.getNode(runA, "ask#2", 1)?.messageBoundary).toBeUndefined();
  5542. plan.length = 0;
  5543. plan.push({ kind: "submit", result: { text: "revised" } });
  5544. return {
  5545. harness,
  5546. plan,
  5547. prefixBoundary: journal.getNode(runA, "ask#1", 1)!.messageBoundary!,
  5548. runA,
  5549. };
  5550. }
  5551. it("前驱在飞的 ask 被同一条指令续上:新会话以前驱**整段**转录开场", async () => {
  5552. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-inflight-"));
  5553. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5554. const journal = new SweepableJournalStore();
  5555. const script = amendScript("second question");
  5556. try {
  5557. const { harness, prefixBoundary, runA } = await liveMidAskPredecessor({
  5558. journal,
  5559. label: "amend-inflight",
  5560. script,
  5561. stall: "hang-until-cancelled",
  5562. store,
  5563. });
  5564. // —— 修订:脚本逐字节相同,所以第二问的 inputHash 与在飞的那条相符。
  5565. const amended = await amendRun(harness, {
  5566. cwd: TEST_CWD,
  5567. predecessorRunId: runA,
  5568. scriptText: script,
  5569. trace: traceFor("amend-inflight-b"),
  5570. });
  5571. const runB = amended.runId;
  5572. expect(amended.supersededRunId).toBe(runA);
  5573. await settle(harness, runB);
  5574. // 前驱那半场对话确实比第一问的边界长——否则这条用例什么都没证明。
  5575. const sourceSession = journal.getActor(runA, "actor#1", 1)!.sessionId! as SessionId;
  5576. const predecessorTranscript = await transcriptOf(store, sourceSession);
  5577. expect(predecessorTranscript.length).toBeGreaterThan(prefixBoundary);
  5578. // 第一问照旧命中缓存;第二问是 live 跑的(它是那条被接续的 ask)。
  5579. expect((await harness.service.getTask(runB))?.output).toBe("one|revised|0");
  5580. expect(settledEvents(harness, runB)).toEqual([
  5581. { siteId: "world-read#1", ordinal: 1, cached: true },
  5582. { siteId: "ask#1", ordinal: 1, cached: true },
  5583. { siteId: "ask#2", ordinal: 1, cached: false },
  5584. ]);
  5585. // 核心断言:新会话的开头**逐条**就是前驱的整段转录(含那半场未完的问答),
  5586. // 而不是只到第一问的边界为止。
  5587. const amendedSession = journal.getActor(runB, "actor#1", 1)!.sessionId! as SessionId;
  5588. expect(amendedSession).not.toBe(sourceSession);
  5589. const amendedTranscript = await transcriptOf(store, amendedSession);
  5590. expect(amendedTranscript.slice(0, predecessorTranscript.length)).toEqual(
  5591. predecessorTranscript,
  5592. );
  5593. // 接续之后 ask 照常 live 跑,所以会话还要更长。
  5594. expect(amendedTranscript.length).toBeGreaterThan(predecessorTranscript.length);
  5595. // 接续过的 ask 的 stats 不记 worldToolCalls:它的转录早于本次派发就存在,
  5596. // 内存里的工具计数只数得到自己跑的那几轮,报 0 会被后来的修订读成「纯」。
  5597. const carried = journal.getNode(runB, "ask#2", 1);
  5598. expect(carried?.status).toBe("completed");
  5599. expect(carried?.stats?.worldToolCalls).toBeUndefined();
  5600. // 记账仍在接续来的转录之上接着数,所以 runB 也能再作前驱(链式修订的根基)。
  5601. expect(carried?.messageBoundary).toBe(amendedTranscript.length);
  5602. } finally {
  5603. store.close();
  5604. await rm(tempRoot, { force: true, recursive: true });
  5605. }
  5606. });
  5607. /**
  5608. * 同一个形状,只把第二问的正文改掉:inputHash 不再相符,那半场对话就**不是**这条指令的
  5609. * 上文了。新会话只接到第一问的边界为止,在飞那段被丢弃——也就是本特性之前的行为。
  5610. */
  5611. it("修订改掉了在飞的那条指令:不接续,新会话只到完结前缀的边界", async () => {
  5612. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-inflight-miss-"));
  5613. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5614. const journal = new SweepableJournalStore();
  5615. try {
  5616. const { harness, prefixBoundary, runA } = await liveMidAskPredecessor({
  5617. journal,
  5618. label: "amend-inflight-miss",
  5619. script: amendScript("second question"),
  5620. stall: "hang-until-cancelled",
  5621. store,
  5622. });
  5623. const amended = await amendRun(harness, {
  5624. cwd: TEST_CWD,
  5625. predecessorRunId: runA,
  5626. scriptText: amendScript("second question, revised"),
  5627. trace: traceFor("amend-inflight-miss-b"),
  5628. });
  5629. await settle(harness, amended.runId);
  5630. const sourceSession = journal.getActor(runA, "actor#1", 1)!.sessionId! as SessionId;
  5631. const predecessorTranscript = await transcriptOf(store, sourceSession);
  5632. // 前驱确实有一段在飞转录可丢(对照组与实验组面对的是同一个形状)。
  5633. expect(predecessorTranscript.length).toBeGreaterThan(prefixBoundary);
  5634. // 新会话的开场恰好是**前缀**那几条,在飞那段一条都没带过来。
  5635. const amendedSession = journal.getActor(amended.runId, "actor#1", 1)!.sessionId! as SessionId;
  5636. const amendedTranscript = await transcriptOf(store, amendedSession);
  5637. expect(amendedTranscript.slice(0, prefixBoundary)).toEqual(
  5638. predecessorTranscript.slice(0, prefixBoundary),
  5639. );
  5640. // 接续那条用例的核心断言的**直接否定**:新会话不以前驱的整段转录开场。
  5641. expect(amendedTranscript.slice(0, predecessorTranscript.length)).not.toEqual(
  5642. predecessorTranscript,
  5643. );
  5644. // 指令变了,所以前驱那半场的提问正文在新会话里根本不出现。
  5645. expect(amendedTranscript).not.toContain(predecessorTranscript[prefixBoundary]);
  5646. } finally {
  5647. store.close();
  5648. await rm(tempRoot, { force: true, recursive: true });
  5649. }
  5650. });
  5651. /**
  5652. * 静默闸门的端到端证据(driver 的账 → amend → 构建器):前驱的第二问连取消都不理会,
  5653. * 它的 turn 永远落不了地,于是那个会话「写完了没有」永远答不上来。
  5654. *
  5655. * 闸门到点后**不**把它当静默继续用:接续取消,完结前缀照旧导入——正是本特性之前的行为。
  5656. */
  5657. it("前驱会话到点仍在被写 → 不接续,完结前缀照旧导入", async () => {
  5658. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-inflight-noisy-"));
  5659. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5660. const journal = new SweepableJournalStore();
  5661. const script = amendScript("second question");
  5662. try {
  5663. const { harness, prefixBoundary, runA } = await liveMidAskPredecessor({
  5664. journal,
  5665. label: "amend-inflight-noisy",
  5666. // 真等满 5 秒没有意义:闸门的上界可注入,正是为了让这条路可测。
  5667. quiesceMs: 5,
  5668. script,
  5669. stall: "hang",
  5670. store,
  5671. });
  5672. const amended = await amendRun(harness, {
  5673. cwd: TEST_CWD,
  5674. predecessorRunId: runA,
  5675. // 指令逐字节相同——所以**只有**静默闸门能解释「没接上」。
  5676. scriptText: script,
  5677. trace: traceFor("amend-inflight-noisy-b"),
  5678. });
  5679. await settle(harness, amended.runId);
  5680. // 前缀照旧命中(它的边界是 journal 事实,与会话此刻长不长无关)。
  5681. expect(settledEvents(harness, amended.runId)).toEqual([
  5682. { siteId: "world-read#1", ordinal: 1, cached: true },
  5683. { siteId: "ask#1", ordinal: 1, cached: true },
  5684. { siteId: "ask#2", ordinal: 1, cached: false },
  5685. ]);
  5686. const sourceSession = journal.getActor(runA, "actor#1", 1)!.sessionId! as SessionId;
  5687. const predecessorTranscript = await transcriptOf(store, sourceSession);
  5688. // 前驱确实有一段在飞转录**可以**被带走,所以「没带走」只能是闸门的功劳。
  5689. expect(predecessorTranscript.length).toBeGreaterThan(prefixBoundary);
  5690. const amendedSession = journal.getActor(amended.runId, "actor#1", 1)!.sessionId! as SessionId;
  5691. const amendedTranscript = await transcriptOf(store, amendedSession);
  5692. expect(amendedTranscript.slice(0, prefixBoundary)).toEqual(
  5693. predecessorTranscript.slice(0, prefixBoundary),
  5694. );
  5695. // 指令逐字节相同,所以提问正文本来就会再出现一次——能分辨「接没接上」的只有这一条:
  5696. // 新会话不以前驱的**整段**转录开场(在飞那半场的回答没被带过来)。
  5697. expect(amendedTranscript.slice(0, predecessorTranscript.length)).not.toEqual(
  5698. predecessorTranscript,
  5699. );
  5700. } finally {
  5701. store.close();
  5702. await rm(tempRoot, { force: true, recursive: true });
  5703. }
  5704. });
  5705. });
  5706. describe("dynamic workflow run service — 脚本读到的 run 身份", () => {
  5707. // facade 的 `run`(docs/dynamic-workflow/authoring.md「The run's identity」):修订得到新 id、
  5708. // `resumedFrom` 指向前驱;resume 沿用同一个 id,前驱 id 从 journal 读回——resume 的入参里
  5709. // 没有它,读不回来脚本就会在续跑那一世看到 undefined。
  5710. // run 身份只进返回值、不进 ask 指令(缓存键);修订靠改问题文本分叉,好让子代理真的派发。
  5711. const identityScript = (question: string): string =>
  5712. [
  5713. "interface Answer { text: string }",
  5714. `const a = await agent("worker").ask<Answer>(${JSON.stringify(question)});`,
  5715. 'return `${run.id}|${run.resumedFrom ?? "-"}|${a.text}`;',
  5716. ].join("\n");
  5717. it("新 run 无前驱;amend 得新 id 并指向前驱;resume 沿用 id 与前驱", async () => {
  5718. // amend 要读前驱的消息边界,所以会话真的落库(同「前缀零派发命中」那条用例)。
  5719. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-run-identity-"));
  5720. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5721. try {
  5722. await runIdentityLifecycle(store);
  5723. } finally {
  5724. store.close();
  5725. await rm(tempRoot, { force: true, recursive: true });
  5726. }
  5727. });
  5728. async function runIdentityLifecycle(
  5729. store: Awaited<ReturnType<typeof createSqliteSessionStore>>,
  5730. ): Promise<void> {
  5731. const journal = new SweepableJournalStore();
  5732. const options: HarnessOptions = {
  5733. journal,
  5734. sessionStore: store as never,
  5735. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "a" } }] },
  5736. };
  5737. const harness = makeHarness(options);
  5738. const runA = await submitRun(harness, {
  5739. cwd: TEST_CWD,
  5740. scriptText: identityScript("first"),
  5741. trace: traceFor("run-identity-a"),
  5742. });
  5743. await settle(harness, runA);
  5744. expect((await harness.service.getTask(runA))?.output).toBe(`${runA}|-|a`);
  5745. // 修订后子代理挂住,好让 run 停在可恢复的位置。
  5746. options.actorScripts = { "actor#1@1": [{ kind: "hang" }] };
  5747. const { runId: runB } = await amendRun(harness, {
  5748. cwd: TEST_CWD,
  5749. predecessorRunId: runA,
  5750. scriptText: identityScript("amended"),
  5751. trace: traceFor("run-identity-b"),
  5752. });
  5753. expect(runB).not.toBe(runA);
  5754. await vi.waitFor(() => {
  5755. expect(harness.actorRuntimeInputs).toHaveLength(2);
  5756. });
  5757. expect(await harness.service.cancel(runB)).toBe(true);
  5758. await settle(harness, runB);
  5759. options.actorScripts = { "actor#1@1": [{ kind: "submit", result: { text: "b" } }] };
  5760. expect(await harness.service.resume!(runB)).toMatchObject({ ok: true, runId: runB });
  5761. await settle(harness, runB);
  5762. expect((await harness.service.getTask(runB))?.output).toBe(`${runB}|${runA}|b`);
  5763. }
  5764. });
  5765. describe("dynamic workflow run service — 用量沿 lineage 累计", () => {
  5766. /**
  5767. * 一轮 scripted turn 的 token 数(见本文件顶部 scriptedModelAdapter 的 usage)。
  5768. * 用量断言要的是准确数字而不是「大于零」:继承来的那部分与本次现跑的那部分必须分得开。
  5769. */
  5770. const TOKENS_PER_TURN = 20;
  5771. it("后继 run 从前驱总量起账:命中不加钱、live turn 才加,前驱行分文不动;链式修订按构造求和", async () => {
  5772. // docs/dynamic-workflow/launch.md「The AmendWorkflow tool」:完成卡与详情页上的 token 是
  5773. // **整条 lineage** 的花费。真 session store:命中要拷消息边界,而预检要求每个完结 ask 都有边界,
  5774. // 链式修订(runB 再作前驱)全靠这条。
  5775. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-lineage-tokens-"));
  5776. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5777. const journal = new SweepableJournalStore();
  5778. try {
  5779. // —— 前驱 runA:两问都 live = 两轮 turn。
  5780. const before = makeHarness({
  5781. actorScripts: {
  5782. "actor#1@1": [
  5783. { kind: "submit", result: { text: "one" } },
  5784. { kind: "submit", result: { text: "two" } },
  5785. ],
  5786. },
  5787. journal,
  5788. sessionStore: store as never,
  5789. });
  5790. const runA = await submitRun(before, {
  5791. cwd: TEST_CWD,
  5792. scriptText: amendScript("second question"),
  5793. trace: traceFor("lineage-tokens-a"),
  5794. });
  5795. await settle(before, runA);
  5796. expect(turnCount(before)).toBe(2);
  5797. const totalA = 2 * TOKENS_PER_TURN;
  5798. expect(journal.getRun(runA)?.spentTokens).toBe(totalA);
  5799. // —— 修订 runB:第一问命中、第二问 live = 一轮 turn。
  5800. const after = makeHarness({
  5801. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "revised" } }] },
  5802. journal,
  5803. sessionStore: store as never,
  5804. });
  5805. const runB = await amendRun(after, {
  5806. cwd: TEST_CWD,
  5807. predecessorRunId: runA,
  5808. scriptText: amendScript("second question, revised"),
  5809. trace: traceFor("lineage-tokens-b"),
  5810. });
  5811. await settle(after, runB.runId);
  5812. expect(turnCount(after)).toBe(1);
  5813. // 继承 + 本次现跑的一轮。命中的那一问一分钱都没有再加(它的账在继承值里)。
  5814. const totalB = totalA + TOKENS_PER_TURN;
  5815. expect(journal.getRun(runB.runId)?.spentTokens).toBe(totalB);
  5816. expect(settledEvents(after, runB.runId)).toEqual([
  5817. { siteId: "world-read#1", ordinal: 1, cached: true },
  5818. { siteId: "ask#1", ordinal: 1, cached: true },
  5819. { siteId: "ask#2", ordinal: 1, cached: false },
  5820. ]);
  5821. // 前驱只读:lineage 因此保留「上一版花了多少」这段历史。
  5822. expect(journal.getRun(runA)?.spentTokens).toBe(totalA);
  5823. // 投影面:run-started 把用量清零,紧跟其后的第一条 usage-updated 必须已经是继承值——
  5824. // 否则卡片在第一轮 live turn 落地之前会显示 0(也就是「这次修订还没花钱」的假象)。
  5825. const usageB = after.runEvents.filter(
  5826. (event) => event.runId === runB.runId && event.eventType === "usage-updated",
  5827. );
  5828. expect(usageB[0]?.payload.spentTokens).toBe(totalA);
  5829. expect(usageB.at(-1)?.payload.spentTokens).toBe(totalB);
  5830. const typesB = after.runEvents
  5831. .filter((event) => event.runId === runB.runId)
  5832. .map((event) => event.eventType);
  5833. // 补发那条落在起手序幕里:它之前只允许出现 run-started 与 run-launched(修订路一定带锚点),
  5834. // 绝不允许任何 actor / node 事件——否则卡片在第一次派发时就已经显示过 0。
  5835. expect(typesB.slice(0, typesB.indexOf("usage-updated"))).toEqual([
  5836. "run-started",
  5837. "run-launched",
  5838. ]);
  5839. // —— 链式修订 runC:每个前驱的数字本身已是累计值,所以求和是构造出来的,没人走 resumedFrom 链。
  5840. const third = makeHarness({
  5841. actorScripts: { "actor#1@1": [{ kind: "submit", result: { text: "revised twice" } }] },
  5842. journal,
  5843. sessionStore: store as never,
  5844. });
  5845. const runC = await amendRun(third, {
  5846. cwd: TEST_CWD,
  5847. predecessorRunId: runB.runId,
  5848. scriptText: amendScript("second question, revised twice"),
  5849. trace: traceFor("lineage-tokens-c"),
  5850. });
  5851. await settle(third, runC.runId);
  5852. expect(turnCount(third)).toBe(1);
  5853. expect(journal.getRun(runC.runId)?.spentTokens).toBe(totalB + TOKENS_PER_TURN);
  5854. expect(journal.getRun(runB.runId)?.spentTokens).toBe(totalB);
  5855. } finally {
  5856. store.close();
  5857. await rm(tempRoot, { force: true, recursive: true });
  5858. }
  5859. });
  5860. it("全新 submit 从零起账(继承只发生在 amend 路上)", async () => {
  5861. const harness = makeHarness();
  5862. const runId = await submitRun(harness, {
  5863. cwd: TEST_CWD,
  5864. scriptText: TYPED_SCRIPT,
  5865. trace: traceFor("lineage-tokens-fresh"),
  5866. });
  5867. await settle(harness, runId);
  5868. // 头一条 usage-updated 就是本 run 自己第一轮的花费,不是继承值(缺席即零,不发补发那条)。
  5869. const usage = harness.runEvents.filter(
  5870. (event) => event.runId === runId && event.eventType === "usage-updated",
  5871. );
  5872. expect(usage[0]?.payload.spentTokens).toBe(TOKENS_PER_TURN);
  5873. expect(harness.journal.getRun(runId)?.spentTokens).toBe(turnCount(harness) * TOKENS_PER_TURN);
  5874. });
  5875. it("间隙读面(dwf_run 行藏起来)报继承值而不是 0", async () => {
  5876. // 间隙 = 注册表已有条目、journal 还没有行(藏读模拟,见 hideRunsFromReads)。修订 run 在这里
  5877. // 报 0 会说「这条 lineage 没花钱」,而它的起点在 amend 那一刻就已确定。
  5878. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-lineage-gap-"));
  5879. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5880. try {
  5881. const real = resolveDynamicWorkflowJournalStore(store as never) as JournalStorePort &
  5882. DwfRunIntrospectionQueries;
  5883. const hidden = new Set<string>();
  5884. const journal = hideRunsFromReads(real, hidden);
  5885. // 前驱:第一问 submit(一轮 turn 的用量 + 一条消息边界,预检要它),第二问挂住后被取消。
  5886. const harness = makeHarness({
  5887. actorScripts: {
  5888. "actor#1@1": [{ kind: "submit", result: { text: "one" } }, { kind: "hang" }],
  5889. },
  5890. journal,
  5891. // `hang` 的 turn 连取消都不理会,所以 amend 的静默闸门会等满上界才放行
  5892. // (workflow-driver-quiescence.ts)。本用例算的是 token,不必陪它等 5 秒。
  5893. quiesceMs: 5,
  5894. sessionStore: store as never,
  5895. });
  5896. const predecessor = await submitRun(harness, {
  5897. cwd: TEST_CWD,
  5898. parentSessionId: HARNESS_PARENT_SESSION,
  5899. scriptText: amendScript("second question"),
  5900. trace: traceFor("lineage-gap-a"),
  5901. });
  5902. await vi.waitFor(() => {
  5903. expect(real.getRun(predecessor)?.spentTokens).toBe(TOKENS_PER_TURN);
  5904. });
  5905. expect(await harness.service.cancel(predecessor)).toBe(true);
  5906. await settle(harness, predecessor);
  5907. const inherited = real.getRun(predecessor)!.spentTokens;
  5908. expect(inherited).toBe(TOKENS_PER_TURN);
  5909. const amended = await amendRun(harness, {
  5910. cwd: TEST_CWD,
  5911. predecessorRunId: predecessor,
  5912. parentSessionId: HARNESS_PARENT_SESSION,
  5913. scriptText: amendScript("second question, revised"),
  5914. trace: traceFor("lineage-gap-b"),
  5915. });
  5916. await settle(harness, amended.runId);
  5917. // 落行后:继承值 + 本次现跑的一轮。
  5918. expect(real.getRun(amended.runId)?.spentTokens).toBe(inherited + TOKENS_PER_TURN);
  5919. // 藏掉行 ⇒ 走注册表间隙分支:报得出继承值(条目只知道起点,这已经比 0 诚实)。
  5920. hidden.add(amended.runId);
  5921. const gap = await introspectionOf(harness).getRunDetail(amended.runId);
  5922. expect(gap?.usage).toMatchObject({ nodesObserved: 0, spentTokens: inherited });
  5923. const listed = await introspectionOf(harness).listRuns({ cwd: TEST_CWD, limit: 8 });
  5924. const gapRow = listed.runs.find((row) => row.runId === amended.runId);
  5925. expect(gapRow?.spentTokens).toBe(inherited);
  5926. // 全新 submit 的条目没有起点 ⇒ 间隙照旧报 0(继承只发生在 amend 路上)。
  5927. const fresh = await submitRun(harness, {
  5928. cwd: TEST_CWD,
  5929. parentSessionId: HARNESS_PARENT_SESSION,
  5930. scriptText: TYPED_SCRIPT,
  5931. trace: traceFor("lineage-gap-fresh"),
  5932. });
  5933. hidden.add(fresh);
  5934. expect((await introspectionOf(harness).getRunDetail(fresh))?.usage.spentTokens).toBe(0);
  5935. hidden.delete(fresh);
  5936. await harness.service.cancel(fresh);
  5937. await settle(harness, fresh);
  5938. } finally {
  5939. store.close();
  5940. await rm(tempRoot, { force: true, recursive: true });
  5941. }
  5942. });
  5943. });
  5944. describe("dynamic workflow run service — amend-resume 的崩溃后重建", () => {
  5945. it("崩溃后 resume:alpha 曾 live 但没写过工作区 ⇒ 门没关,beta 仍从导入表结算;journal pin 压过承袭的 seed pin", async () => {
  5946. // apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Amend-resume」:runB 里 alpha 分歧转 live 并挂住;进程没了。
  5947. // 转 live 本身不关门——alpha 一个字节都没写,beta 读的工作区就是前驱留下的那个。resume 重建导入表后
  5948. // beta 照常命中。(这条曾断言相反的结论:那时「任一 ask live 即关门」,是拿时钟代替依赖。)
  5949. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-resume-"));
  5950. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  5951. const journal = new SweepableJournalStore();
  5952. try {
  5953. const before = makeHarness({
  5954. actorScripts: {
  5955. "actor#1@1": [{ kind: "submit", result: { text: "alpha-1" } }],
  5956. "actor#2@1": [{ kind: "submit", result: { text: "beta-1" } }],
  5957. },
  5958. journal,
  5959. sessionStore: store as never,
  5960. });
  5961. const runA = await submitRun(before, {
  5962. cwd: TEST_CWD,
  5963. scriptText: TWO_ACTOR_SCRIPT,
  5964. trace: traceFor("amend-two-actor"),
  5965. });
  5966. await settle(before, runA);
  5967. // 修订:只改 alpha 的问题 → alpha 在 seq 0 分歧转 live 并挂住,beta 尚未排队。
  5968. const crashed = makeHarness({ hangActors: true, journal, sessionStore: store as never });
  5969. const submitted = await crashed.service.amend!({
  5970. cwd: TEST_CWD,
  5971. predecessorRunId: runA,
  5972. scriptText: TWO_ACTOR_SCRIPT.replace("alpha question", "alpha question, revised"),
  5973. trace: traceFor("amend-crash"),
  5974. });
  5975. expect(submitted.ok).toBe(true);
  5976. if (!submitted.ok) return;
  5977. const runB = submitted.runId;
  5978. await vi.waitFor(() => {
  5979. expect(crashed.actorRuntimeInputs.length).toBeGreaterThan(0);
  5980. });
  5981. expect(await crashed.service.cancel(runB)).toBe(true);
  5982. await settle(crashed, runB);
  5983. // 取消发生在 beta 之前:beta 在 runB 的 journal 里没有任何行;也没有关门事件。
  5984. expect(
  5985. journal
  5986. .listNodes(runB, { kinds: "all", withResult: true })
  5987. .some((node) => node.actorSiteId === "actor#2"),
  5988. ).toBe(false);
  5989. expect(
  5990. journal
  5991. .listEvents(runB, { types: "all", reportItems: "all" })
  5992. .some(({ event }) => event.type === "import-cache-closed"),
  5993. ).toBe(false);
  5994. // journal pin 必须压过承袭的 seed pin:本 run 里实际跑过的模型比前驱的更具体。
  5995. // 两者本应相等,所以这里把 runB 的记录改成一个哨兵值,好让「谁赢」成为可断言的事实。
  5996. const alphaRow = journal.getActor(runB, "actor#1", 1)!;
  5997. journal.putActor({ ...alphaRow, resolvedModel: "sentinel/from-journal" });
  5998. const resumed = makeHarness({
  5999. actorScripts: {
  6000. "actor#1@1": [{ kind: "submit", result: { text: "alpha-2" } }],
  6001. "actor#2@1": [{ kind: "submit", result: { text: "beta-2" } }],
  6002. },
  6003. journal,
  6004. sessionStore: store as never,
  6005. });
  6006. const outcome = await resumed.service.resume?.(runB);
  6007. expect(outcome?.ok).toBe(true);
  6008. await settle(resumed, runB);
  6009. // beta 从重建出来的导入表结算:门从未关过,只有 alpha 真的跑了。
  6010. expect((await resumed.service.getTask(runB))?.output).toBe("alpha-2|beta-1");
  6011. expect(turnCount(resumed)).toBe(1);
  6012. expect(resumed.actorRuntimeInputs.map((input) => refToString(input.actor))).toEqual([
  6013. "actor#1@1",
  6014. ]);
  6015. expect(settledEvents(resumed, runB)).toContainEqual({
  6016. siteId: "ask#2",
  6017. ordinal: 1,
  6018. cached: true,
  6019. });
  6020. expect(journal.getNode(runB, "ask#2", 1)?.result).toEqual({ text: "beta-1" });
  6021. expect(resumed.actorRuntimeInputs[0]!.pinnedModel).toBe("sentinel/from-journal");
  6022. } finally {
  6023. store.close();
  6024. await rm(tempRoot, { force: true, recursive: true });
  6025. }
  6026. });
  6027. it("崩溃后 resume:alpha 真的写了文件 ⇒ 执行器 → driver → 引擎关门;beta live 重跑(关门判定从 import-cache-closed 恢复)", async () => {
  6028. // 同一场景,两处不同:
  6029. // 1. runA 的 beta **用过工具**(一次 Write),所以它的缓存条目不是「纯」的——它可能读过工作区;
  6030. // 2. runB 的 alpha 挂住之前先调了一次真的 `Write`。执行器在 handler 之前发出带
  6031. // readOnly:false / sideEffectScope:"workspace" 的 ToolCallStarted,driver 的工具活动观察上报
  6032. // askMutating,引擎记下 import-cache-closed。
  6033. // resume 只认那条事件;beta 于是 live 重跑——它读的工作区可能已被 alpha 改过。
  6034. // (工具在这套夹具里会因 fakeFileSystemPort 而失败,无妨:ToolCallStarted 在 handler 之前就发了,
  6035. // 而这条链要验的正是「调用发生过」。)
  6036. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-resume-write-"));
  6037. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  6038. const journal = new SweepableJournalStore();
  6039. try {
  6040. const before = makeHarness({
  6041. actorScripts: {
  6042. "actor#1@1": [{ kind: "submit", result: { text: "alpha-1" } }],
  6043. "actor#2@1": [
  6044. { kind: "write", path: join(TEST_CWD, "beta-notes.md"), content: "beta was here" },
  6045. { kind: "submit", result: { text: "beta-1" } },
  6046. ],
  6047. },
  6048. journal,
  6049. sessionStore: store as never,
  6050. });
  6051. const runA = await submitRun(before, {
  6052. cwd: TEST_CWD,
  6053. scriptText: TWO_ACTOR_SCRIPT,
  6054. trace: traceFor("amend-two-actor-write"),
  6055. });
  6056. await settle(before, runA);
  6057. // 夹具前提:beta 在 runA 里确实碰过外部世界(一次 Write),所以它的条目在关门后不再命中;
  6058. // alpha 只交了结果,它的 worldToolCalls 是 0(`submit_result` 只计入 toolCalls)——纯条目,
  6059. // 关门后照样命中(上一条用例走的正是这条路)。
  6060. expect(journal.getNode(runA, "ask#2", 1)?.stats?.worldToolCalls ?? 0).toBeGreaterThan(0);
  6061. expect(journal.getNode(runA, "ask#1", 1)?.stats?.worldToolCalls).toBe(0);
  6062. const crashed = makeHarness({
  6063. actorScripts: {
  6064. "actor#1@1": [
  6065. { kind: "write", path: join(TEST_CWD, "notes.md"), content: "alpha was here" },
  6066. { kind: "hang" },
  6067. ],
  6068. },
  6069. journal,
  6070. sessionStore: store as never,
  6071. });
  6072. const submitted = await crashed.service.amend!({
  6073. cwd: TEST_CWD,
  6074. predecessorRunId: runA,
  6075. scriptText: TWO_ACTOR_SCRIPT.replace("alpha question", "alpha question, revised"),
  6076. trace: traceFor("amend-crash-write"),
  6077. });
  6078. expect(submitted.ok).toBe(true);
  6079. if (!submitted.ok) return;
  6080. const runB = submitted.runId;
  6081. // 等到关门事件落 journal:这是整条链(工具层 → driver → 引擎)跑通的证据。
  6082. await vi.waitFor(() => {
  6083. expect(
  6084. journal
  6085. .listEvents(runB, { types: "all", reportItems: "all" })
  6086. .some(({ event }) => event.type === "import-cache-closed"),
  6087. ).toBe(true);
  6088. });
  6089. const closed = journal
  6090. .listEvents(runB, { types: "all", reportItems: "all" })
  6091. .find(({ event }) => event.type === "import-cache-closed")!.event;
  6092. expect(closed).toMatchObject({
  6093. type: "import-cache-closed",
  6094. instance: { siteId: "ask#1", ordinal: 1 },
  6095. cause: "mutating-tool",
  6096. actorName: "alpha",
  6097. });
  6098. expect(await crashed.service.cancel(runB)).toBe(true);
  6099. await settle(crashed, runB);
  6100. expect(
  6101. journal
  6102. .listNodes(runB, { kinds: "all", withResult: true })
  6103. .some((node) => node.actorSiteId === "actor#2"),
  6104. ).toBe(false);
  6105. const resumed = makeHarness({
  6106. actorScripts: {
  6107. "actor#1@1": [{ kind: "submit", result: { text: "alpha-2" } }],
  6108. "actor#2@1": [{ kind: "submit", result: { text: "beta-2" } }],
  6109. },
  6110. journal,
  6111. sessionStore: store as never,
  6112. });
  6113. const outcome = await resumed.service.resume?.(runB);
  6114. expect(outcome?.ok).toBe(true);
  6115. await settle(resumed, runB);
  6116. expect((await resumed.service.getTask(runB))?.output).toBe("alpha-2|beta-2");
  6117. expect(turnCount(resumed)).toBe(2);
  6118. expect(resumed.actorRuntimeInputs.map((input) => refToString(input.actor))).toEqual([
  6119. "actor#1@1",
  6120. "actor#2@1",
  6121. ]);
  6122. expect(settledEvents(resumed, runB)).toContainEqual({
  6123. siteId: "ask#2",
  6124. ordinal: 1,
  6125. cached: false,
  6126. });
  6127. expect(journal.getNode(runB, "ask#2", 1)?.result).toEqual({ text: "beta-2" });
  6128. // resume 不重发关门事件:判定是恢复出来的,不是新发生的。
  6129. expect(
  6130. resumed.runEvents.filter(
  6131. (event) => event.runId === runB && event.eventType === "import-cache-closed",
  6132. ),
  6133. ).toHaveLength(0);
  6134. } finally {
  6135. store.close();
  6136. await rm(tempRoot, { force: true, recursive: true });
  6137. }
  6138. });
  6139. it("前驱被清理 → resume 仍成功,未消费的导入降级为 live 重跑", async () => {
  6140. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-amend-lost-"));
  6141. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  6142. const journal = new SweepableJournalStore();
  6143. try {
  6144. const before = makeHarness({
  6145. actorScripts: {
  6146. "actor#1@1": [{ kind: "submit", result: { text: "alpha-1" } }],
  6147. "actor#2@1": [{ kind: "submit", result: { text: "beta-1" } }],
  6148. },
  6149. journal,
  6150. sessionStore: store as never,
  6151. });
  6152. const runA = await submitRun(before, {
  6153. cwd: TEST_CWD,
  6154. scriptText: TWO_ACTOR_SCRIPT,
  6155. trace: traceFor("amend-lost-predecessor"),
  6156. });
  6157. await settle(before, runA);
  6158. const crashed = makeHarness({ hangActors: true, journal, sessionStore: store as never });
  6159. const submitted = await crashed.service.amend!({
  6160. cwd: TEST_CWD,
  6161. predecessorRunId: runA,
  6162. scriptText: TWO_ACTOR_SCRIPT.replace("alpha question", "alpha question, revised"),
  6163. trace: traceFor("amend-lost-crash"),
  6164. });
  6165. expect(submitted.ok).toBe(true);
  6166. if (!submitted.ok) return;
  6167. const runB = submitted.runId;
  6168. await vi.waitFor(() => {
  6169. expect(crashed.actorRuntimeInputs.length).toBeGreaterThan(0);
  6170. });
  6171. await crashed.service.cancel(runB);
  6172. await settle(crashed, runB);
  6173. // 前驱 journal 是修订 run 的**存续依赖,但只是加速结构**:丢了变贵,不变错。
  6174. const resumed = makeHarness({
  6175. actorScripts: {
  6176. "actor#1@1": [{ kind: "submit", result: { text: "alpha-2" } }],
  6177. "actor#2@1": [{ kind: "submit", result: { text: "beta-live" } }],
  6178. },
  6179. journal: withHiddenRun(journal, runA),
  6180. sessionStore: store as never,
  6181. });
  6182. const outcome = await resumed.service.resume?.(runB);
  6183. expect(outcome?.ok).toBe(true);
  6184. await settle(resumed, runB);
  6185. // beta 这次真的跑了模型,答案随之不同——退化的是账单,不是正确性。
  6186. expect((await resumed.service.getTask(runB))?.output).toBe("alpha-2|beta-live");
  6187. expect(turnCount(resumed)).toBe(2);
  6188. expect(
  6189. resumed.logs.some(
  6190. (entry) => entry.context?.event === "dynamic_workflow.amend.rebuild_skipped",
  6191. ),
  6192. ).toBe(true);
  6193. } finally {
  6194. store.close();
  6195. await rm(tempRoot, { force: true, recursive: true });
  6196. }
  6197. });
  6198. });
  6199. describe("dynamic workflow run service — 升级问答(escalation)", () => {
  6200. /**
  6201. * 起一个 run、等它把 ask 派下去,回 actor 会话的升级端口。
  6202. *
  6203. * `hangActors` 让模型永不 resolve——那正是一次被升级问答阻塞住的 turn 的形状,也是唯一
  6204. * 能让「问题停驻期间 run 照常在飞」成为可断言事实的装配。
  6205. */
  6206. async function inflightEscalatePort(
  6207. harness: Harness,
  6208. name: string,
  6209. ): Promise<{ runId: string; port: WorkflowEscalatePort }> {
  6210. const runId = await submitRun(harness, {
  6211. cwd: TEST_CWD,
  6212. scriptText: TYPED_SCRIPT,
  6213. trace: traceFor(name),
  6214. });
  6215. await vi.waitFor(() => {
  6216. expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0);
  6217. });
  6218. // ask 真正派下去(driver 记下 currentInstance)之后才谈得上停驻。
  6219. await vi.waitFor(() => {
  6220. expect(harness.runEvents.some((event) => event.eventType === "node-dispatched")).toBe(true);
  6221. });
  6222. const port = harness.actorRuntimeInputs[0]?.escalatePort;
  6223. if (port === undefined) throw new Error("actor runtime 输入里没有 escalatePort");
  6224. return { runId, port };
  6225. }
  6226. it("停驻的问题出现在快照的 pendingQuestions 里,作答后就地清空", async () => {
  6227. const harness = makeHarness({ hangActors: true });
  6228. const { runId, port } = await inflightEscalatePort(harness, "escalation-snapshot");
  6229. const answered = port.escalate({
  6230. toolCallId: createToolCallId("escalate-1"),
  6231. question: "评分上限 95 而通过门槛 96,这个门是不是坏了?",
  6232. trace: traceFor("escalation-snapshot"),
  6233. });
  6234. // 快照兜底:通知被丢弃时,主代理仍能从这里重新发现待答问题。
  6235. const blocked = await harness.service.getTask(runId);
  6236. expect(blocked?.pendingQuestions).toHaveLength(1);
  6237. const question = blocked?.pendingQuestions?.[0];
  6238. expect(question).toMatchObject({
  6239. actor: "actor#1@1",
  6240. // 脚本是 `agent("worker")`,所以有效名一路到达快照——通知面与侧栏因此不必各自
  6241. // 回查 journal.listActors(那份重复迟早会与实时轨对不上)。
  6242. actorName: "worker",
  6243. question: "评分上限 95 而通过门槛 96,这个门是不是坏了?",
  6244. });
  6245. // run 状态全程不动:升级是 ask 内部的一次慢工具调用,不是 run 生命周期事件。
  6246. expect(blocked?.status).toBe("running");
  6247. // 实时轨(侧栏据它渲染)与快照兜底(通知丢弃后据它自愈)报同一个提问时刻——
  6248. // 两条读面上的「已等待 N 分钟」因此不会各说各话。
  6249. const raisedPayload = harness.runEvents.find(
  6250. (event) => event.eventType === "escalation-raised",
  6251. )?.payload;
  6252. expect(raisedPayload?.askedAt).toBe(question?.askedAt);
  6253. const outcome = await harness.service.resolveQuestion?.(question!.qid, "门坏了,按 95 通过。");
  6254. expect(outcome).toEqual({ ok: true, qid: question!.qid });
  6255. await expect(answered).resolves.toMatchObject({
  6256. kind: "answered",
  6257. answer: "门坏了,按 95 通过。",
  6258. });
  6259. const after = await harness.service.getTask(runId);
  6260. // 零条时整字段缺席(与 reports 同规),不发空数组。
  6261. expect(after).not.toHaveProperty("pendingQuestions");
  6262. expect(after?.status).toBe("running");
  6263. });
  6264. // 通知丢弃后的**查询兜底**,也是模型侧唯一的发现面:`ResolveWorkflowQuestion` 只认 qid,
  6265. // 而升级通知有两条已知的丢弃路径(stale branch generation / shutdown)。快照面服务后台
  6266. // 任务追踪器,本条服务 `GetWorkflowRun`——两条读面同源同投影,缺了这一条,通知文案与
  6267. // `unknown_question` 的服务端文案都会指向一个什么都不返回的工具。
  6268. it("停驻的问题同样出现在 getRunDetail 里(GetWorkflowRun 的取数面)", async () => {
  6269. // sqlite journal:getRunDetail / listRuns 是内省查询面,内存 journal 不带它们。
  6270. await withSqliteJournal(async (journal) => {
  6271. const harness = makeHarness({ hangActors: true, journal });
  6272. const { runId, port } = await inflightEscalatePort(harness, "escalation-detail");
  6273. const answered = port.escalate({
  6274. toolCallId: createToolCallId("escalate-detail"),
  6275. question: "两条指令互相矛盾,先满足哪一条?",
  6276. context: "第 3 步要求保留原文,第 5 步要求改写。",
  6277. trace: traceFor("escalation-detail"),
  6278. });
  6279. const detail = await introspectionOf(harness).getRunDetail(runId);
  6280. expect(detail?.pendingQuestions).toHaveLength(1);
  6281. const question = detail?.pendingQuestions?.[0];
  6282. expect(question).toMatchObject({
  6283. actor: "actor#1@1",
  6284. actorName: "worker",
  6285. question: "两条指令互相矛盾,先满足哪一条?",
  6286. context: "第 3 步要求保留原文,第 5 步要求改写。",
  6287. });
  6288. // 与快照同源同投影:同一个 run 在两条读面上必须给出同一个 qid 与同一个提问时刻,
  6289. // 否则「已等待多久」在两处各说各话。
  6290. const snapshotQuestion = (await harness.service.getTask(runId))?.pendingQuestions?.[0];
  6291. expect(question?.qid).toBe(snapshotQuestion?.qid);
  6292. expect(question?.askedAt).toBe(snapshotQuestion?.askedAt);
  6293. // run 状态全程不动。
  6294. expect(detail?.status).toBe("running");
  6295. await harness.service.resolveQuestion?.(question!.qid, "以第 5 步为准。");
  6296. await expect(answered).resolves.toMatchObject({ kind: "answered" });
  6297. // 零条时整字段缺席(与快照同规,不发空数组)。
  6298. expect(await introspectionOf(harness).getRunDetail(runId)).not.toHaveProperty(
  6299. "pendingQuestions",
  6300. );
  6301. // actor 的 turn 仍然挂着(hangActors);收口后再关库,避免写进一个已关闭的 store。
  6302. await harness.service.cancel(runId);
  6303. await settle(harness, runId);
  6304. });
  6305. });
  6306. it("raised / resolved 两类事件都进了实时轨与事件分页", async () => {
  6307. const harness = makeHarness({ hangActors: true });
  6308. const { runId, port } = await inflightEscalatePort(harness, "escalation-events");
  6309. const answered = port.escalate({
  6310. toolCallId: createToolCallId("escalate-2"),
  6311. question: "这个门坏了吗?",
  6312. trace: traceFor("escalation-events"),
  6313. });
  6314. const qid = (await harness.service.getTask(runId))?.pendingQuestions?.[0]?.qid;
  6315. await harness.service.resolveQuestion?.(qid!, "坏了。");
  6316. await answered;
  6317. // 实时轨:progress sink 收到的载荷(Slice 2 的通知生产者读的就是它)。
  6318. const raised = harness.runEvents.find((event) => event.eventType === "escalation-raised");
  6319. // 通知生产者(Slice 2)读的就是这份载荷:结构 ref 定位、actorName 供人读、askedAt 供算等待时长。
  6320. expect(raised?.payload).toMatchObject({
  6321. qid,
  6322. actorName: "worker",
  6323. question: "这个门坏了吗?",
  6324. });
  6325. expect(typeof raised?.payload.askedAt).toBe("number");
  6326. expect(
  6327. harness.runEvents.find((event) => event.eventType === "escalation-resolved")?.payload,
  6328. ).toMatchObject({ answer: "坏了。", qid });
  6329. // durable 轨:既有的事件分页面原样承载新种类(协议层 type 是不透明字符串,契约零加值)。
  6330. const { events: page } = await harness.service.listEvents(runId, {});
  6331. expect(
  6332. page.filter((event) => event.type.startsWith("escalation-")).map((one) => one.type),
  6333. ).toEqual(["escalation-raised", "escalation-resolved"]);
  6334. // sequence 与 journal 的分配一致(driver 侧的 record 与引擎的 record 走同一条截取)。
  6335. expect(page.find((one) => one.type === "escalation-raised")?.sequence).toBe(raised?.sequence);
  6336. });
  6337. it("三类结构化拒绝:未知 id / 已回答 / 不在飞", async () => {
  6338. const harness = makeHarness({ hangActors: true });
  6339. const { runId, port } = await inflightEscalatePort(harness, "escalation-refusals");
  6340. // (1) 未知 id(含死 run 的陈旧 id:停驻项不持久化,重启后都长这样)。
  6341. expect(await harness.service.resolveQuestion?.("dwfq-nonesuch-1", "答案")).toMatchObject({
  6342. ok: false,
  6343. reason: "unknown_question",
  6344. });
  6345. // (2) 已回答。
  6346. const answered = port.escalate({
  6347. toolCallId: createToolCallId("escalate-3"),
  6348. question: "第一个问题",
  6349. trace: traceFor("escalation-refusals"),
  6350. });
  6351. const firstQid = (await harness.service.getTask(runId))?.pendingQuestions?.[0]?.qid;
  6352. await harness.service.resolveQuestion?.(firstQid!, "答案一");
  6353. await answered;
  6354. expect(await harness.service.resolveQuestion?.(firstQid!, "答案二")).toMatchObject({
  6355. ok: false,
  6356. reason: "already_resolved",
  6357. });
  6358. // (3) run 被取消 → 停驻项随 cancelAsk 撤下 → 之后作答得到 run_not_in_flight。
  6359. const cancelled = port.escalate({
  6360. toolCallId: createToolCallId("escalate-4"),
  6361. question: "第二个问题",
  6362. trace: traceFor("escalation-refusals"),
  6363. });
  6364. const secondQid = (await harness.service.getTask(runId))?.pendingQuestions?.[0]?.qid;
  6365. expect(await harness.service.cancel(runId)).toBe(true);
  6366. await expect(cancelled).rejects.toMatchObject({ code: "Cancelled" });
  6367. await settle(harness, runId);
  6368. expect(await harness.service.resolveQuestion?.(secondQid!, "答案三")).toMatchObject({
  6369. ok: false,
  6370. reason: "run_not_in_flight",
  6371. });
  6372. // 取消的语义与今天逐字节一致:ask 拒 Cancelled,run 结算 cancelled(因而可 resume)。
  6373. expect((await harness.service.getTask(runId))?.status).toBe("cancelled");
  6374. });
  6375. it("一张停驻表跨本服务的多个在飞 run,qid 互不碰撞且 pendingQuestions 按 run 隔离", async () => {
  6376. const harness = makeHarness({ hangActors: true });
  6377. const first = await inflightEscalatePort(harness, "escalation-multi-a");
  6378. const secondRunId = await submitRun(harness, {
  6379. cwd: TEST_CWD,
  6380. scriptText: TYPED_SCRIPT,
  6381. trace: traceFor("escalation-multi-b"),
  6382. });
  6383. await vi.waitFor(() => {
  6384. expect(harness.actorRuntimeInputs.length).toBe(2);
  6385. });
  6386. await vi.waitFor(() => {
  6387. expect(
  6388. harness.runEvents.filter((event) => event.eventType === "node-dispatched").length,
  6389. ).toBe(2);
  6390. });
  6391. const secondPort = harness.actorRuntimeInputs[1]!.escalatePort;
  6392. void first.port
  6393. .escalate({
  6394. toolCallId: createToolCallId("escalate-a"),
  6395. question: "A 的问题",
  6396. trace: traceFor("escalation-multi-a"),
  6397. })
  6398. .catch(() => {});
  6399. void secondPort
  6400. .escalate({
  6401. toolCallId: createToolCallId("escalate-b"),
  6402. question: "B 的问题",
  6403. trace: traceFor("escalation-multi-b"),
  6404. })
  6405. .catch(() => {});
  6406. const left = (await harness.service.getTask(first.runId))?.pendingQuestions;
  6407. const right = (await harness.service.getTask(secondRunId))?.pendingQuestions;
  6408. expect(left?.map((one) => one.question)).toEqual(["A 的问题"]);
  6409. expect(right?.map((one) => one.question)).toEqual(["B 的问题"]);
  6410. // qid 全局唯一正是「resolveQuestion 只收一个不透明 token」的前提。
  6411. expect(left?.[0]?.qid).not.toBe(right?.[0]?.qid);
  6412. });
  6413. });
  6414. // ————————————————————————————————————————————————
  6415. // 升级问答的端到端闭环(Slice 4)。
  6416. //
  6417. // 上面那组用例由测试自己持端口扮演模型;这一组把两端都交给真东西:actor 的**模型**发一次
  6418. // `escalate` 工具调用,主会话的**模型**发一次 `ResolveWorkflowQuestion` 工具调用,两条路各自
  6419. // 经真实工具层(注册门 → 权限 → handler → 端口)落到同一张停驻表上。
  6420. //
  6421. // 只有在这一层才证明得了、而端口层用例结构上看不见的三件事:
  6422. // 1. `escalate` 真的出现在 actor 那一轮的工具面上(端口在场 → includeEscalate → 注册表)。
  6423. // 中间任何一环漏掉,端口层的断言仍然全绿,而 actor 撞上坏门时手里根本没有这个工具;
  6424. // 2. 答案**逐字**作为工具结果回到 actor 的下一次模型请求——那是「带着答案继续干活」的唯一
  6425. // 物理通道,也是 spec 里「问答对整体生活在 actor 轮次转录内部」这条缓存不变式的实处;
  6426. // 3. 主代理侧零新接线:一个手上只有 qid 的普通会话,用既有工具面就能把 actor 放行。
  6427. // ————————————————————————————————————————————————
  6428. describe("dynamic workflow run service — 升级问答的端到端闭环", () => {
  6429. /**
  6430. * 主会话的替身:一个真实 AgentRuntime,注入本服务作为 dwf run 端口(生产里主代理就是这样
  6431. * 拿到 `ResolveWorkflowQuestion` 的——该工具无注册门,端口缺席时才回结构化失败)。模型按
  6432. * 计划先发一次工具调用,再收一段文本结束 turn。
  6433. */
  6434. function mainSessionRuntime(
  6435. service: Harness["service"],
  6436. call: () => { question_id: string; answer: string },
  6437. ): { runtime: AgentRuntime; log: ModelRequestLog } {
  6438. const log: ModelRequestLog = { requests: [] };
  6439. let index = 0;
  6440. const usage = { inputTokens: 9, outputTokens: 4, totalTokens: 13 };
  6441. const runtime = createTestAgentRuntime(
  6442. createSessionId("escalation-main"),
  6443. {
  6444. systemPrompt: "You created this workflow.",
  6445. mode: "yolo",
  6446. subagents: { enabled: false },
  6447. workingDirectory: TEST_CWD,
  6448. },
  6449. {
  6450. dynamicWorkflowRunPort: service,
  6451. eventStore: createInMemorySessionEventStore(),
  6452. fileSystemPort: fakeFileSystemPort({}),
  6453. modelAdapter: {
  6454. async generateText(request?: {
  6455. messages?: unknown;
  6456. tools?: readonly { name: string }[];
  6457. }) {
  6458. log.requests.push({ messages: request?.messages, tools: request?.tools });
  6459. if (index++ > 0) {
  6460. return {
  6461. finishReason: "stop",
  6462. model: "scripted",
  6463. providerMetadata: undefined,
  6464. text: "answered.",
  6465. usage,
  6466. };
  6467. }
  6468. return {
  6469. finishReason: "tool-calls",
  6470. model: "scripted",
  6471. providerMetadata: undefined,
  6472. text: "",
  6473. toolCalls: [
  6474. {
  6475. id: "resolve-question-call-1",
  6476. name: RESOLVE_WORKFLOW_QUESTION_TOOL_NAME,
  6477. input: call(),
  6478. },
  6479. ],
  6480. usage,
  6481. };
  6482. },
  6483. } as never,
  6484. },
  6485. );
  6486. return { runtime, log };
  6487. }
  6488. /** 起 run 并等第一个问题停驻(主代理侧的发现面就是这张快照)。 */
  6489. async function runUntilParked(
  6490. harness: Harness,
  6491. name: string,
  6492. ): Promise<{
  6493. runId: string;
  6494. question: NonNullable<DynamicWorkflowRunDetail["pendingQuestions"]>[number];
  6495. }> {
  6496. const runId = await submitRun(harness, {
  6497. cwd: TEST_CWD,
  6498. scriptText: TYPED_SCRIPT,
  6499. trace: traceFor(name),
  6500. });
  6501. await vi.waitFor(async () => {
  6502. expect((await harness.service.getTask(runId))?.pendingQuestions).toHaveLength(1);
  6503. });
  6504. const question = (await harness.service.getTask(runId))?.pendingQuestions?.[0];
  6505. if (question === undefined) throw new Error("停驻的问题没有出现在快照里");
  6506. return { runId, question };
  6507. }
  6508. const QUESTION = "评分上限 95 而通过门槛 96,这个门是不是坏了?";
  6509. const CONTEXT = "每一项都已拉满,总分仍然是 95。";
  6510. const ANSWER = "门确实坏了:按 95 分通过即可,不要为了凑 96 去改评分口径。";
  6511. it("actor 的模型提问 → 主代理的模型作答 → 答案逐字回到 actor → ask 照常 settle", async () => {
  6512. const harness = makeHarness({
  6513. actorScripts: {
  6514. "actor#1@1": [
  6515. { kind: "escalate", question: QUESTION, context: CONTEXT },
  6516. // 拿到答案之后 actor 继续干活并提交——escalate 不终止 turn,这一步就是证据。
  6517. { kind: "submit", result: { text: "按 95 通过" } },
  6518. ],
  6519. },
  6520. });
  6521. const { runId, question } = await runUntilParked(harness, "escalation-loop");
  6522. expect(question).toMatchObject({
  6523. actor: "actor#1@1",
  6524. actorName: "worker",
  6525. question: QUESTION,
  6526. context: CONTEXT,
  6527. });
  6528. expect(question.qid).toMatch(/^dwfq-/);
  6529. // (1) 工具面:actor 的第一次模型请求里真的带着 escalate。
  6530. const actorRequests = harness.actorModelRequests["actor#1@1"];
  6531. expect(actorRequests?.requests[0]?.tools?.map((tool) => tool.name)).toContain(
  6532. ESCALATE_TOOL_NAME,
  6533. );
  6534. // (2) 主代理侧:一次真的 ResolveWorkflowQuestion 工具调用(手上只有 qid)。
  6535. const main = mainSessionRuntime(harness.service, () => ({
  6536. question_id: question.qid,
  6537. answer: ANSWER,
  6538. }));
  6539. await main.runtime.executeTurn(
  6540. `工作流 run ${runId} 有一个待答问题 ${question.qid},去回答它。`,
  6541. );
  6542. await settle(harness, runId);
  6543. const snapshot = await harness.service.getTask(runId);
  6544. expect(snapshot?.status).toBe("completed");
  6545. expect(snapshot?.output).toBe("按 95 通过");
  6546. // 结算后停驻表就地清空(零条时整字段缺席)。
  6547. expect(snapshot).not.toHaveProperty("pendingQuestions");
  6548. // (3) 答案逐字回到 actor 的下一次模型请求:这是 actor「带着答案继续」的唯一通道。
  6549. expect(actorRequests?.requests.length).toBeGreaterThanOrEqual(2);
  6550. expect(JSON.stringify(actorRequests?.requests[1]?.messages)).toContain(ANSWER);
  6551. // 主代理拿到的回执带着 qid(「答案已送达、run 并没有因此停下」)。
  6552. expect(JSON.stringify(main.log.requests[1]?.messages)).toContain(question.qid);
  6553. // 事件双轨按序:raised 在前,resolved 在后。
  6554. expect(
  6555. harness.runEvents
  6556. .filter((event) => event.eventType.startsWith("escalation-"))
  6557. .map((event) => event.eventType),
  6558. ).toEqual(["escalation-raised", "escalation-resolved"]);
  6559. });
  6560. it("停驻期间取消 run:actor 的 escalate 调用被打断,之后作答得到 run_not_in_flight", async () => {
  6561. // spec 的「无答案 = 无限期阻塞」有且只有一个逃生舱,就是既有的 cancel。这条用例把它钉在
  6562. // 工具层:停驻的不是一个测试持有的 promise,而是 actor 真实轮次里的一次工具调用。
  6563. const harness = makeHarness({
  6564. actorScripts: {
  6565. "actor#1@1": [
  6566. { kind: "escalate", question: "要不要干脆跳过这个检查?" },
  6567. { kind: "submit", result: { text: "不该走到这里" } },
  6568. ],
  6569. },
  6570. });
  6571. const { runId, question } = await runUntilParked(harness, "escalation-loop-cancel");
  6572. expect(await harness.service.cancel(runId)).toBe(true);
  6573. await settle(harness, runId);
  6574. const snapshot = await harness.service.getTask(runId);
  6575. expect(snapshot?.status).toBe("cancelled");
  6576. expect(snapshot).not.toHaveProperty("pendingQuestions");
  6577. // 陈旧 qid 的作答得到结构化拒绝,而不是静默成功——静默成功会让主代理以为自己已经答过了。
  6578. expect(await harness.service.resolveQuestion?.(question.qid, "太晚了")).toMatchObject({
  6579. ok: false,
  6580. reason: "run_not_in_flight",
  6581. });
  6582. });
  6583. });
  6584. // 阶段进入记录的接缝(docs/dynamic-workflow/presentation.md):引擎发的
  6585. // phase-entered 经 toProgressPayload 有界化后,共享 reducer 真的能归约出 phases / currentPhase。
  6586. describe("dynamic workflow run service · phase-entered", () => {
  6587. it("引擎发出的 phase-entered 经进度管线归约成 workflowRuns.phases 与 currentPhase", async () => {
  6588. const harness = makeHarness();
  6589. const runId = await submitRun(harness, {
  6590. cwd: TEST_CWD,
  6591. parentSessionId: HARNESS_PARENT_SESSION,
  6592. scriptText: [
  6593. 'phase("Prepare");',
  6594. 'log("start");',
  6595. "for (let i = 0; i < 2; i++) {",
  6596. ' phase("Work");',
  6597. " report({ round: i });",
  6598. "}",
  6599. 'phase("Wrap up");',
  6600. 'return "done";',
  6601. ].join("\n"),
  6602. trace: traceFor("phase-entered"),
  6603. });
  6604. await settle(harness, runId);
  6605. expect(harness.journal.getRun(runId)).toMatchObject({ status: "completed" });
  6606. const entered = harness.runEvents.filter((event) => event.eventType === "phase-entered");
  6607. expect(entered.map((event) => event.payload)).toEqual([
  6608. { name: "Prepare", ordinal: 1 },
  6609. { name: "Work", ordinal: 1 },
  6610. { name: "Work", ordinal: 2 },
  6611. { name: "Wrap up", ordinal: 1 },
  6612. ]);
  6613. let state: WorkflowRunsState | undefined;
  6614. for (const event of harness.runEvents) {
  6615. state = reduceWorkflowRunsState(state, event as WorkflowRunProgressEnvelope) ?? state;
  6616. }
  6617. expect(state?.runs[0]?.phases).toEqual([
  6618. { name: "Prepare", rounds: 1 },
  6619. { name: "Work", rounds: 2 },
  6620. { name: "Wrap up", rounds: 1 },
  6621. ]);
  6622. expect(state?.runs[0]?.currentPhase).toBe("Wrap up");
  6623. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  6624. });
  6625. });
  6626. // ————————————————————————————————————————————————————————————————
  6627. // 出生阶段(docs/dynamic-workflow/presentation.md)
  6628. // ————————————————————————————————————————————————————————————————
  6629. /**
  6630. * 一个横跨「标记之前 / Prepare / Work」的脚本:每段各建一个 actor 并问一次,Prepare 里另有
  6631. * 一次 world-read。三类出生事件(actor-created / node-queued / cached node-settled)与
  6632. * 「标记之前不带戳」在同一条脚本上同时可观察。
  6633. */
  6634. const BIRTH_PHASE_SCRIPT = [
  6635. "interface Answer { text: string }",
  6636. 'const solo = agent("solo");',
  6637. 'const s = await solo.ask<Answer>("before any marker");',
  6638. 'phase("Prepare");',
  6639. 'const prep = agent("prep");',
  6640. 'const p = await prep.ask<Answer>("prepare question");',
  6641. 'const paths = await files.glob("src/**/*.ts");',
  6642. 'phase("Work");',
  6643. 'const worker = agent("worker");',
  6644. 'const w = await worker.ask<Answer>("work question");',
  6645. "return `${s.text}|${p.text}|${w.text}|${paths.length}`;",
  6646. ].join("\n");
  6647. /**
  6648. * 出生事件上的阶段坐标:把 `actor-created` / `node-queued` / `node-settled` 压成
  6649. * (类型, 实例, 戳) 三元组。`phaseName` **缺席**与「值为 undefined」在这里是两件事——引擎只在
  6650. * 出生事件上打戳,其余事件必须一个键都不带——所以按 in 判断条件展开,断言侧用 toStrictEqual。
  6651. */
  6652. function birthStamps(harness: Harness): { type: string; ref: string; phaseName?: string }[] {
  6653. return harness.runEvents
  6654. .filter(
  6655. (event) =>
  6656. event.eventType === "actor-created" ||
  6657. event.eventType === "node-queued" ||
  6658. event.eventType === "node-settled",
  6659. )
  6660. .map((event) => {
  6661. const payload = event.payload as {
  6662. actor?: { siteId: string; ordinal: number };
  6663. instance?: { siteId: string; ordinal: number };
  6664. phaseName?: string;
  6665. };
  6666. // instance 优先:node-* 的载荷两个键都有,出生的是 instance 那个。
  6667. const ref = payload.instance ?? payload.actor;
  6668. return {
  6669. type: `${event.eventType}${event.payload.cached === true ? "(cached)" : ""}`,
  6670. ref: `${ref?.siteId}@${ref?.ordinal}`,
  6671. ...("phaseName" in payload ? { phaseName: payload.phaseName } : {}),
  6672. };
  6673. });
  6674. }
  6675. /** 载荷点名的实例键(`instance` 优先,没有就取 `actor`)。 */
  6676. function refOfPayload(payload: Record<string, unknown>): string {
  6677. const ref = (payload.instance ?? payload.actor) as
  6678. | { siteId: string; ordinal: number }
  6679. | undefined;
  6680. return `${ref?.siteId}@${ref?.ordinal}`;
  6681. }
  6682. /** 归约后的实例 → 阶段坐标(缺席即 undefined)。 */
  6683. function reducedPhaseNames(state: WorkflowRunsState | undefined): {
  6684. actors: [string, string | undefined][];
  6685. nodes: [string, string | undefined][];
  6686. } {
  6687. const run = state?.runs[0];
  6688. return {
  6689. actors: (run?.actors ?? []).map((actor) => [
  6690. `${actor.siteId}@${actor.ordinal}`,
  6691. actor.phaseName,
  6692. ]),
  6693. nodes: (run?.nodes ?? []).map((node) => [`${node.siteId}@${node.ordinal}`, node.phaseName]),
  6694. };
  6695. }
  6696. /** 事件流逐条归约(每个用例都要走一遍完整的进度管线)。 */
  6697. function reduceAll(harness: Harness): WorkflowRunsState | undefined {
  6698. let state: WorkflowRunsState | undefined;
  6699. for (const event of harness.runEvents) {
  6700. state = reduceWorkflowRunsState(state, event as WorkflowRunProgressEnvelope) ?? state;
  6701. }
  6702. return state;
  6703. }
  6704. /**
  6705. * 运行时实例带阶段坐标的接缝(追记 2026-09-09):引擎在**出生事件**上打的 `phaseName` 经
  6706. * `toProgressPayload` 原样过境,再由共享 reducer 落到 `actors[*]` / `nodes[*]` 上。
  6707. *
  6708. * 这条接缝正是「所有子代理出现在所有阶段」那个 bug 的修复面:静态图按阶段拷贝站点,运行时
  6709. * 实例必须带同一个坐标,UI 才能按 (站点, 阶段) 而不是按车道绑定。
  6710. */
  6711. describe("dynamic workflow run service · 出生阶段(phaseName)", () => {
  6712. it("标记前出生的实例不带戳、Prepare / Work 各带各的;派发与 live 结算不带,且归约后落到 actors / nodes 上", async () => {
  6713. const harness = makeHarness();
  6714. const runId = await submitRun(harness, {
  6715. cwd: TEST_CWD,
  6716. parentSessionId: HARNESS_PARENT_SESSION,
  6717. scriptText: BIRTH_PHASE_SCRIPT,
  6718. trace: traceFor("birth-phase"),
  6719. });
  6720. await settle(harness, runId);
  6721. expect(harness.journal.getRun(runId)).toMatchObject({ status: "completed" });
  6722. // 出生事件:标记之前的一个键都不带;标记之后的按**出生时**所在阶段带。
  6723. // live 的 node-settled 不是出生事件,因此同样不带(戳靠 reducer 从 queued 向前携带)。
  6724. expect(birthStamps(harness)).toStrictEqual([
  6725. { type: "actor-created", ref: "actor#1@1" },
  6726. { type: "node-queued", ref: "ask#1@1" },
  6727. { type: "node-settled", ref: "ask#1@1" },
  6728. { type: "actor-created", ref: "actor#2@1", phaseName: "Prepare" },
  6729. { type: "node-queued", ref: "ask#2@1", phaseName: "Prepare" },
  6730. { type: "node-settled", ref: "ask#2@1" },
  6731. { type: "node-queued", ref: "world-read#1@1", phaseName: "Prepare" },
  6732. { type: "node-settled", ref: "world-read#1@1" },
  6733. { type: "actor-created", ref: "actor#3@1", phaseName: "Work" },
  6734. { type: "node-queued", ref: "ask#3@1", phaseName: "Work" },
  6735. { type: "node-settled", ref: "ask#3@1" },
  6736. ]);
  6737. // ask 的 node-dispatched 重复自己的出生事实(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  6738. // 「Events」):戳与它的 node-queued 同源,标记之前出生的那个照样一个键都不带;
  6739. // world-read 的派发始终是裸的。
  6740. const dispatched = harness.runEvents.filter((event) => event.eventType === "node-dispatched");
  6741. expect(
  6742. dispatched.map((event) => ({
  6743. ref: refOfPayload(event.payload),
  6744. ...("phaseName" in event.payload ? { phaseName: event.payload.phaseName } : {}),
  6745. ...("actorPhaseName" in event.payload
  6746. ? { actorPhaseName: event.payload.actorPhaseName }
  6747. : {}),
  6748. })),
  6749. ).toStrictEqual([
  6750. { ref: "ask#1@1" },
  6751. { ref: "ask#2@1", phaseName: "Prepare", actorPhaseName: "Prepare" },
  6752. { ref: "world-read#1@1" },
  6753. { ref: "ask#3@1", phaseName: "Work", actorPhaseName: "Work" },
  6754. ]);
  6755. // 点名子代理的事件都带上会话 id:读面据这一条就能把一个开跑的实例连同它的子代理收进表。
  6756. const askDispatch = dispatched.find((event) => refOfPayload(event.payload) === "ask#3@1");
  6757. expect(askDispatch).toMatchObject({
  6758. actorSessionId: expect.any(String),
  6759. payload: { kind: "ask", actorName: "worker", instructionsHead: "work question" },
  6760. });
  6761. expect(askDispatch?.actorSessionId).toBe(
  6762. harness.runEvents.find(
  6763. (event) =>
  6764. event.eventType === "actor-created" && refOfPayload(event.payload) === "actor#3@1",
  6765. )?.actorSessionId,
  6766. );
  6767. // world-read 的那条没有 actor,也就没有转录可开。
  6768. expect(
  6769. dispatched.find((event) => refOfPayload(event.payload) === "world-read#1@1"),
  6770. ).not.toHaveProperty("actorSessionId");
  6771. // 归约面:actor 从 actor-created 取;节点从 node-queued 取并在 dispatched / settled 上携带。
  6772. const state = reduceAll(harness);
  6773. expect(reducedPhaseNames(state)).toEqual({
  6774. actors: [
  6775. ["actor#1@1", undefined],
  6776. ["actor#2@1", "Prepare"],
  6777. ["actor#3@1", "Work"],
  6778. ],
  6779. nodes: [
  6780. ["ask#1@1", undefined],
  6781. ["ask#2@1", "Prepare"],
  6782. ["world-read#1@1", "Prepare"],
  6783. ["ask#3@1", "Work"],
  6784. ],
  6785. });
  6786. // 节点确实走完了整条生命周期(否则上面的「携带」只是恰好没被覆盖)。
  6787. expect(state?.runs[0]?.nodes.every((node) => node.phase === "settled")).toBe(true);
  6788. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  6789. });
  6790. it("resume 时 cached 的 node-settled 带回与前一世相同的出生阶段", async () => {
  6791. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-birth-phase-"));
  6792. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  6793. const journal = new SweepableJournalStore();
  6794. try {
  6795. // —— 前驱:三个 ask 与 world-read 都 live 跑一遍,边界真的落库(resume 的门槛)。
  6796. const before = makeHarness({ journal, sessionStore: store as never });
  6797. const runA = await submitRun(before, {
  6798. cwd: TEST_CWD,
  6799. scriptText: BIRTH_PHASE_SCRIPT,
  6800. trace: traceFor("birth-phase-predecessor"),
  6801. });
  6802. await settle(before, runA);
  6803. expect(before.journal.getRun(runA)).toMatchObject({ status: "completed" });
  6804. // —— 续跑:脚本逐字节相同,于是每个节点都命中导入缓存,一次真派发都没有。
  6805. const after = makeHarness({ journal, sessionStore: store as never });
  6806. const submitted = await after.service.amend!({
  6807. cwd: TEST_CWD,
  6808. predecessorRunId: runA,
  6809. scriptText: BIRTH_PHASE_SCRIPT,
  6810. trace: traceFor("birth-phase-resume"),
  6811. });
  6812. expect(submitted.ok).toBe(true);
  6813. if (!submitted.ok) return;
  6814. await settle(after, submitted.runId);
  6815. expect(turnCount(after)).toBe(0);
  6816. // 命中的节点没有 queued,那条 cached settle 就是它的出生事件——戳与前一世逐个相同,
  6817. // 因为脚本重跑前缀时 phase() 沿同一轨迹重走,每个铸造点上的 currentPhase 不变。
  6818. expect(birthStamps(after)).toStrictEqual([
  6819. { type: "actor-created", ref: "actor#1@1" },
  6820. { type: "node-settled(cached)", ref: "ask#1@1" },
  6821. { type: "actor-created", ref: "actor#2@1", phaseName: "Prepare" },
  6822. { type: "node-settled(cached)", ref: "ask#2@1", phaseName: "Prepare" },
  6823. { type: "node-settled(cached)", ref: "world-read#1@1", phaseName: "Prepare" },
  6824. { type: "actor-created", ref: "actor#3@1", phaseName: "Work" },
  6825. { type: "node-settled(cached)", ref: "ask#3@1", phaseName: "Work" },
  6826. ]);
  6827. const state = reduceAll(after);
  6828. expect(reducedPhaseNames(state)).toEqual({
  6829. actors: [
  6830. ["actor#1@1", undefined],
  6831. ["actor#2@1", "Prepare"],
  6832. ["actor#3@1", "Work"],
  6833. ],
  6834. nodes: [
  6835. ["ask#1@1", undefined],
  6836. ["ask#2@1", "Prepare"],
  6837. ["world-read#1@1", "Prepare"],
  6838. ["ask#3@1", "Work"],
  6839. ],
  6840. });
  6841. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  6842. } finally {
  6843. store.close();
  6844. await rm(tempRoot, { recursive: true, force: true });
  6845. }
  6846. });
  6847. });
  6848. describe("dynamic workflow run service — 模型侧错误的收容(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)", () => {
  6849. const PARALLEL_SCRIPT = [
  6850. "interface Answer { text: string }",
  6851. 'const alpha = agent("alpha");',
  6852. 'const beta = agent("beta");',
  6853. "const [a, b] = await Promise.all([",
  6854. ' alpha.ask<Answer>("first"),',
  6855. ' beta.ask<Answer>("second"),',
  6856. "]);",
  6857. "return a.text + b.text;",
  6858. ].join("\n");
  6859. const adapterError = (context: Record<string, unknown>, message: string) =>
  6860. Object.assign(new Error(message), {
  6861. name: "AiSdkModelAdapterError",
  6862. code: "model_request_failed",
  6863. context,
  6864. });
  6865. it("一个子代理撞上确定性模型错误 → run stopped(provider),兄弟在飞 ask 被 abort,可恢复", async () => {
  6866. const harness = makeHarness({
  6867. actorScripts: {
  6868. "actor#1@1": [
  6869. {
  6870. kind: "throw",
  6871. error: adapterError(
  6872. {
  6873. reason: "auth_failed",
  6874. providerId: "prov",
  6875. modelId: "alpha",
  6876. providerCode: "1006",
  6877. retryable: false,
  6878. },
  6879. "[1006] token expired",
  6880. ),
  6881. },
  6882. ],
  6883. "actor#2@1": [{ kind: "hang" }],
  6884. },
  6885. });
  6886. const runId = await submitRun(harness, {
  6887. cwd: TEST_CWD,
  6888. parentSessionId: HARNESS_PARENT_SESSION,
  6889. scriptText: PARALLEL_SCRIPT,
  6890. trace: traceFor("provider-stop"),
  6891. });
  6892. await settle(harness, runId);
  6893. const record = harness.journal.getRun(runId);
  6894. expect(record?.status).toBe("stopped");
  6895. expect(record?.stopReason).toBe("provider");
  6896. expect(record?.failure?.code).toBe("ProviderStop");
  6897. expect(record?.failure?.providerStop).toMatchObject({
  6898. kind: "auth",
  6899. reason: "auth_failed",
  6900. providerCode: "1006",
  6901. subagent: "actor#1@1",
  6902. subagentName: "alpha",
  6903. rawMessage: "[1006] token expired",
  6904. });
  6905. // 节点:触发者与兄弟都以 node-settled(cancelled) 收场(与 cancel 同),没有 failed 节点;
  6906. // journal 的节点行保持 running(与 cancel 同:resume 时重新派发)。
  6907. const settledNodes = harness.runEvents.filter(
  6908. (event) => event.runId === runId && event.eventType === "node-settled",
  6909. );
  6910. expect(settledNodes.map((event) => event.payload.outcome)).toEqual(["cancelled", "cancelled"]);
  6911. const nodes = harness.journal
  6912. .listNodes(runId, { kinds: "all", withResult: true })
  6913. .filter((node) => node.kind === "ask");
  6914. expect(nodes.map((node) => node.status)).toEqual(["running", "running"]);
  6915. // 快照:追踪器词汇 cancelled,真实词 stopped(provider) + 结构化失败。
  6916. const snapshot = await harness.service.getTask(runId);
  6917. expect(snapshot?.status).toBe("cancelled");
  6918. expect(snapshot?.runStatus).toBe("stopped");
  6919. expect(snapshot?.stopReason).toBe("provider");
  6920. expect(snapshot?.failure?.code).toBe("ProviderStop");
  6921. expect(snapshot?.failure?.providerStop?.kind).toBe("auth");
  6922. // run-settled 载荷:resumable + stopReason 随事件透出(UI 的 Resume 控件与原因行读它)。
  6923. const settled = harness.runEvents.find((event) => event.eventType === "run-settled");
  6924. expect(settled?.payload).toMatchObject({
  6925. status: "stopped",
  6926. stopReason: "provider",
  6927. resumable: true,
  6928. error: { code: "ProviderStop" },
  6929. });
  6930. expect((await harness.service.listRunsForSession?.())?.[0]).toMatchObject({
  6931. runId,
  6932. status: "stopped",
  6933. stopReason: "provider",
  6934. failureCode: "ProviderStop",
  6935. resumable: true,
  6936. });
  6937. });
  6938. it('cancel(runId, "model")(TaskStop)→ stopped(model);缺省 initiator 是 user', async () => {
  6939. const harness = makeHarness({ hangActors: true });
  6940. const byModel = await submitRun(harness, {
  6941. cwd: TEST_CWD,
  6942. scriptText: TYPED_SCRIPT,
  6943. trace: traceFor("stop-by-model"),
  6944. });
  6945. expect(await harness.service.cancel(byModel, "model")).toBe(true);
  6946. await settle(harness, byModel);
  6947. expect(harness.journal.getRun(byModel)).toMatchObject({
  6948. status: "stopped",
  6949. stopReason: "model",
  6950. });
  6951. expect((await harness.service.getTask(byModel))?.stopReason).toBe("model");
  6952. const settled = harness.runEvents.find(
  6953. (event) => event.runId === byModel && event.eventType === "run-settled",
  6954. );
  6955. expect(settled?.payload).toMatchObject({
  6956. status: "stopped",
  6957. stopReason: "model",
  6958. resumable: true,
  6959. });
  6960. const byUser = await submitRun(harness, {
  6961. cwd: TEST_CWD,
  6962. scriptText: TYPED_SCRIPT,
  6963. trace: traceFor("stop-by-user"),
  6964. });
  6965. expect(await harness.service.cancel(byUser)).toBe(true);
  6966. await settle(harness, byUser);
  6967. expect(harness.journal.getRun(byUser)).toMatchObject({ status: "stopped", stopReason: "user" });
  6968. });
  6969. });
  6970. /**
  6971. * 完成卡的时长口径(docs/dynamic-workflow/transcript-and-notifications.md「How long it took」):
  6972. * 快照在终态携带整条 lineage 的活动时长,终态之前不带。
  6973. *
  6974. * 求和规则本身在 `dynamic-workflow-run-elapsed.test.ts` 里单测,每一世的 SQL 在
  6975. * `adapters/tests/dwf-journal-store.test.ts` 里对真库钉住;这里钉的是**接线**——读面在场时那个数
  6976. * 真的走到了快照上(终态通知只读快照),以及读面缺席时字段整个不出。
  6977. */
  6978. class LifeSpanJournalStore extends SweepableJournalStore {
  6979. /** 每个 run 的世;缺席即「这个 run 没有可读的世」。 */
  6980. readonly lifeSpans = new Map<string, DwfRunLifeSpan[]>();
  6981. listRunLifeSpans(runId: string): DwfRunLifeSpan[] {
  6982. return this.lifeSpans.get(runId) ?? [];
  6983. }
  6984. }
  6985. describe("dynamic workflow run service — 快照上的 lineage 活动时长", () => {
  6986. it("终态快照带 activeDurationMs(逐世求和),运行中不带", async () => {
  6987. const journal = new LifeSpanJournalStore();
  6988. const harness = makeHarness({ hangActors: true, journal });
  6989. const runId = await submitRun(harness, {
  6990. cwd: TEST_CWD,
  6991. scriptText: TYPED_SCRIPT,
  6992. trace: traceFor("lifespan-terminal"),
  6993. });
  6994. // 两世:第一世跑了一小时被打断,这一世(重放)两分钟。世与世之间的死时间不计。
  6995. journal.lifeSpans.set(runId, [
  6996. { startedAt: 0, lastActivityAt: 3_600_000 },
  6997. { startedAt: 200_000_000, lastActivityAt: 200_120_000 },
  6998. ]);
  6999. // 运行中:与 reports / artifacts 同一道终态闸门——快照被后台追踪器反复轮询,
  7000. // 而这个数的唯一消费者是终态通知。
  7001. const running = await harness.service.getTask(runId);
  7002. expect(running?.status).toBe("running");
  7003. expect(running?.activeDurationMs).toBeUndefined();
  7004. expect(await harness.service.cancel(runId)).toBe(true);
  7005. await settle(harness, runId);
  7006. expect((await harness.service.getTask(runId))?.activeDurationMs).toBe(3_600_000 + 120_000);
  7007. });
  7008. it("修订链:快照报的是整条 lineage 的活动时长,不只是这一次修订的那一世", async () => {
  7009. // 挂住 actor:前驱没有已完结的 ask,预检因此不要求消息边界(与本文件其余 amend 用例同款)。
  7010. const journal = new LifeSpanJournalStore();
  7011. const harness = makeHarness({ hangActors: true, journal });
  7012. const predecessor = await submitRun(harness, {
  7013. cwd: TEST_CWD,
  7014. scriptText: TYPED_SCRIPT,
  7015. trace: traceFor("lifespan-predecessor"),
  7016. });
  7017. // 前驱跑了四小时。
  7018. journal.lifeSpans.set(predecessor, [{ startedAt: 0, lastActivityAt: 4 * 3_600_000 }]);
  7019. const amended = await amendRun(harness, {
  7020. cwd: TEST_CWD,
  7021. predecessorRunId: predecessor,
  7022. scriptText: TYPED_SCRIPT,
  7023. trace: traceFor("lifespan-amendment"),
  7024. });
  7025. // 修订出来的这一世几乎全是缓存重放:12 秒。
  7026. journal.lifeSpans.set(amended.runId, [
  7027. { startedAt: 10 * 3_600_000, lastActivityAt: 10 * 3_600_000 + 12_000 },
  7028. ]);
  7029. expect(await harness.service.cancel(amended.runId)).toBe(true);
  7030. await settle(harness, amended.runId);
  7031. // 缺陷原因:只报这一世 → 四小时的活在完成卡上写成 12 秒,而同卡 tokens 是 lineage 总数。
  7032. expect(journal.getRun(amended.runId)?.resumedFrom).toBe(predecessor);
  7033. expect((await harness.service.getTask(amended.runId))?.activeDurationMs).toBe(
  7034. 4 * 3_600_000 + 12_000,
  7035. );
  7036. // 前驱自己的卡不受影响(它被 supersede 停下,也是终态)。
  7037. expect((await harness.service.getTask(predecessor))?.activeDurationMs).toBe(4 * 3_600_000);
  7038. });
  7039. it("journal 没有这条读面(引擎的内存实现):字段整个缺席,通知退回本世", async () => {
  7040. const harness = makeHarness();
  7041. const runId = await submitRun(harness, {
  7042. cwd: TEST_CWD,
  7043. scriptText: TYPED_SCRIPT,
  7044. trace: traceFor("lifespan-absent"),
  7045. });
  7046. await settle(harness, runId);
  7047. const snapshot = await harness.service.getTask(runId);
  7048. expect(snapshot?.status).toBe("completed");
  7049. expect(snapshot?.activeDurationMs).toBeUndefined();
  7050. expect("activeDurationMs" in (snapshot ?? {})).toBe(false);
  7051. });
  7052. });
  7053. describe("dynamic workflow run service — 留白(FillWorkflowHole)", () => {
  7054. /** 一处开放的留白,prompt 带着前一步的值;阶段表 ["准备", "裁决"],留白按名字站在第 1 位。 */
  7055. const HOLE_SCRIPT = [
  7056. 'phase("准备");',
  7057. 'const a = await agent("worker").ask<{ text: string }>("do the thing");',
  7058. 'const v = await hole<string>("裁决", `decide on ${a.text}`);',
  7059. "return v;",
  7060. ].join("\n");
  7061. const HOLE_PHASES = ["准备", "裁决"];
  7062. // 留白 id 是名字键(docs/analysis.md「Sites」):按名字取,不写死哈希。
  7063. const VERDICT = holeSiteId("裁决");
  7064. const LEFT = holeSiteId("左");
  7065. const RIGHT = holeSiteId("右");
  7066. const DECIDE = holeSiteId("决定");
  7067. const REFINE = holeSiteId("细化");
  7068. /** 提交并等到 run 停在留白处(`hole-reached` 进度事件到达即停驻已成立:引擎先停驻再记事件)。 */
  7069. async function submitAndReachHole(
  7070. harness: Harness,
  7071. name: string,
  7072. extra: Partial<Parameters<Harness["service"]["submit"]>[0]> = {},
  7073. ): Promise<string> {
  7074. const runId = await submitRun(harness, {
  7075. cwd: TEST_CWD,
  7076. parentSessionId: HARNESS_PARENT_SESSION,
  7077. phaseNames: HOLE_PHASES,
  7078. scriptText: HOLE_SCRIPT,
  7079. trace: traceFor(name),
  7080. ...extra,
  7081. });
  7082. await vi.waitFor(() => {
  7083. expect(
  7084. harness.runEvents.some(
  7085. (event) => event.runId === runId && event.eventType === "hole-reached",
  7086. ),
  7087. ).toBe(true);
  7088. });
  7089. return runId;
  7090. }
  7091. function fill(harness: Harness, runId: string, body: string, holeId = VERDICT) {
  7092. return harness.service.fillHole!({
  7093. runId,
  7094. holeId,
  7095. body,
  7096. parentSessionId: HARNESS_PARENT_SESSION,
  7097. trace: traceFor("fill"),
  7098. });
  7099. }
  7100. it("停在留白处:run-launched 的 holes 下标、快照的 waiting 条目、hole-reached 载荷的 type / reachedAt", async () => {
  7101. // 真库:详情面(getRunDetail)只在带内省查询的 journal 上装,且 `updateRunScript` 的 SQLite
  7102. // 实现在这里跟着整条链路走一遍。
  7103. await withSqliteJournal(async (journal) => {
  7104. const harness = makeHarness({ journal });
  7105. const runId = await submitAndReachHole(harness, "hole-wait");
  7106. // 声明阶段表里第 1 位是开放的留白(按名字对出)。
  7107. const launched = harness.journal.listEvents(runId, {
  7108. types: ["run-launched"],
  7109. reportItems: { limit: 0 },
  7110. })[0]?.event;
  7111. expect(launched).toMatchObject({ type: "run-launched", phaseNames: HOLE_PHASES, holes: [1] });
  7112. // 进度载荷:类型来自编译产物,到达时刻来自 journal 的戳;prompt 带着上一步的值。
  7113. const reached = harness.runEvents.find((event) => event.eventType === "hole-reached");
  7114. expect(reached?.payload).toMatchObject({
  7115. instance: { siteId: VERDICT, ordinal: 1 },
  7116. name: "裁决",
  7117. prompt: "decide on done",
  7118. type: "string",
  7119. });
  7120. expect(typeof reached?.payload.reachedAt).toBe("number");
  7121. // 快照:waiting 只因为引擎的停驻表里有它;line 是调用在草稿里的行,before 是前一个阶段。
  7122. const waiting = await harness.service.getTask(runId);
  7123. expect(waiting?.status).toBe("running");
  7124. expect(waiting?.holes).toEqual([
  7125. {
  7126. siteId: VERDICT,
  7127. ordinal: 1,
  7128. name: "裁决",
  7129. type: "string",
  7130. state: "waiting",
  7131. since: reached?.payload.reachedAt,
  7132. line: 3,
  7133. before: "准备",
  7134. },
  7135. ]);
  7136. // 详情面同源同投影。
  7137. const detail = await harness.service.getRunDetail?.(runId);
  7138. expect(detail?.holes).toEqual(waiting?.holes);
  7139. const result = await fill(harness, runId, 'return "verdict";');
  7140. expect(result).toMatchObject({ ok: true, phasesAdded: [] });
  7141. if (!result.ok) throw new Error(result.message);
  7142. expect(result.scriptText).toContain(
  7143. 'hole<string>("裁决", `decide on ${a.text}`, async () => {',
  7144. );
  7145. expect(result.scriptText).toContain(' return "verdict";\n})');
  7146. await settle(harness, runId);
  7147. const done = await harness.service.getTask(runId);
  7148. expect(done?.status).toBe("completed");
  7149. expect(done?.output).toBe("verdict");
  7150. // 补全后:filled 来自 hole-filled 事件,带补全它的会话。函数体没有站点也没有阶段标记,但留白
  7151. // 自己的阶段靠 mark 节点留在有效脚本的阶段表里(analysis.md「Sites」),所以仍念得出前邻居。
  7152. expect(done?.holes).toEqual([
  7153. {
  7154. before: "准备",
  7155. siteId: VERDICT,
  7156. ordinal: 1,
  7157. name: "裁决",
  7158. type: "string",
  7159. state: "filled",
  7160. filledAt: expect.any(Number),
  7161. filledBy: HARNESS_PARENT_SESSION,
  7162. line: 3,
  7163. },
  7164. ]);
  7165. // run 行上是有效脚本,两列同一笔(哈希对文本),getScript 给的也是它。
  7166. const record = harness.journal.getRun(runId);
  7167. expect(record?.scriptText).toBe(result.scriptText);
  7168. expect(record?.scriptHash).toBe(
  7169. createHash("sha256").update(result.scriptText, "utf8").digest("hex"),
  7170. );
  7171. expect(await harness.service.getScript(runId)).toBe(result.scriptText);
  7172. // hole-filled 与 phase-entered 一样原样转发,带有效脚本的阶段表。
  7173. const filledEvent = harness.runEvents.find((event) => event.eventType === "hole-filled");
  7174. expect(filledEvent?.payload).toMatchObject({
  7175. siteId: VERDICT,
  7176. filledBy: HARNESS_PARENT_SESSION,
  7177. // 无站点、无标记的补全:留白自己的阶段仍在表里(analysis.md「Sites」)。
  7178. phaseNames: ["准备", "裁决"],
  7179. });
  7180. });
  7181. });
  7182. it("函数体可以带阶段与子代理:新站点带留白自己的一层前缀,phasesAdded 列出函数体的阶段", async () => {
  7183. const harness = makeHarness({
  7184. actorScripts: { [`${VERDICT}/actor#1@1`]: [{ kind: "submit", result: { text: "judged" } }] },
  7185. });
  7186. const runId = await submitAndReachHole(harness, "hole-body-phases");
  7187. const result = await fill(
  7188. harness,
  7189. runId,
  7190. [
  7191. 'phase("复核");',
  7192. 'const j = await agent("judge").ask<{ text: string }>("judge it");',
  7193. "return j.text;",
  7194. ].join("\n"),
  7195. );
  7196. expect(result).toMatchObject({ ok: true, phasesAdded: ["复核"] });
  7197. await settle(harness, runId);
  7198. const done = await harness.service.getTask(runId);
  7199. expect(done?.output).toBe("judged");
  7200. expect(
  7201. harness.runEvents.find((event) => event.eventType === "actor-created")?.payload,
  7202. ).toMatchObject({ actor: { siteId: "actor#1", ordinal: 1 } });
  7203. expect(
  7204. harness.runEvents
  7205. .filter((event) => event.eventType === "actor-created")
  7206. .map((event) => (event.payload.actor as { siteId: string }).siteId),
  7207. ).toEqual(["actor#1", `${VERDICT}/actor#1`]);
  7208. expect(
  7209. harness.runEvents.find((event) => event.eventType === "hole-filled")?.payload,
  7210. // 函数体以 `phase("复核")` 开头:留白自己的阶段没有成员,但仍留在表里(analysis.md「Sites」)。
  7211. // 修复原因:它曾被丢掉,接龙的每一步名字因此从侧栏与 phaseNames 消失。
  7212. ).toMatchObject({ phaseNames: ["准备", "裁决", "复核"] });
  7213. });
  7214. it("函数体里可以跑种子脚本没有的命令:world.run 的授权只在编译期,driver 没有第二份名单", async () => {
  7215. // 回归:driver 曾持有 launch 时从种子脚本收集的 declaredRunCommands,补全编译的是有效脚本、
  7216. // driver 手里却还是种子那份,函数体里第一次出现的 `world.run("echo", …)` 被当"接线错误"拒掉,
  7217. // 整个 run 因此失败(workflow-world-read.ts 文件头第 2 条;authoring.md「Running commands」)。
  7218. const ran: string[] = [];
  7219. const stream = (text: string) => ({
  7220. text,
  7221. bytes: Buffer.byteLength(text, "utf8"),
  7222. truncated: false,
  7223. });
  7224. const executionPort: ExecutionPort = {
  7225. run: async (request) => {
  7226. ran.push(request.command.mode === "argv" ? request.command.file : request.command.command);
  7227. return {
  7228. status: "completed",
  7229. exitCode: 0,
  7230. stdout: stream("hi\n"),
  7231. stderr: stream(""),
  7232. durationMs: 1,
  7233. timedOut: false,
  7234. cancelled: false,
  7235. startedAt: new Date(0),
  7236. completedAt: new Date(1),
  7237. } as never;
  7238. },
  7239. };
  7240. const harness = makeHarness({ executionPort });
  7241. const runId = await submitAndReachHole(harness, "hole-body-new-command");
  7242. const result = await fill(
  7243. harness,
  7244. runId,
  7245. ['const r = await world.run("echo", ["hi"]);', "return r.stdout.trim();"].join("\n"),
  7246. );
  7247. expect(result).toMatchObject({ ok: true });
  7248. await settle(harness, runId);
  7249. const done = await harness.service.getTask(runId);
  7250. expect(done?.status).toBe("completed");
  7251. expect(done?.output).toBe("hi");
  7252. expect(ran).toEqual(["echo"]);
  7253. });
  7254. it("编不过的函数体是拒绝:诊断落在函数体坐标上,什么都没写,留白照旧在等", async () => {
  7255. const harness = makeHarness();
  7256. const runId = await submitAndReachHole(harness, "hole-diagnostics");
  7257. const before = harness.journal.getRun(runId)?.scriptText;
  7258. const refused = await fill(
  7259. harness,
  7260. runId,
  7261. ['const x: number = "no";', 'return "v";'].join("\n"),
  7262. );
  7263. expect(refused.ok).toBe(false);
  7264. if (refused.ok) throw new Error("expected compile_failed");
  7265. expect(refused.reason).toBe("compile_failed");
  7266. expect(refused.diagnostics).toEqual([
  7267. // 分析器把 2322 锚在声明名 `x` 上(第 7 列),拼接垫的缩进已经扣掉。
  7268. expect.objectContaining({ inFill: true, line: 1, column: 7, code: 2322 }),
  7269. ]);
  7270. expect(harness.journal.getRun(runId)?.scriptText).toBe(before);
  7271. expect((await harness.service.getTask(runId))?.holes?.[0]?.state).toBe("waiting");
  7272. expect(harness.runEvents.some((event) => event.eventType === "hole-filled")).toBe(false);
  7273. // 改好再交:同一处留白照常接受。
  7274. expect(await fill(harness, runId, 'return "v";')).toMatchObject({ ok: true });
  7275. await settle(harness, runId);
  7276. });
  7277. describe("函数体点名的模型只能取本 run 的绑定表(MR !2837 评审 CR-01)", () => {
  7278. const LIGHT: ModelSelection = { providerId: "zhipu", modelId: "GLM-5.3-Flash" };
  7279. const judgeBody = (name: string) =>
  7280. [
  7281. `const j = await agent("judge", { model: model(${JSON.stringify(name)}) }).ask<{ text: string }>("judge it");`,
  7282. "return j.text;",
  7283. ].join("\n");
  7284. it("表外的名字是 9011 拒绝:落在函数体坐标上,什么都没写,留白照旧在等", async () => {
  7285. const harness = makeHarness();
  7286. const runId = await submitAndReachHole(harness, "hole-model-unbound", {
  7287. modelBindings: { "GLM-5.3-Flash": LIGHT },
  7288. });
  7289. const before = harness.journal.getRun(runId)?.scriptText;
  7290. const refused = await fill(harness, runId, judgeBody("GLM-5.3$high"));
  7291. if (refused.ok) throw new Error("expected compile_failed");
  7292. expect(refused.reason).toBe("compile_failed");
  7293. expect(refused.diagnostics).toEqual([
  7294. expect.objectContaining({ inFill: true, line: 1, code: 9011 }),
  7295. ]);
  7296. expect(refused.diagnostics?.[0]?.message).toContain('"GLM-5.3$high"');
  7297. expect(refused.diagnostics?.[0]?.message).toContain('"GLM-5.3-Flash" = zhipu/GLM-5.3-Flash');
  7298. expect(harness.journal.getRun(runId)?.scriptText).toBe(before);
  7299. expect((await harness.service.getTask(runId))?.holes?.[0]?.state).toBe("waiting");
  7300. expect(harness.runEvents.some((event) => event.eventType === "hole-filled")).toBe(false);
  7301. expect(harness.actorRuntimeInputs.some((input) => "actorModel" in input)).toBe(false);
  7302. });
  7303. it("run 没点名过任何模型时,函数体点名模型同样被拒", async () => {
  7304. const harness = makeHarness();
  7305. const runId = await submitAndReachHole(harness, "hole-model-no-table");
  7306. const refused = await fill(harness, runId, judgeBody("GLM-5.3-Flash"));
  7307. if (refused.ok) throw new Error("expected compile_failed");
  7308. expect(refused.diagnostics).toEqual([expect.objectContaining({ inFill: true, code: 9011 })]);
  7309. expect(refused.diagnostics?.[0]?.message).toContain("without naming any model");
  7310. expect((await harness.service.getTask(runId))?.holes?.[0]?.state).toBe("waiting");
  7311. });
  7312. it("表里的名字照常接受,子代理跑在绑定的模型上", async () => {
  7313. const harness = makeHarness({
  7314. actorScripts: {
  7315. [`${VERDICT}/actor#1@1`]: [{ kind: "submit", result: { text: "judged" } }],
  7316. },
  7317. });
  7318. const runId = await submitAndReachHole(harness, "hole-model-bound", {
  7319. modelBindings: { "GLM-5.3-Flash": LIGHT },
  7320. });
  7321. expect(await fill(harness, runId, judgeBody("GLM-5.3-Flash"))).toMatchObject({ ok: true });
  7322. await settle(harness, runId);
  7323. expect((await harness.service.getTask(runId))?.output).toBe("judged");
  7324. const judge = harness.actorRuntimeInputs.find(
  7325. (input) => refToString(input.actor) === `${VERDICT}/actor#1@1`,
  7326. );
  7327. expect(judge?.actorModel).toEqual(LIGHT);
  7328. });
  7329. });
  7330. it("不在等的种种:未知 run、未知留白、还没到达、已补过、已停下(指向 ResumeWorkflowRun)", async () => {
  7331. expect(await fill(makeHarness(), "dwfrun-nope", "return 1;")).toMatchObject({
  7332. ok: false,
  7333. reason: "run_not_found",
  7334. });
  7335. // 还没到达:子代理挂着,脚本停在留白之前的 ask 上。
  7336. const hanging = makeHarness({ hangActors: true });
  7337. const pending = await submitRun(hanging, {
  7338. cwd: TEST_CWD,
  7339. phaseNames: HOLE_PHASES,
  7340. scriptText: HOLE_SCRIPT,
  7341. trace: traceFor("hole-not-reached"),
  7342. });
  7343. await vi.waitFor(() => {
  7344. expect(hanging.runEvents.some((event) => event.eventType === "node-dispatched")).toBe(true);
  7345. });
  7346. const notReached = await fill(hanging, pending, 'return "v";');
  7347. expect(notReached).toMatchObject({ ok: false, reason: "hole_not_waiting" });
  7348. expect((await hanging.service.getTask(pending))?.holes).toBeUndefined();
  7349. await hanging.service.cancel(pending);
  7350. await settle(hanging, pending);
  7351. const harness = makeHarness();
  7352. const runId = await submitAndReachHole(harness, "hole-refusals");
  7353. const unknownHole = await fill(harness, runId, "return 1;", "hole#9");
  7354. expect(unknownHole).toMatchObject({ ok: false, reason: "hole_not_waiting" });
  7355. if (unknownHole.ok) throw new Error("unreachable");
  7356. expect(unknownHole.message).toContain("hole#9");
  7357. expect(await fill(harness, runId, 'return "v";')).toMatchObject({ ok: true });
  7358. const again = await fill(harness, runId, 'return "w";');
  7359. expect(again).toMatchObject({ ok: false, reason: "hole_not_waiting" });
  7360. if (again.ok) throw new Error("unreachable");
  7361. expect(again.message).toContain("already filled");
  7362. await settle(harness, runId);
  7363. // 在留白处停下的 run:停驻的分支随取消撤下,补全指向 resume。
  7364. const stopped = makeHarness();
  7365. const stoppedRun = await submitAndReachHole(stopped, "hole-stopped");
  7366. await stopped.service.cancel(stoppedRun);
  7367. await settle(stopped, stoppedRun);
  7368. expect((await stopped.service.getTask(stoppedRun))?.status).toBe("cancelled");
  7369. const afterStop = await fill(stopped, stoppedRun, 'return "v";');
  7370. expect(afterStop).toMatchObject({ ok: false, reason: "hole_not_waiting" });
  7371. if (afterStop.ok) throw new Error("unreachable");
  7372. expect(afterStop.message).toContain("ResumeWorkflowRun");
  7373. // 死掉的停驻不报 waiting:没有引擎在等,快照上这处留白整个不出。
  7374. expect((await stopped.service.getTask(stoppedRun))?.holes).toBeUndefined();
  7375. });
  7376. it("草稿就地改写成有效脚本、路径不变;没有草稿的 run 由注入的铸造器补一份", async () => {
  7377. const dir = await mkdtemp(join(tmpdir(), "dwf-hole-draft-"));
  7378. const draftPath = join(dir, "裁决.dwf.ts");
  7379. await writeFile(draftPath, HOLE_SCRIPT, "utf8");
  7380. const harness = makeHarness();
  7381. const runId = await submitAndReachHole(harness, "hole-draft", { scriptPath: draftPath });
  7382. const result = await fill(harness, runId, 'return "v";');
  7383. if (!result.ok) throw new Error(result.message);
  7384. expect(result.scriptPath).toBe(draftPath);
  7385. expect(await readFile(draftPath, "utf8")).toBe(result.scriptText);
  7386. expect((await harness.service.getTask(runId))?.scriptPath).toBe(draftPath);
  7387. await settle(harness, runId);
  7388. // 没有草稿的 run:铸造器先于引擎落盘,路径随 hole-filled 进 journal,冷读面重启后照样找得到。
  7389. await withSqliteJournal(async (journal) => {
  7390. const minted: { cwd: string; name: string; source: string }[] = [];
  7391. const mintPath = join(dir, "minted.dwf.ts");
  7392. const minting = makeHarness({
  7393. journal,
  7394. writeWorkflowDraft: async (input) => {
  7395. minted.push(input);
  7396. return { path: mintPath };
  7397. },
  7398. });
  7399. const draftless = await submitAndReachHole(minting, "hole-mint", { name: "夜间审阅" });
  7400. const mintedResult = await fill(minting, draftless, 'return "v";');
  7401. if (!mintedResult.ok) throw new Error(mintedResult.message);
  7402. expect(mintedResult.scriptPath).toBe(mintPath);
  7403. expect(minted).toEqual([
  7404. { cwd: TEST_CWD, name: "夜间审阅", source: mintedResult.scriptText },
  7405. ]);
  7406. expect((await minting.service.getTask(draftless))?.scriptPath).toBe(mintPath);
  7407. expect(
  7408. minting.runEvents.find((event) => event.eventType === "hole-filled")?.payload,
  7409. ).toMatchObject({ siteId: VERDICT, scriptPath: mintPath });
  7410. await settle(minting, draftless);
  7411. // 冷读:另一个 service 实例(没有条目)从 journal 事件读回补全铸的那份,而不是 run-launched
  7412. // 上的缺席。
  7413. const cold = makeHarness({ journal });
  7414. expect((await cold.service.getTask(draftless))?.scriptPath).toBe(mintPath);
  7415. expect((await cold.service.getRunDetail?.(draftless))?.scriptPath).toBe(mintPath);
  7416. });
  7417. await rm(dir, { recursive: true, force: true });
  7418. });
  7419. /** 两个 future 各停在一处留白:两处可以同时在等,模型也会把两次补全放进同一个并行批里。 */
  7420. const TWO_HOLES_SCRIPT = [
  7421. 'phase("准备");',
  7422. "const left = future(async () => {",
  7423. ' const a = await agent("l").ask<{ text: string }>("left");',
  7424. ' return await hole<string>("左", `l ${a.text}`);',
  7425. "});",
  7426. "const right = future(async () => {",
  7427. ' const b = await agent("r").ask<{ text: string }>("right");',
  7428. ' return await hole<string>("右", `r ${b.text}`);',
  7429. "});",
  7430. "const [x, y] = await Promise.all([left, right]);",
  7431. 'return x + "+" + y;',
  7432. ].join("\n");
  7433. async function submitAndReachBothHoles(harness: Harness, name: string): Promise<string> {
  7434. const runId = await submitRun(harness, {
  7435. cwd: TEST_CWD,
  7436. parentSessionId: HARNESS_PARENT_SESSION,
  7437. phaseNames: ["准备", "左", "右"],
  7438. scriptText: TWO_HOLES_SCRIPT,
  7439. trace: traceFor(name),
  7440. });
  7441. await vi.waitFor(() => {
  7442. expect(
  7443. harness.runEvents.filter(
  7444. (event) => event.runId === runId && event.eventType === "hole-reached",
  7445. ),
  7446. ).toHaveLength(2);
  7447. });
  7448. return runId;
  7449. }
  7450. it("同一个 run 的两次并发补全串行执行:journal 的有效脚本同时带着两个函数体,两个分支都完成", async () => {
  7451. await withSqliteJournal(async (journal) => {
  7452. const harness = makeHarness({ journal });
  7453. const runId = await submitAndReachBothHoles(harness, "hole-concurrent");
  7454. expect((await harness.service.getTask(runId))?.holes?.map((hole) => hole.state)).toEqual([
  7455. "waiting",
  7456. "waiting",
  7457. ]);
  7458. const [first, second] = await Promise.all([
  7459. fill(harness, runId, 'return "L";', LEFT),
  7460. fill(harness, runId, 'return "R";', RIGHT),
  7461. ]);
  7462. expect(first).toMatchObject({ ok: true });
  7463. expect(second).toMatchObject({ ok: true });
  7464. if (!second.ok || !first.ok) throw new Error("unreachable");
  7465. // 第二次是在第一次的有效脚本上拼的:它交出的文本包含两个函数体,journal 行就是它。
  7466. expect(second.scriptText).toContain('hole<string>("左", `l ${a.text}`, async () => {');
  7467. expect(second.scriptText).toContain('hole<string>("右", `r ${b.text}`, async () => {');
  7468. expect(second.scriptText).toContain('return "L";');
  7469. expect(second.scriptText).toContain('return "R";');
  7470. const record = journal.getRun(runId);
  7471. expect(record?.scriptText).toBe(second.scriptText);
  7472. expect(record?.scriptHash).toBe(
  7473. createHash("sha256").update(second.scriptText, "utf8").digest("hex"),
  7474. );
  7475. await settle(harness, runId);
  7476. const done = await harness.service.getTask(runId);
  7477. expect(done?.status).toBe("completed");
  7478. expect(done?.output).toBe("L+R");
  7479. expect(done?.holes?.map((hole) => [hole.siteId, hole.state])).toEqual([
  7480. [LEFT, "filled"],
  7481. [RIGHT, "filled"],
  7482. ]);
  7483. expect(
  7484. harness.runEvents
  7485. .filter((event) => event.eventType === "hole-filled")
  7486. .map((event) => event.payload.siteId),
  7487. ).toEqual([LEFT, RIGHT]);
  7488. });
  7489. });
  7490. it("被拒绝的第一次补全不阻塞排在它后面的第二次", async () => {
  7491. const harness = makeHarness();
  7492. const runId = await submitAndReachBothHoles(harness, "hole-refused-first");
  7493. const [refused, accepted] = await Promise.all([
  7494. // `hole<string>` 的体返回 number:编译期拒绝。
  7495. fill(harness, runId, "return 1;", LEFT),
  7496. fill(harness, runId, 'return "R";', RIGHT),
  7497. ]);
  7498. expect(refused).toMatchObject({ ok: false, reason: "compile_failed" });
  7499. expect(accepted).toMatchObject({ ok: true });
  7500. if (!accepted.ok) throw new Error("unreachable");
  7501. expect(accepted.scriptText).not.toContain("return 1;");
  7502. expect(accepted.scriptText).toContain('return "R";');
  7503. expect(
  7504. (await harness.service.getTask(runId))?.holes?.map((hole) => [hole.siteId, hole.state]),
  7505. ).toEqual([
  7506. [LEFT, "waiting"],
  7507. [RIGHT, "filled"],
  7508. ]);
  7509. const retried = await fill(harness, runId, 'return "L";', LEFT);
  7510. expect(retried).toMatchObject({ ok: true });
  7511. if (!retried.ok) throw new Error("unreachable");
  7512. expect(retried.scriptText).toContain('return "R";');
  7513. await settle(harness, runId);
  7514. expect((await harness.service.getTask(runId))?.output).toBe("L+R");
  7515. });
  7516. it("递归补全:外层函数体里再开一处留白,内层体读到外层体与留白之前的绑定;两次补全都就地改写草稿;停下后 resume 不再请求任何留白", async () => {
  7517. const NESTED_SCRIPT = [
  7518. "interface Plan { step: string }",
  7519. 'phase("探索");',
  7520. 'const seed = await agent("scout").ask<{ text: string }>("scout it");',
  7521. 'const plan = await hole<Plan>("决定", `plan for ${seed.text}`);',
  7522. 'phase("执行");',
  7523. 'const done = await agent("worker").ask<{ text: string }>(`execute ${plan.step}`);',
  7524. "return done.text;",
  7525. ].join("\n");
  7526. const dir = await mkdtemp(join(tmpdir(), "dwf-hole-nested-"));
  7527. const draftPath = join(dir, "决定.dwf.ts");
  7528. await writeFile(draftPath, NESTED_SCRIPT, "utf8");
  7529. // worker 的计划是一个**共享的**数组:第一世挂起(好让 run 在两次补全之后停下),resume 之前
  7530. // 换成一次提交——重水化出来的新 runtime 拿到的是同一个数组引用。
  7531. const workerPlan: ActorPlan[] = [{ kind: "hang-until-cancelled" }];
  7532. await withSqliteJournal(async (journal) => {
  7533. const harness = makeHarness({
  7534. journal,
  7535. actorScripts: {
  7536. "actor#1@1": [{ kind: "submit", result: { text: "seed" } }],
  7537. [`${DECIDE}/actor#1@1`]: [{ kind: "submit", result: { text: "draft" } }],
  7538. "actor#2@1": workerPlan,
  7539. },
  7540. });
  7541. const runId = await submitRun(harness, {
  7542. cwd: TEST_CWD,
  7543. parentSessionId: HARNESS_PARENT_SESSION,
  7544. phaseNames: ["探索", "决定", "执行"],
  7545. scriptPath: draftPath,
  7546. scriptText: NESTED_SCRIPT,
  7547. trace: traceFor("hole-nested"),
  7548. });
  7549. const reachedIds = () =>
  7550. harness.runEvents
  7551. .filter((event) => event.runId === runId && event.eventType === "hole-reached")
  7552. .map((event) => (event.payload.instance as { siteId: string }).siteId);
  7553. await vi.waitFor(() => expect(reachedIds()).toEqual([DECIDE]));
  7554. // 第一次补全:体里先开一个阶段、问一次,再以内层留白的结果返回;内层留白的 prompt 读体内的 const。
  7555. const outer = await fill(
  7556. harness,
  7557. runId,
  7558. [
  7559. 'phase("初步");',
  7560. 'const draft = await agent("drafter").ask<{ text: string }>("draft it");',
  7561. "const x = draft.text;",
  7562. 'return await hole<Plan>("细化", `refine ${x}`);',
  7563. ].join("\n"),
  7564. DECIDE,
  7565. );
  7566. if (!outer.ok) throw new Error(outer.message);
  7567. expect(outer.phasesAdded).toEqual(["初步", "细化"]);
  7568. expect(outer.scriptPath).toBe(draftPath);
  7569. expect(await readFile(draftPath, "utf8")).toBe(outer.scriptText);
  7570. // run 停在嵌套的留白处:id 是它自己的名字键(不带外层前缀),类型来自有效脚本,前后邻居是
  7571. // 有效脚本的阶段。
  7572. await vi.waitFor(() => expect(reachedIds()).toEqual([DECIDE, REFINE]));
  7573. const nestedReached = harness.runEvents.find(
  7574. (event) =>
  7575. event.eventType === "hole-reached" &&
  7576. reachedIds().length === 2 &&
  7577. (event.payload.instance as { siteId: string }).siteId === REFINE,
  7578. );
  7579. expect(nestedReached?.payload).toMatchObject({
  7580. name: "细化",
  7581. prompt: "refine draft",
  7582. type: "Plan",
  7583. reachedAt: expect.any(Number),
  7584. });
  7585. const parked = await harness.service.getTask(runId);
  7586. expect(parked?.holes).toEqual([
  7587. expect.objectContaining({
  7588. siteId: DECIDE,
  7589. state: "filled",
  7590. filledBy: HARNESS_PARENT_SESSION,
  7591. }),
  7592. expect.objectContaining({
  7593. siteId: REFINE,
  7594. ordinal: 1,
  7595. name: "细化",
  7596. type: "Plan",
  7597. state: "waiting",
  7598. before: "初步",
  7599. after: "执行",
  7600. }),
  7601. ]);
  7602. expect(
  7603. harness.runEvents.find((event) => event.eventType === "hole-filled")?.payload,
  7604. // 外层留白的函数体以标记开头,它自己的阶段仍留在表里(「决定」不再从 phaseNames 消失)。
  7605. ).toMatchObject({
  7606. siteId: DECIDE,
  7607. phaseNames: ["探索", "决定", "初步", "细化", "执行"],
  7608. holes: [3],
  7609. });
  7610. // 第二次补全:内层体读外层体的 `x` 与外层留白之前的 `seed`;新 id 带内层留白自己的前缀。
  7611. const inner = await fill(harness, runId, "return { step: `${seed.text}/${x}` };", REFINE);
  7612. if (!inner.ok) throw new Error(inner.message);
  7613. expect(inner.phasesAdded).toEqual([]);
  7614. expect(inner.scriptPath).toBe(draftPath);
  7615. expect(await readFile(draftPath, "utf8")).toBe(inner.scriptText);
  7616. expect(inner.scriptText).toContain('hole<Plan>("细化", `refine ${x}`, async () => {');
  7617. expect(inner.scriptText).toContain("return { step: `${seed.text}/${x}` };");
  7618. // journal 的 run 行:两个函数体嵌套在有效脚本里,哈希对文本。
  7619. const record = journal.getRun(runId);
  7620. expect(record?.scriptText).toBe(inner.scriptText);
  7621. expect(record?.scriptHash).toBe(
  7622. createHash("sha256").update(inner.scriptText, "utf8").digest("hex"),
  7623. );
  7624. expect((await harness.service.getTask(runId))?.holes?.map((hole) => hole.state)).toEqual([
  7625. "filled",
  7626. "filled",
  7627. ]);
  7628. // 内层体的值流进了外层留白之后的阶段:worker 的问句里带着 seed/draft。
  7629. await vi.waitFor(() => {
  7630. expect(harness.actorModelRequests["actor#2@1"]?.requests.length ?? 0).toBeGreaterThan(0);
  7631. });
  7632. expect(
  7633. JSON.stringify(harness.actorModelRequests["actor#2@1"]?.requests[0]?.messages),
  7634. ).toContain("execute seed/draft");
  7635. // 两次补全之后停下,再 resume:有效脚本的两个函数体内联执行,一次留白请求都没有。
  7636. await harness.service.cancel(runId);
  7637. await settle(harness, runId);
  7638. expect((await harness.service.getTask(runId))?.status).toBe("cancelled");
  7639. workerPlan.splice(0, workerPlan.length, { kind: "submit", result: { text: "shipped" } });
  7640. const eventsBeforeResume = harness.runEvents.length;
  7641. const resumed = await harness.service.resume(runId);
  7642. expect(resumed).toMatchObject({ ok: true, runId });
  7643. await settle(harness, runId);
  7644. const secondLife = harness.runEvents.slice(eventsBeforeResume);
  7645. expect(secondLife.some((event) => event.eventType === "hole-reached")).toBe(false);
  7646. const finished = await harness.service.getTask(runId);
  7647. expect(finished?.status).toBe("completed");
  7648. expect(finished?.output).toBe("shipped");
  7649. expect(finished?.scriptPath).toBe(draftPath);
  7650. expect(
  7651. JSON.stringify(harness.actorModelRequests["actor#2@1"]?.requests.at(-1)?.messages),
  7652. ).toContain("execute seed/draft");
  7653. });
  7654. await rm(dir, { recursive: true, force: true });
  7655. });
  7656. // 修复原因:留白 id 曾逐层拼接(`hole#1/hole#1/…`,每层 7 个字符),十层的接龙里最里层的 id 就过了
  7657. // 协议的 64 字符上界。这里在真实的 SQLite journal 上跑一条十步的尾巴留白接龙:每一步都是一次
  7658. // FillWorkflowHole,最后一步派一个子代理并返回;每条到达事件、每个子代理、run 的留白快照里的 id
  7659. // 都在 64 以内,且与深度无关。
  7660. it("十步的尾巴留白接龙跑到完成:每一步一个名字键 id,深度不进 id,所有 id 都在 64 字符以内", async () => {
  7661. const STEPS = 10;
  7662. const stepName = (k: number) => `第${k}步`;
  7663. const SEED = [
  7664. 'phase("起步");',
  7665. 'const seed = await agent("勘察员").ask<{ text: string }>("look");',
  7666. `return await hole<string>("${stepName(1)}", \`from \${seed.text}\`);`,
  7667. ].join("\n");
  7668. const last = holeSiteId(stepName(STEPS));
  7669. await withSqliteJournal(async (journal) => {
  7670. const harness = makeHarness({
  7671. journal,
  7672. actorScripts: {
  7673. "actor#1@1": [{ kind: "submit", result: { text: "seed" } }],
  7674. [`${last}/actor#1@1`]: [{ kind: "submit", result: { text: "shipped" } }],
  7675. },
  7676. });
  7677. const runId = await submitRun(harness, {
  7678. cwd: TEST_CWD,
  7679. parentSessionId: HARNESS_PARENT_SESSION,
  7680. phaseNames: ["起步", stepName(1)],
  7681. scriptText: SEED,
  7682. trace: traceFor("hole-chain-ten"),
  7683. });
  7684. const reached = () =>
  7685. harness.runEvents
  7686. .filter((event) => event.runId === runId && event.eventType === "hole-reached")
  7687. .map((event) => (event.payload.instance as { siteId: string }).siteId);
  7688. for (let k = 1; k <= STEPS; k += 1) {
  7689. const id = holeSiteId(stepName(k));
  7690. await vi.waitFor(() => expect(reached()).toContain(id));
  7691. const body =
  7692. k === STEPS
  7693. ? 'const done = await agent("收尾").ask<{ text: string }>(`finish ${seed.text}`);\nreturn done.text;'
  7694. : `return await hole<string>("${stepName(k + 1)}", "progress ${k}");`;
  7695. const result = await fill(harness, runId, body, id);
  7696. if (!result.ok) throw new Error(`step ${k}: ${result.message}`);
  7697. }
  7698. await settle(harness, runId);
  7699. const done = await harness.service.getTask(runId);
  7700. expect(done?.status).toBe("completed");
  7701. expect(done?.output).toBe("shipped");
  7702. // 每一步恰好到达一次,按接龙次序。
  7703. expect(reached()).toEqual(
  7704. Array.from({ length: STEPS }, (_, i) => holeSiteId(stepName(i + 1))),
  7705. );
  7706. // 所有进过事件的 id:到达的留白、创建的子代理,都在协议上界以内,而且最长的与深度无关。
  7707. const actorIds = harness.runEvents
  7708. .filter((event) => event.eventType === "actor-created")
  7709. .map((event) => (event.payload.actor as { siteId: string }).siteId);
  7710. expect(actorIds).toEqual(["actor#1", `${last}/actor#1`]);
  7711. for (const id of [...reached(), ...actorIds]) expect(id.length, id).toBeLessThanOrEqual(64);
  7712. expect(Math.max(...[...reached(), ...actorIds].map((id) => id.length))).toBe(
  7713. `${last}/actor#1`.length,
  7714. );
  7715. // 快照:十个留白都补全了;有效脚本的阶段表念得出每一步的名字。
  7716. expect(done?.holes?.map((hole) => [hole.siteId, hole.state])).toEqual(
  7717. Array.from({ length: STEPS }, (_, i) => [holeSiteId(stepName(i + 1)), "filled"]),
  7718. );
  7719. const lastFilled = harness.runEvents
  7720. .filter((event) => event.eventType === "hole-filled")
  7721. .at(-1);
  7722. expect(lastFilled?.payload.phaseNames).toEqual([
  7723. "起步",
  7724. ...Array.from({ length: STEPS }, (_, i) => stepName(i + 1)),
  7725. ]);
  7726. });
  7727. });
  7728. it("冷回放为 hole-reached 铸出与 live 逐字节相同的载荷(type 从行里的有效脚本重建)", async () => {
  7729. const harness = makeHarness();
  7730. const runId = await submitAndReachHole(harness, "hole-replay");
  7731. expect(await fill(harness, runId, 'return "v";')).toMatchObject({ ok: true });
  7732. await settle(harness, runId);
  7733. const live = harness.runEvents.filter(
  7734. (event) => event.eventType === "hole-reached" || event.eventType === "hole-filled",
  7735. );
  7736. const row = (harness.journal as SweepableJournalStore)
  7737. .listRunsByParentSession(HARNESS_PARENT_SESSION, 16)
  7738. .find((item) => item.runId === runId);
  7739. const replayed = replayRunProgress(
  7740. row!,
  7741. harness.journal,
  7742. resolveWorkflowDefaultConcurrency(),
  7743. ).filter((event) => event.eventType === "hole-reached" || event.eventType === "hole-filled");
  7744. expect(replayed).toEqual(live);
  7745. });
  7746. });
  7747. describe("dynamic workflow run service — 额度停止后到点自动续跑", () => {
  7748. // apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Resuming after a quota
  7749. // reset」:真实格式的 1308 原文(没有 Retry-After)→ 停止记录带上重置时刻 → 到点自动续跑。
  7750. const SCRIPT = [
  7751. "interface Answer { text: string }",
  7752. 'const a = await agent("worker").ask<Answer>("go");',
  7753. "return a.text;",
  7754. ].join("\n");
  7755. /** 北京时间的「YYYY-MM-DD HH:MM:SS」,与服务端文案同形。 */
  7756. const beijingText = (at: number): string => {
  7757. const iso = new Date(at + 8 * 60 * 60 * 1000).toISOString();
  7758. return `${iso.slice(0, 10)} ${iso.slice(11, 19)}`;
  7759. };
  7760. it("原文里的重置时刻落进停止记录,到点后续跑并跑完", async () => {
  7761. const resetAt = Math.floor((Date.now() + 2 * 60 * 60 * 1000) / 1000) * 1000;
  7762. const quotaError = Object.assign(
  7763. new Error(
  7764. `[1308][已达到 5 小时的使用上限。您的限额将在 ${beijingText(resetAt)} 重置。][20261019120000abc]`,
  7765. ),
  7766. {
  7767. name: "AiSdkModelAdapterError",
  7768. code: "model_rate_limited",
  7769. context: { reason: "rate_limited", providerCode: "1308", retryable: false },
  7770. },
  7771. );
  7772. const options: HarnessOptions = {
  7773. actorScripts: { "actor#1@1": [{ kind: "throw", error: quotaError }] },
  7774. };
  7775. const harness = makeHarness(options);
  7776. let now = Date.now();
  7777. const timers: { at: number; callback: () => void }[] = [];
  7778. const auto = startWorkflowQuotaAutoResume({
  7779. journal: harness.journal,
  7780. parentSessionId: HARNESS_PARENT_SESSION,
  7781. resume: (runId) => harness.service.resume!(runId),
  7782. subscribeRunSettled: (listener) => harness.service.subscribeRunSettled(listener),
  7783. clock: {
  7784. now: () => now,
  7785. schedule: (callback, delayMs) => {
  7786. timers.push({ at: now + delayMs, callback });
  7787. return () => {};
  7788. },
  7789. },
  7790. });
  7791. try {
  7792. const runId = await submitRun(harness, {
  7793. cwd: TEST_CWD,
  7794. parentSessionId: HARNESS_PARENT_SESSION,
  7795. scriptText: SCRIPT,
  7796. trace: traceFor("quota-auto-resume"),
  7797. });
  7798. await settle(harness, runId);
  7799. expect(harness.journal.getRun(runId)).toMatchObject({
  7800. status: "stopped",
  7801. stopReason: "provider",
  7802. failure: { providerStop: { kind: "quota", providerCode: "1308", resetAt } },
  7803. });
  7804. await vi.waitFor(() => {
  7805. expect(timers).toHaveLength(1);
  7806. });
  7807. expect(timers[0]!.at).toBe(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  7808. // 额度恢复了:子代理这次能答。时钟拨到重置时刻之后,定时器触发续跑。
  7809. options.actorScripts = { "actor#1@1": [{ kind: "submit", result: { text: "after reset" } }] };
  7810. now = timers[0]!.at;
  7811. timers.shift()!.callback();
  7812. await vi.waitFor(() => {
  7813. expect(harness.journal.getRun(runId)?.status).toBe("completed");
  7814. });
  7815. expect((await harness.service.getTask(runId))?.output).toBe("after reset");
  7816. } finally {
  7817. auto.dispose();
  7818. }
  7819. });
  7820. });
  7821. describe("session close waits for workflow actor resources", () => {
  7822. it.each([true, false])(
  7823. "drains actors even when run was already terminal=%s",
  7824. async (terminal) => {
  7825. let finish!: () => void;
  7826. const cleanup = new Promise<void>((resolve) => {
  7827. finish = resolve;
  7828. });
  7829. let cleanupStarted = false;
  7830. const harness = makeHarness({
  7831. hangActors: !terminal,
  7832. actorCleanup: async () => {
  7833. cleanupStarted = true;
  7834. await cleanup;
  7835. },
  7836. });
  7837. const runId = await submitRun(harness, {
  7838. cwd: TEST_CWD,
  7839. parentSessionId: HARNESS_PARENT_SESSION,
  7840. scriptText: TYPED_SCRIPT,
  7841. trace: traceFor("owned-workflow-close"),
  7842. });
  7843. await vi.waitFor(() => expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0));
  7844. if (terminal) await settle(harness, runId);
  7845. let closed = false;
  7846. const closing = harness.service.close().then(() => {
  7847. closed = true;
  7848. });
  7849. try {
  7850. await vi.waitFor(() => expect(cleanupStarted).toBe(true));
  7851. expect(closed).toBe(false);
  7852. finish();
  7853. await closing;
  7854. expect(closed).toBe(true);
  7855. } finally {
  7856. finish();
  7857. await closing;
  7858. }
  7859. },
  7860. );
  7861. });
  7862. it("owner close prevents an in-flight amend from launching a successor", async () => {
  7863. const harness = makeHarness({ hangActors: true });
  7864. const runId = await submitRun(harness, {
  7865. cwd: TEST_CWD,
  7866. parentSessionId: HARNESS_PARENT_SESSION,
  7867. scriptText: TYPED_SCRIPT,
  7868. trace: traceFor("close-amend-race"),
  7869. });
  7870. await vi.waitFor(() => expect(harness.actorRuntimeInputs.length).toBeGreaterThan(0));
  7871. const amending = harness.service.amend!({
  7872. cwd: TEST_CWD,
  7873. parentSessionId: HARNESS_PARENT_SESSION,
  7874. predecessorRunId: runId,
  7875. scriptText: TYPED_SCRIPT,
  7876. trace: traceFor("closing-amend"),
  7877. });
  7878. const rejected = expect(amending).rejects.toThrow(/closed/);
  7879. await harness.service.close();
  7880. await rejected;
  7881. expect(harness.service.countLiveRuns()).toBe(0);
  7882. });