plugins.test.ts 210 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { existsSync } from "node:fs";
  4. import * as asyncFs from "node:fs/promises";
  5. import { cp, mkdir, mkdtemp, readFile, rename, rm, symlink, writeFile } from "node:fs/promises";
  6. import { createServer, type Server } from "node:http";
  7. import { tmpdir } from "node:os";
  8. import { join } from "node:path";
  9. import { promisify } from "node:util";
  10. import { afterEach, describe, expect, it, vi } from "vitest";
  11. import {
  12. addMarketplace,
  13. applyClaudePluginIcons,
  14. createNodePluginAdapter,
  15. describeMarketplacePlugin,
  16. discoverNodePlugins,
  17. enrichCachedClaudeMarketplaceIcons,
  18. ensureDefaultPluginMarketplaces,
  19. installMarketplacePlugin,
  20. listInstalledPluginRecords,
  21. loadKnownMarketplacesSync,
  22. loadMarketplaceManifestSync,
  23. parsePluginIconSources,
  24. uninstallMarketplacePlugin,
  25. updateMarketplace,
  26. validateMarketplacePlugin,
  27. validateMarketplaceSource,
  28. writeBundledOfficialMarketplacePartition,
  29. } from "../src/plugins/index.js";
  30. import {
  31. activateDirectoryAtomically,
  32. recoverAtomicTargetSync,
  33. resolveAtomicReadPath,
  34. replaceDirectoryAtomically,
  35. } from "../src/plugins/atomic-directory.js";
  36. import { createArchiveFetchError } from "../src/plugins/source-errors.js";
  37. import { enumeratePluginComponents } from "../src/plugins/plugin-components.js";
  38. import {
  39. buildGitHubArchiveUrl,
  40. parsePublicGitHubRepositoryUrl,
  41. } from "../src/plugins/github-archive-source.js";
  42. import {
  43. listInstalledPluginRecordsAsync,
  44. buildMarketplaceGitEnv,
  45. } from "../src/plugins/marketplace.js";
  46. import { resolveZipPluginSource } from "../src/plugins/zip-source.js";
  47. import {
  48. appendPluginSourceCleanupError,
  49. cleanupPluginSourceBestEffort,
  50. PluginMaterialCache,
  51. } from "../src/plugins/helpers.js";
  52. import { createNodeCustomCommandAdapter } from "../src/commands/index.js";
  53. import { createNodeSkillAdapter } from "../src/skills/index.js";
  54. import {
  55. ZCODE_AGENT_CA_CERT_ENV_KEY,
  56. ZCODE_HTTP_PROXY_ENV_KEY,
  57. ZCODE_NO_PROXY_ENV_KEY,
  58. ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY,
  59. } from "@zcode/shared";
  60. const execFileAsync = promisify(execFile);
  61. vi.mock("node:fs/promises", async (importOriginal) => {
  62. const actual = await importOriginal<typeof import("node:fs/promises")>();
  63. return {
  64. ...actual,
  65. readFile: vi.fn(actual.readFile),
  66. readdir: vi.fn(actual.readdir),
  67. lstat: vi.fn(actual.lstat),
  68. stat: vi.fn(actual.stat),
  69. realpath: vi.fn(actual.realpath),
  70. };
  71. });
  72. describe("NodePluginAdapter", () => {
  73. it("shares concurrent path checks and reuses their type in Skill scanning", async () => {
  74. const root = await mkdtemp(join(tmpdir(), "zcode-shared-path-check-"));
  75. const file = join(root, "SKILL.md");
  76. const cache = new PluginMaterialCache();
  77. try {
  78. await writeFile(file, "# first");
  79. const reader = cache.reader("scope");
  80. vi.mocked(asyncFs.stat).mockClear();
  81. vi.mocked(asyncFs.realpath).mockClear();
  82. await Promise.all(Array.from({ length: 8 }, () => reader.observe(file)));
  83. expect(vi.mocked(asyncFs.stat).mock.calls.filter(([path]) => path === file)).toHaveLength(1);
  84. expect(vi.mocked(asyncFs.realpath).mock.calls.filter(([path]) => path === file)).toHaveLength(
  85. 1,
  86. );
  87. await reader.observe(root);
  88. vi.mocked(asyncFs.stat).mockClear();
  89. vi.mocked(asyncFs.lstat).mockClear();
  90. expect(await reader.skillFiles(root)).toEqual([file]);
  91. expect(asyncFs.stat).not.toHaveBeenCalled();
  92. expect(asyncFs.lstat).toHaveBeenCalledTimes(2);
  93. await writeFile(file, "# changed content");
  94. expect(await reader.validate()).toBe(false);
  95. } finally {
  96. cache.dispose();
  97. await rm(root, { recursive: true, force: true });
  98. }
  99. });
  100. it("uses directory absence without probing each candidate and detects later creation", async () => {
  101. const root = await mkdtemp(join(tmpdir(), "zcode-directory-absence-"));
  102. const cache = new PluginMaterialCache();
  103. try {
  104. const reader = cache.reader("scope");
  105. await reader.directory(root);
  106. vi.mocked(asyncFs.stat).mockClear();
  107. vi.mocked(asyncFs.realpath).mockClear();
  108. for (const name of [
  109. ".mcp.json",
  110. "hooks/hooks.json",
  111. ".claude-plugin/plugin.json",
  112. "skills",
  113. "agents",
  114. ]) {
  115. const path = join(root, name);
  116. expect(await reader.missing(path)).toBe(true);
  117. await expect(reader.json(path)).rejects.toMatchObject({ code: "ENOENT" });
  118. }
  119. expect(asyncFs.stat).not.toHaveBeenCalled();
  120. expect(asyncFs.realpath).not.toHaveBeenCalled();
  121. expect(await reader.validate()).toBe(true);
  122. expect(vi.mocked(asyncFs.stat).mock.calls.map(([path]) => path)).toEqual([root]);
  123. await mkdir(join(root, "hooks"));
  124. await writeFile(join(root, "hooks", "hooks.json"), "{}");
  125. expect(await reader.validate()).toBe(false);
  126. const next = cache.reader("scope");
  127. await next.directory(root);
  128. expect(await next.json(join(root, "hooks", "hooks.json"))).toEqual({});
  129. const moved = `${root}-old`;
  130. try {
  131. await rename(root, moved);
  132. await mkdir(root);
  133. expect(await next.validate()).toBe(false);
  134. const replaced = cache.reader("scope");
  135. await replaced.directory(root);
  136. expect(await replaced.missing(join(root, "hooks", "hooks.json"))).toBe(true);
  137. } finally {
  138. await rm(moved, { recursive: true, force: true });
  139. }
  140. } finally {
  141. cache.dispose();
  142. await rm(root, { recursive: true, force: true });
  143. }
  144. });
  145. it("keeps real checks for case-equivalent and nonstandard directory entries", async () => {
  146. const root = await mkdtemp(join(tmpdir(), "zcode-directory-case-"));
  147. const cache = new PluginMaterialCache();
  148. try {
  149. await mkdir(join(root, "SKILLS"));
  150. const reader = cache.reader("scope");
  151. await reader.directory(root);
  152. vi.mocked(asyncFs.stat).mockClear();
  153. await reader.directoryExists(join(root, "skills"));
  154. await reader.missing(join(root, "CUSTOM~1"));
  155. expect(vi.mocked(asyncFs.stat).mock.calls.map(([path]) => path)).toEqual([
  156. join(root, "skills"),
  157. join(root, "CUSTOM~1"),
  158. ]);
  159. await mkdir(join(root, "技能"));
  160. const uncertain = cache.reader("scope");
  161. await uncertain.directory(root);
  162. vi.mocked(asyncFs.stat).mockClear();
  163. await uncertain.missing(join(root, "hooks", "hooks.json"));
  164. expect(vi.mocked(asyncFs.stat).mock.calls.map(([path]) => path)).toEqual([
  165. join(root, "hooks", "hooks.json"),
  166. ]);
  167. } finally {
  168. cache.dispose();
  169. await rm(root, { recursive: true, force: true });
  170. }
  171. });
  172. it("falls back to normal discovery when the plugin root cannot be listed", async () => {
  173. const root = await mkdtemp(join(tmpdir(), "zcode-root-listing-denied-"));
  174. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  175. const adapter = createNodePluginAdapter({ storageRoot: join(root, "storage") });
  176. try {
  177. await writePluginManifest(root, { name: "listing-denied", skills: ["./skill"] });
  178. await mkdir(join(root, "skill"));
  179. await writeFile(join(root, "skill", "SKILL.md"), "---\nname: kept\n---\nbody");
  180. vi.mocked(asyncFs.readdir).mockImplementation(async (...args) => {
  181. if (args[0] === root) throw Object.assign(new Error("denied"), { code: "EACCES" });
  182. return actual.readdir(...args);
  183. });
  184. const result = await adapter.discoverPlugins({
  185. config: { dirs: [root], enabled: true, enabledPlugins: {}, options: {} },
  186. env: {},
  187. storageRoot: join(root, "storage"),
  188. workingDirectory: root,
  189. });
  190. expect(
  191. result.plugins.find((plugin) => plugin.id === "listing-denied@inline")?.skillCount,
  192. ).toBe(1);
  193. expect(vi.mocked(asyncFs.readdir).mock.calls.some(([path]) => path === root)).toBe(true);
  194. } finally {
  195. vi.mocked(asyncFs.readdir).mockReset();
  196. adapter.dispose();
  197. await rm(root, { recursive: true, force: true });
  198. }
  199. });
  200. it.each([
  201. { skills: ["./entry"], expected: ["entry"] },
  202. { skills: "./entry", expected: ["entry"] },
  203. { skills: ["./entry", "./entry/child"], expected: ["child", "entry"] },
  204. { skills: [], expected: [] },
  205. { skills: "./collection", expected: ["collection-item"] },
  206. { skills: ["./collection", "./collection/item"], expected: ["collection-item"] },
  207. { skills: undefined, expected: ["default"] },
  208. ])("uses only declared Skill entries: $skills", async ({ skills, expected }) => {
  209. const dir = await mkdtemp(join(tmpdir(), "zcode-declared-skills-"));
  210. const root = join(dir, "plugin");
  211. const storageRoot = join(dir, "storage");
  212. const adapter = createNodePluginAdapter({ storageRoot });
  213. try {
  214. await writePluginManifest(root, { name: "declared", skills });
  215. for (const [path, name] of [
  216. ["entry", "entry"],
  217. ["entry/child", "child"],
  218. ["collection/item", "collection-item"],
  219. ["skills/default", "default"],
  220. ]) {
  221. const skill = join(root, path!);
  222. await mkdir(skill, { recursive: true });
  223. await writeFile(
  224. join(skill, "SKILL.md"),
  225. `---\nname: ${name}\ndescription: demo\n---\nbody`,
  226. );
  227. }
  228. for (let attempt = 0; attempt < 2; attempt += 1) {
  229. vi.mocked(asyncFs.readdir).mockClear();
  230. const outcome = await adapter.discoverPlugins({
  231. config: { dirs: [root], enabled: true, enabledPlugins: {}, options: {} },
  232. env: {},
  233. storageRoot,
  234. workingDirectory: dir,
  235. });
  236. const plugin = outcome.plugins.find((item) => item.id === "declared@inline");
  237. expect(plugin?.skillCount).toBe(expected.length);
  238. expect(componentNames(plugin?.components ?? [], "skill").sort()).toEqual(expected);
  239. const standalone = await enumeratePluginComponents(root, { name: "declared", skills });
  240. expect(componentNames(standalone, "skill").sort()).toEqual(expected);
  241. const runtime = await createNodeSkillAdapter().discoverSkills({
  242. roots: outcome.skillRoots,
  243. workingDirectory: dir,
  244. });
  245. expect(runtime.skills.map((skill) => skill.name).sort()).toEqual(expected);
  246. // 声明单技能后,不应再枚举附属目录;未声明默认根也不应被补扫。
  247. const reads = vi.mocked(asyncFs.readdir).mock.calls.map(([path]) => String(path));
  248. expect(reads).not.toContain(join(root, "entry"));
  249. if (skills !== undefined) expect(reads).not.toContain(join(root, "skills"));
  250. }
  251. } finally {
  252. adapter.dispose();
  253. await rm(dir, { recursive: true, force: true });
  254. }
  255. });
  256. it("shares each Skill root scan across diagnostics, counts and component metadata", async () => {
  257. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-scan-reuse-"));
  258. const root = join(directory, "plugin");
  259. await writePluginManifest(root, { name: "scan-reuse", skills: ["./skills"] });
  260. const files = ["first", "second"].map((name) => join(root, "skills", name, "SKILL.md"));
  261. for (const path of files) {
  262. await mkdir(join(path, ".."), { recursive: true });
  263. await writeFile(path, "---\nname: duplicate-name\n---\nbody");
  264. }
  265. const adapter = createNodePluginAdapter({ storageRoot: join(directory, "storage") });
  266. const request = {
  267. storageRoot: join(directory, "storage"),
  268. workingDirectory: directory,
  269. config: {
  270. dirs: [root],
  271. enabled: true,
  272. enabledPlugins: {},
  273. options: {},
  274. suppressedBuiltins: [],
  275. },
  276. };
  277. try {
  278. for (let query = 0; query < 2; query += 1) {
  279. vi.mocked(asyncFs.lstat).mockClear();
  280. const result = await adapter.discoverPlugins(request);
  281. expect(result.plugins[0]?.skillCount).toBe(2);
  282. expect(
  283. result.plugins[0]?.components.find((group) => group.kind === "skill")?.items,
  284. ).toEqual([{ name: "duplicate-name" }]);
  285. for (const file of files)
  286. expect(
  287. vi.mocked(asyncFs.lstat).mock.calls.filter(([path]) => path === file),
  288. ).toHaveLength(1);
  289. }
  290. } finally {
  291. adapter.dispose();
  292. await rm(directory, { recursive: true, force: true });
  293. }
  294. });
  295. it("avoids reads for missing materials and detects later creation", async () => {
  296. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-material-"));
  297. const path = join(directory, "optional.json");
  298. const parentFile = join(directory, "not-a-directory");
  299. await writeFile(parentFile, "file");
  300. const nested = join(parentFile, "child.json");
  301. const cache = new PluginMaterialCache();
  302. try {
  303. const reader = cache.reader("scope");
  304. vi.mocked(asyncFs.readFile).mockClear();
  305. for (let i = 0; i < 2; i += 1) {
  306. await expect(reader.json(path)).rejects.toMatchObject({ code: "ENOENT" });
  307. await expect(reader.json(nested)).rejects.toMatchObject({ code: "ENOTDIR" });
  308. }
  309. expect(
  310. vi.mocked(asyncFs.readFile).mock.calls.filter(([file]) => file === path || file === nested),
  311. ).toHaveLength(0);
  312. expect(await reader.validate()).toBe(true);
  313. await writeFile(path, '{"created":true}');
  314. expect(await reader.validate()).toBe(false);
  315. expect(await cache.reader("scope").json(path)).toEqual({ created: true });
  316. } finally {
  317. cache.dispose();
  318. await rm(directory, { recursive: true, force: true });
  319. }
  320. });
  321. it("reads component Markdown concurrently with a four-read owner limit and stable name precedence", async () => {
  322. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-parallel-markdown-"));
  323. const root = join(directory, "plugin");
  324. const commandRoot = join(root, "commands");
  325. await mkdir(commandRoot, { recursive: true });
  326. for (let i = 0; i < 8; i += 1)
  327. await writeFile(
  328. join(commandRoot, `${i}.md`),
  329. `---\nname: ${i < 2 ? "duplicate" : `command-${i}`}\ndescription: file-${i}\n---\nbody`,
  330. );
  331. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  332. const first = Promise.withResolvers<void>();
  333. const rest = Promise.withResolvers<void>();
  334. let active = 0;
  335. let peak = 0;
  336. let completed = 0;
  337. vi.mocked(asyncFs.readFile).mockImplementation(async (...args) => {
  338. if (!String(args[0]).startsWith(commandRoot)) return actual.readFile(...args);
  339. active += 1;
  340. peak = Math.max(peak, active);
  341. try {
  342. await (String(args[0]).endsWith("0.md") ? first.promise : rest.promise);
  343. return await actual.readFile(...args);
  344. } finally {
  345. active -= 1;
  346. completed += 1;
  347. }
  348. });
  349. const cache = new PluginMaterialCache();
  350. const reads = ["a", "b"].map((scope) =>
  351. enumeratePluginComponents(root, null, {
  352. loaded: {
  353. id: "parallel@inline",
  354. manifest: { name: "parallel" },
  355. manifestPath: join(root, ".zcode-plugin/plugin.json"),
  356. rootPath: root,
  357. marketplace: "inline",
  358. source: "inline",
  359. materials: cache.reader(scope),
  360. },
  361. }),
  362. );
  363. const done = Promise.all(reads);
  364. try {
  365. await vi.waitFor(() => expect(active).toBe(4));
  366. expect(peak).toBe(4);
  367. rest.resolve();
  368. await vi.waitFor(() => expect(completed).toBeGreaterThan(0));
  369. first.resolve();
  370. const results = await done;
  371. expect(peak).toBe(4);
  372. expect(results[0]).toEqual(results[1]);
  373. expect(results[0].find((group) => group.kind === "command")?.items).toEqual([
  374. { name: "duplicate", description: "file-0" },
  375. ...[2, 3, 4, 5, 6, 7].map((i) => ({ name: `command-${i}`, description: `file-${i}` })),
  376. ]);
  377. } finally {
  378. first.resolve();
  379. rest.resolve();
  380. await Promise.allSettled(reads);
  381. cache.dispose();
  382. vi.mocked(asyncFs.readFile).mockReset();
  383. await rm(directory, { recursive: true, force: true });
  384. }
  385. });
  386. it.each(["invalidate", "dispose"] as const)(
  387. "does not start queued material IO after %s",
  388. async (action) => {
  389. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-read-limit-"));
  390. const paths = Array.from({ length: 9 }, (_, i) => join(directory, `${i}.json`));
  391. for (const path of paths) await writeFile(path, "{}");
  392. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  393. const release = Promise.withResolvers<void>();
  394. let started = 0;
  395. vi.mocked(asyncFs.readFile).mockImplementation(async (...args) => {
  396. if (paths.includes(String(args[0]))) {
  397. started += 1;
  398. await release.promise;
  399. }
  400. return actual.readFile(...args);
  401. });
  402. const cache = new PluginMaterialCache();
  403. const reader = cache.reader("scope");
  404. const done = Promise.allSettled(paths.map((path) => reader.json(path)));
  405. try {
  406. await vi.waitFor(() => expect(started).toBe(4));
  407. cache[action]();
  408. release.resolve();
  409. const results = await done;
  410. expect(started).toBe(4);
  411. for (const result of results) {
  412. expect(result.status).toBe("rejected");
  413. if (result.status === "rejected")
  414. expect(result.reason).toMatchObject(
  415. action === "dispose"
  416. ? { name: "AbortError" }
  417. : { code: "ZCODE_PLUGIN_SOURCES_CHANGED" },
  418. );
  419. }
  420. } finally {
  421. release.resolve();
  422. await done;
  423. cache.dispose();
  424. vi.mocked(asyncFs.readFile).mockReset();
  425. await rm(directory, { recursive: true, force: true });
  426. }
  427. },
  428. );
  429. it("shares concurrent Skill scans without sharing mutable results or link policies", async () => {
  430. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-scan-policy-"));
  431. const root = join(directory, "real");
  432. await mkdir(root);
  433. const file = join(root, "SKILL.md");
  434. await writeFile(file, "# skill");
  435. const link = join(directory, "linked");
  436. await symlink(root, link, process.platform === "win32" ? "junction" : "dir");
  437. const cache = new PluginMaterialCache();
  438. try {
  439. const reader = cache.reader("scope");
  440. vi.mocked(asyncFs.lstat).mockClear();
  441. const [first, second] = await Promise.all([reader.skillFiles(root), reader.skillFiles(root)]);
  442. expect(first).toEqual([file]);
  443. first.length = 0;
  444. expect(second).toEqual([file]);
  445. expect(vi.mocked(asyncFs.lstat).mock.calls.filter(([path]) => path === file)).toHaveLength(1);
  446. expect(await reader.skillFiles(link)).toEqual([]);
  447. expect(await reader.skillFiles(link, true)).toEqual([join(link, "SKILL.md")]);
  448. cache.invalidate();
  449. await expect(reader.skillFiles(root)).rejects.toMatchObject({
  450. code: "ZCODE_PLUGIN_SOURCES_CHANGED",
  451. });
  452. } finally {
  453. cache.dispose();
  454. await rm(directory, { recursive: true, force: true });
  455. }
  456. });
  457. it("releases material read slots after IO and parse failures", async () => {
  458. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-failed-reads-"));
  459. const paths = Array.from({ length: 9 }, (_, i) => join(directory, `${i}.json`));
  460. for (const path of paths) await writeFile(path, path === paths[4] ? "{" : "{}");
  461. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  462. vi.mocked(asyncFs.readFile).mockImplementation(async (...args) => {
  463. if (paths.slice(0, 4).includes(String(args[0])))
  464. throw Object.assign(new Error("denied"), { code: "EACCES" });
  465. return actual.readFile(...args);
  466. });
  467. const cache = new PluginMaterialCache();
  468. try {
  469. const reader = cache.reader("scope");
  470. const results = await Promise.allSettled(paths.map((path) => reader.json(path)));
  471. expect(results.slice(0, 5).map((result) => result.status)).toEqual(Array(5).fill("rejected"));
  472. expect(results.slice(5).map((result) => result.status)).toEqual(Array(4).fill("fulfilled"));
  473. vi.mocked(asyncFs.readFile).mockReset();
  474. await writeFile(paths[4]!, "{}");
  475. expect(await Promise.all(paths.map((path) => cache.reader("scope").json(path)))).toEqual(
  476. paths.map(() => ({})),
  477. );
  478. } finally {
  479. cache.dispose();
  480. vi.mocked(asyncFs.readFile).mockReset();
  481. await rm(directory, { recursive: true, force: true });
  482. }
  483. });
  484. it("reuses parsed materials across sequential queries but reprojects configuration and isolates scopes", async () => {
  485. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-material-reuse-"));
  486. const root = join(directory, "plugin");
  487. const storageRoot = join(directory, "storage");
  488. await writePluginManifest(root, { name: "material-fixture", version: "1.0.0" });
  489. const skillFile = join(root, "skills", "one", "SKILL.md");
  490. await mkdir(join(root, "skills", "one"), { recursive: true });
  491. await writeFile(skillFile, "---\nname: one\ndescription: first\n---\nbody");
  492. const manifestPath = join(root, ".zcode-plugin", "plugin.json");
  493. const sources = new Set([manifestPath, skillFile]);
  494. const sourceReads = () =>
  495. vi
  496. .mocked(asyncFs.readFile)
  497. .mock.calls.filter(([path]) => typeof path === "string" && sources.has(path)).length;
  498. const adapter = createNodePluginAdapter({ storageRoot });
  499. const request = {
  500. storageRoot,
  501. workingDirectory: directory,
  502. workspaceIdentity: "workspace-a",
  503. remoteSessionId: "attachment-a",
  504. config: {
  505. dirs: [root],
  506. enabled: true,
  507. enabledPlugins: {},
  508. options: {},
  509. suppressedBuiltins: [],
  510. },
  511. };
  512. try {
  513. const first = await adapter.discoverPlugins(request);
  514. expect(first.plugins[0]?.name).toBe("material-fixture");
  515. first.plugins[0]!.name = "changed-by-caller";
  516. vi.mocked(asyncFs.readFile).mockClear();
  517. vi.mocked(asyncFs.readdir).mockClear();
  518. const second = await adapter.discoverPlugins({
  519. ...request,
  520. config: { ...request.config, enabledPlugins: { "material-fixture@inline": false } },
  521. });
  522. expect(second.plugins[0]?.name).toBe("material-fixture");
  523. expect(second.plugins[0]?.enabled).toBe(false);
  524. expect(sourceReads()).toBe(0);
  525. await adapter.discoverPlugins(request);
  526. expect(sourceReads()).toBe(0);
  527. expect(
  528. vi.mocked(asyncFs.readdir).mock.calls.filter(([path]) => path === join(root, "skills")),
  529. ).toEqual([]);
  530. await adapter.discoverPlugins({ ...request, workspaceIdentity: "workspace-b" });
  531. expect(sourceReads()).toBeGreaterThan(0);
  532. vi.mocked(asyncFs.readFile).mockClear();
  533. await adapter.discoverPlugins({ ...request, remoteSessionId: "attachment-b" });
  534. expect(sourceReads()).toBeGreaterThan(0);
  535. const before = await asyncFs.stat(manifestPath);
  536. await writePluginManifest(root, { name: "material-fixture", version: "2.0.0" });
  537. await asyncFs.utimes(manifestPath, before.atime, before.mtime);
  538. const refreshed = await adapter.discoverPlugins(request);
  539. expect(refreshed.plugins[0]?.version).toBe("2.0.0");
  540. await mkdir(join(root, "skills", "two"));
  541. await writeFile(join(root, "skills", "two", "SKILL.md"), "---\nname: two\n---\nbody");
  542. expect((await adapter.discoverPlugins(request)).plugins[0]?.skillCount).toBe(2);
  543. } finally {
  544. adapter.dispose();
  545. await rm(directory, { recursive: true, force: true });
  546. }
  547. });
  548. it("parses once and returns independent values while validating current file metadata", async () => {
  549. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-parser-cache-"));
  550. const path = join(directory, "data.json");
  551. const cache = new PluginMaterialCache();
  552. const parse = vi.fn(JSON.parse);
  553. await writeFile(path, '{"value":1}');
  554. try {
  555. const first = await cache.reader("scope").parsed(path, "json", parse);
  556. first.value = 9;
  557. expect(await cache.reader("scope").parsed(path, "json", parse)).toEqual({ value: 1 });
  558. expect(parse).toHaveBeenCalledOnce();
  559. cache.invalidate();
  560. expect(await cache.reader("scope").parsed(path, "json", parse)).toEqual({ value: 1 });
  561. expect(parse).toHaveBeenCalledTimes(2);
  562. const inFlight = cache.reader("scope");
  563. await inFlight.json(path);
  564. await writeFile(path, '{"value":2}');
  565. expect(await inFlight.validate()).toBe(false);
  566. expect(await cache.reader("scope").json(path)).toEqual({ value: 2 });
  567. } finally {
  568. cache.dispose();
  569. await rm(directory, { recursive: true, force: true });
  570. }
  571. });
  572. it("shares a read without letting one cancelled query abort another", async () => {
  573. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-shared-material-"));
  574. const root = join(directory, "plugin");
  575. await writePluginManifest(root, { name: "shared", version: "1.0.0" });
  576. const manifestPath = join(root, ".zcode-plugin", "plugin.json");
  577. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  578. const entered = Promise.withResolvers<void>();
  579. const release = Promise.withResolvers<void>();
  580. let reads = 0;
  581. vi.mocked(asyncFs.readFile).mockImplementation(async (...args) => {
  582. const bytes = await actual.readFile(...args);
  583. if (args[0] === manifestPath) {
  584. reads += 1;
  585. entered.resolve();
  586. await release.promise;
  587. }
  588. return bytes;
  589. });
  590. const adapter = createNodePluginAdapter({ storageRoot: join(directory, "storage") });
  591. const request = {
  592. storageRoot: join(directory, "storage"),
  593. workingDirectory: directory,
  594. config: {
  595. dirs: [root],
  596. enabled: true,
  597. enabledPlugins: {},
  598. options: {},
  599. suppressedBuiltins: [],
  600. },
  601. };
  602. const controller = new AbortController();
  603. const first = adapter.discoverPlugins(request, { signal: controller.signal });
  604. const cancelled = expect(first).rejects.toMatchObject({ name: "AbortError" });
  605. await entered.promise;
  606. const second = adapter.discoverPlugins(request);
  607. try {
  608. controller.abort();
  609. await cancelled;
  610. release.resolve();
  611. expect((await second).plugins[0]?.name).toBe("shared");
  612. expect(reads).toBe(1);
  613. } finally {
  614. release.resolve();
  615. await Promise.allSettled([first, second]);
  616. adapter.dispose();
  617. vi.mocked(asyncFs.readFile).mockReset();
  618. await rm(directory, { recursive: true, force: true });
  619. }
  620. });
  621. it("discards material read before a source change and rejects new queries after dispose", async () => {
  622. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-stale-material-"));
  623. const root = join(directory, "plugin");
  624. await writePluginManifest(root, { name: "changing", version: "1.0.0" });
  625. const manifestPath = join(root, ".zcode-plugin", "plugin.json");
  626. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  627. const entered = Promise.withResolvers<void>();
  628. const release = Promise.withResolvers<void>();
  629. let firstRead = true;
  630. vi.mocked(asyncFs.readFile).mockImplementation(async (...args) => {
  631. const bytes = await actual.readFile(...args);
  632. if (args[0] === manifestPath && firstRead) {
  633. firstRead = false;
  634. entered.resolve();
  635. await release.promise;
  636. }
  637. return bytes;
  638. });
  639. const adapter = createNodePluginAdapter({ storageRoot: join(directory, "storage") });
  640. const request = {
  641. storageRoot: join(directory, "storage"),
  642. workingDirectory: directory,
  643. config: {
  644. dirs: [root],
  645. enabled: true,
  646. enabledPlugins: {},
  647. options: {},
  648. suppressedBuiltins: [],
  649. },
  650. };
  651. const pending = adapter.discoverPlugins(request);
  652. try {
  653. await entered.promise;
  654. await writePluginManifest(root, { name: "changing", version: "2.0.0" });
  655. release.resolve();
  656. expect((await pending).plugins[0]?.version).toBe("2.0.0");
  657. adapter.dispose();
  658. await expect(adapter.discoverPlugins(request)).rejects.toMatchObject({ name: "AbortError" });
  659. } finally {
  660. release.resolve();
  661. await Promise.allSettled([pending]);
  662. adapter.dispose();
  663. vi.mocked(asyncFs.readFile).mockReset();
  664. await rm(directory, { recursive: true, force: true });
  665. }
  666. });
  667. it.each(["dispose", "invalidate"] as const)(
  668. "bounds in-flight %s without publishing a stale result",
  669. async (action) => {
  670. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-owner-change-"));
  671. const root = join(directory, "plugin");
  672. await writePluginManifest(root, { name: "changing", version: "1.0.0" });
  673. const manifestPath = join(root, ".zcode-plugin", "plugin.json");
  674. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  675. const adapter = createNodePluginAdapter({ storageRoot: join(directory, "storage") });
  676. let reads = 0;
  677. vi.mocked(asyncFs.readFile).mockImplementation(async (...args) => {
  678. const bytes = await actual.readFile(...args);
  679. if (args[0] === manifestPath) {
  680. reads += 1;
  681. adapter[action]();
  682. }
  683. return bytes;
  684. });
  685. try {
  686. await expect(
  687. adapter.discoverPlugins({
  688. storageRoot: join(directory, "storage"),
  689. workingDirectory: directory,
  690. config: {
  691. dirs: [root],
  692. enabled: true,
  693. enabledPlugins: {},
  694. options: {},
  695. suppressedBuiltins: [],
  696. },
  697. }),
  698. ).rejects.toMatchObject(
  699. action === "dispose" ? { name: "AbortError" } : { code: "ZCODE_PLUGIN_SOURCES_CHANGED" },
  700. );
  701. expect(reads).toBe(action === "dispose" ? 1 : 3);
  702. } finally {
  703. adapter.dispose();
  704. vi.mocked(asyncFs.readFile).mockReset();
  705. await rm(directory, { recursive: true, force: true });
  706. }
  707. },
  708. );
  709. it("does not retain parse failures or materials above its byte budget", async () => {
  710. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-material-budget-"));
  711. const path = join(directory, "source.json");
  712. const cache = new PluginMaterialCache();
  713. try {
  714. await writeFile(path, "{");
  715. await expect(cache.reader("scope").json(path)).rejects.toBeInstanceOf(SyntaxError);
  716. await writeFile(path, '{"ready":true}');
  717. expect(await cache.reader("scope").json(path)).toEqual({ ready: true });
  718. await writeFile(path, "x".repeat(4 * 1024 * 1024 + 1));
  719. const parse = vi.fn((contents: string) => contents.length);
  720. await cache.reader("scope").parsed(path, "text", parse);
  721. await cache.reader("scope").parsed(path, "text", parse);
  722. expect(parse).toHaveBeenCalledTimes(2);
  723. } finally {
  724. cache.dispose();
  725. await rm(directory, { recursive: true, force: true });
  726. }
  727. });
  728. it("waits for asynchronous manifest IO while unrelated work can run and avoids rewriting commands", async () => {
  729. const directory = await mkdtemp(join(tmpdir(), "zcode-plugin-async-discovery-"));
  730. const root = join(directory, "plugin");
  731. await writePluginManifest(root, {
  732. name: "async-fixture",
  733. version: "1.0.0",
  734. commands: { probe: { content: "# probe" } },
  735. });
  736. const manifestPath = join(root, ".zcode-plugin", "plugin.json");
  737. const entered = Promise.withResolvers<void>();
  738. const release = Promise.withResolvers<void>();
  739. const originalRead = (
  740. await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises")
  741. ).readFile;
  742. let intercepted = false;
  743. const read = vi.spyOn(asyncFs, "readFile").mockImplementation(async (...args) => {
  744. if (args[0] === manifestPath) {
  745. intercepted = true;
  746. entered.resolve();
  747. await release.promise;
  748. }
  749. return originalRead(...args);
  750. });
  751. const request = {
  752. config: {
  753. dirs: [root],
  754. enabled: true,
  755. enabledPlugins: {},
  756. options: {},
  757. suppressedBuiltins: [],
  758. },
  759. storageRoot: join(directory, "storage"),
  760. workingDirectory: directory,
  761. };
  762. let settled = false;
  763. const pending = discoverNodePlugins(request).finally(() => {
  764. settled = true;
  765. });
  766. try {
  767. await Promise.race([entered.promise, pending]);
  768. expect(intercepted).toBe(true);
  769. await new Promise<void>((resolve) => setImmediate(resolve));
  770. expect(settled).toBe(false);
  771. release.resolve();
  772. const outcome = await pending;
  773. expect(outcome.plugins.map((plugin) => plugin.name)).toEqual(["async-fixture"]);
  774. const commandPath = join(outcome.commandRoots[0]!.path, "probe.md");
  775. const first = await asyncFs.stat(commandPath, { bigint: true });
  776. await discoverNodePlugins(request);
  777. const second = await asyncFs.stat(commandPath, { bigint: true });
  778. expect([second.ino, second.mtimeNs]).toEqual([first.ino, first.mtimeNs]);
  779. } finally {
  780. release.resolve();
  781. await pending;
  782. read.mockRestore();
  783. await rm(directory, { recursive: true, force: true });
  784. }
  785. });
  786. it("retains the first discovered agent source and rejects paths outside the plugin", async () => {
  787. const temporaryRoot = await mkdtemp(join(tmpdir(), "zcode-agent-component-source-"));
  788. const root = join(temporaryRoot, "plugin");
  789. try {
  790. for (const directory of ["agents", "custom", "absolute"])
  791. await mkdir(join(root, directory), { recursive: true });
  792. const outside = join(temporaryRoot, "outside");
  793. await mkdir(outside);
  794. for (const directory of [outside, join(root, "absolute")]) {
  795. await writeFile(
  796. join(directory, "forbidden.md"),
  797. "---\nname: forbidden\ndescription: Must not load\n---\nForbidden prompt",
  798. );
  799. }
  800. await writeFile(
  801. join(root, "agents", "first.md"),
  802. "---\nname: reviewer\ndescription: Default\n---\nDefault prompt",
  803. );
  804. await writeFile(
  805. join(root, "custom", "duplicate.md"),
  806. "---\nname: reviewer\ndescription: Custom\n---\nCustom prompt",
  807. );
  808. await writeFile(
  809. join(root, "custom", "other.md"),
  810. "---\nname: researcher\ndescription: Research\n---\nResearch prompt",
  811. );
  812. const groups = await enumeratePluginComponents(root, {
  813. name: "fixture",
  814. agents: ["custom", "agents", "custom", "../outside", join(root, "absolute")],
  815. });
  816. expect(groups.find((group) => group.kind === "agent")?.items).toEqual([
  817. { name: "reviewer", description: "Default", path: join(root, "agents", "first.md") },
  818. { name: "researcher", description: "Research", path: join(root, "custom", "other.md") },
  819. ]);
  820. expect(
  821. (
  822. await enumeratePluginComponents(root, {
  823. name: "fixture",
  824. agents: { reviewer: { description: "Declared" } },
  825. })
  826. ).find((group) => group.kind === "agent")?.items,
  827. ).toEqual([{ name: "reviewer", description: "Declared" }]);
  828. } finally {
  829. await rm(temporaryRoot, { force: true, recursive: true });
  830. }
  831. });
  832. afterEach(() => {
  833. vi.unstubAllEnvs();
  834. vi.unstubAllGlobals();
  835. });
  836. it("validates icon source records and only fills missing Claude marketplace icons", () => {
  837. const icons = parsePluginIconSources([
  838. { name: "figma", icon: "figma/icon.png", mimeType: "image/png", sha256: "a".repeat(64) },
  839. { name: "unsafe", icon: "../unsafe.png", mimeType: "image/png" },
  840. { name: "svg", icon: "svg/icon.svg", mimeType: "image/svg+xml" },
  841. ]);
  842. expect(icons.get("figma")).toBe(
  843. "https://cdn-zcode.z.ai/zcode/official-plugin/assets/figma/icon.png",
  844. );
  845. expect(icons.has("unsafe")).toBe(false);
  846. expect(icons.has("svg")).toBe(false);
  847. const enriched = applyClaudePluginIcons(
  848. {
  849. name: "claude-plugins-official",
  850. plugins: [
  851. { name: "figma", source: "./figma" },
  852. { name: "existing", icon: "https://example.com/existing.png", source: "./existing" },
  853. ],
  854. },
  855. new Map([
  856. ["figma", icons.get("figma")!],
  857. ["existing", "https://cdn.example.com/replacement.png"],
  858. ]),
  859. );
  860. expect(enriched.plugins).toEqual([
  861. {
  862. name: "figma",
  863. icon: "https://cdn-zcode.z.ai/zcode/official-plugin/assets/figma/icon.png",
  864. source: "./figma",
  865. },
  866. { name: "existing", icon: "https://example.com/existing.png", source: "./existing" },
  867. ]);
  868. });
  869. it("only classifies canonical public GitHub HTTPS repository URLs for Archive download", () => {
  870. expect(parsePublicGitHubRepositoryUrl("https://github.com/acme/plugins.git")).toEqual({
  871. owner: "acme",
  872. repo: "plugins",
  873. });
  874. expect(parsePublicGitHubRepositoryUrl("http://github.com/acme/plugins.git")).toBeNull();
  875. expect(parsePublicGitHubRepositoryUrl("https://token@github.com/acme/plugins.git")).toBeNull();
  876. expect(parsePublicGitHubRepositoryUrl("https://github.com/acme/plugins/tree/main")).toBeNull();
  877. expect(buildGitHubArchiveUrl({ owner: "acme", repo: "plugins" }, "feature/no-git")).toBe(
  878. "https://api.github.com/repos/acme/plugins/zipball/feature%2Fno-git",
  879. );
  880. });
  881. it("follows marketplace redirects through the configured system proxy without leaking headers", async () => {
  882. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-proxy-"));
  883. const storageRoot = join(dir, "storage");
  884. const proxyRequests: Array<{ token: string | undefined; url: string }> = [];
  885. const proxy = createServer((request, response) => {
  886. const url = request.url ?? "";
  887. proxyRequests.push({
  888. token: request.headers["x-marketplace-token"],
  889. url,
  890. });
  891. if (url === "http://marketplace.test/marketplace.json") {
  892. response.writeHead(302, {
  893. location: "http://cdn.test/marketplace-redirect.json",
  894. });
  895. response.end();
  896. return;
  897. }
  898. if (url === "http://cdn.test/marketplace-redirect.json") {
  899. response.writeHead(307, {
  900. location: "http://cdn.test/marketplace.json",
  901. });
  902. response.end();
  903. return;
  904. }
  905. response.setHeader("content-type", "application/json");
  906. response.end(
  907. JSON.stringify({
  908. name: "proxy-market",
  909. plugins: [{ name: "proxied", source: "./proxied" }],
  910. }),
  911. );
  912. });
  913. try {
  914. await writeKnownMarketplaces(storageRoot, [
  915. {
  916. id: "proxy-market",
  917. source: {
  918. source: "url",
  919. url: "http://marketplace.test/marketplace.json",
  920. headers: { "x-marketplace-token": "marketplace-secret" },
  921. },
  922. name: "proxy-market",
  923. addedAt: "2026-01-01T00:00:00.000Z",
  924. pluginCount: 0,
  925. },
  926. ]);
  927. vi.stubEnv("ZCODE_HTTP_PROXY", "");
  928. vi.stubEnv(
  929. ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY,
  930. JSON.stringify({ HTTP_PROXY: await listenServer(proxy) }),
  931. );
  932. const updated = await updateMarketplace({
  933. marketplace: "proxy-market",
  934. storageRoot,
  935. });
  936. expect(updated.map((record) => record.id)).toEqual(["proxy-market"]);
  937. expect(proxyRequests).toEqual([
  938. {
  939. token: "marketplace-secret",
  940. url: "http://marketplace.test/marketplace.json",
  941. },
  942. {
  943. token: undefined,
  944. url: "http://cdn.test/marketplace-redirect.json",
  945. },
  946. {
  947. token: undefined,
  948. url: "http://cdn.test/marketplace.json",
  949. },
  950. ]);
  951. expect(loadMarketplaceManifestSync(storageRoot, "proxy-market")?.plugins[0]?.name).toBe(
  952. "proxied",
  953. );
  954. } finally {
  955. await new Promise<void>((resolve, reject) =>
  956. proxy.close((error) => (error ? reject(error) : resolve())),
  957. );
  958. await rm(dir, { force: true, recursive: true });
  959. }
  960. });
  961. it("fetches and persists optional icons while refreshing the Claude official marketplace", async () => {
  962. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-claude-icons-"));
  963. const storageRoot = join(dir, "storage");
  964. const sourceDir = join(dir, "claude-marketplace");
  965. try {
  966. await writeMarketplaceManifest(sourceDir, {
  967. name: "claude-plugins-official",
  968. plugins: [{ name: "figma", source: "./figma" }],
  969. });
  970. await writeKnownMarketplaces(storageRoot, [
  971. {
  972. id: "zcode-plugins-official",
  973. source: {
  974. source: "settings",
  975. marketplace: {
  976. name: "zcode-plugins-official",
  977. plugins: [],
  978. raw: { name: "zcode-plugins-official", plugins: [] },
  979. },
  980. },
  981. name: "zcode-plugins-official",
  982. addedAt: "2026-01-01T00:00:00.000Z",
  983. pluginCount: 0,
  984. },
  985. {
  986. id: "claude-plugins-official",
  987. source: {
  988. source: "settings",
  989. marketplace: {
  990. name: "claude-plugins-official",
  991. plugins: [],
  992. raw: { name: "claude-plugins-official", plugins: [] },
  993. },
  994. },
  995. name: "claude-plugins-official",
  996. addedAt: "2026-01-01T00:00:00.000Z",
  997. pluginCount: 0,
  998. },
  999. {
  1000. id: "claude-plugins-official",
  1001. source: { source: "directory", path: sourceDir },
  1002. name: "claude-plugins-official",
  1003. addedAt: "2026-01-01T00:00:00.000Z",
  1004. pluginCount: 1,
  1005. },
  1006. ]);
  1007. vi.stubGlobal(
  1008. "fetch",
  1009. vi
  1010. .fn()
  1011. .mockResolvedValue(
  1012. new Response(
  1013. JSON.stringify([{ name: "figma", icon: "figma/icon.png", mimeType: "image/png" }]),
  1014. { status: 200 },
  1015. ),
  1016. ),
  1017. );
  1018. await updateMarketplace({ marketplace: "claude-plugins-official", storageRoot });
  1019. expect(
  1020. loadMarketplaceManifestSync(storageRoot, "claude-plugins-official")?.raw,
  1021. ).toMatchObject({
  1022. plugins: [
  1023. {
  1024. name: "figma",
  1025. icon: "https://cdn-zcode.z.ai/zcode/official-plugin/assets/figma/icon.png",
  1026. },
  1027. ],
  1028. });
  1029. const cached = JSON.parse(
  1030. await readFile(join(storageRoot, "icon-sources.json"), "utf8"),
  1031. ) as unknown;
  1032. expect(cached).toEqual([{ name: "figma", icon: "figma/icon.png", mimeType: "image/png" }]);
  1033. } finally {
  1034. await rm(dir, { force: true, recursive: true });
  1035. }
  1036. });
  1037. it("enriches an existing Claude catalog without refreshing its marketplace", async () => {
  1038. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-existing-claude-icons-"));
  1039. const storageRoot = join(dir, "storage");
  1040. const marketplaceRoot = join(storageRoot, "marketplaces", "claude-plugins-official");
  1041. try {
  1042. await mkdir(marketplaceRoot, { recursive: true });
  1043. await writeFile(
  1044. join(marketplaceRoot, "marketplace.json"),
  1045. JSON.stringify({
  1046. name: "claude-plugins-official",
  1047. plugins: [{ name: "figma", source: "./figma" }],
  1048. }),
  1049. );
  1050. await writeKnownMarketplaces(storageRoot, [
  1051. {
  1052. id: "claude-plugins-official",
  1053. source: { source: "github", repo: "anthropics/claude-plugins-official" },
  1054. name: "claude-plugins-official",
  1055. addedAt: "2026-01-01T00:00:00.000Z",
  1056. lastUpdated: "2026-01-02T00:00:00.000Z",
  1057. pluginCount: 1,
  1058. },
  1059. ]);
  1060. let resolveFetch!: (response: Response) => void;
  1061. const fetchMock = vi.fn(
  1062. () =>
  1063. new Promise<Response>((resolve) => {
  1064. resolveFetch = resolve;
  1065. }),
  1066. );
  1067. vi.stubGlobal("fetch", fetchMock);
  1068. let writeLockCalls = 0;
  1069. const migration = enrichCachedClaudeMarketplaceIcons(storageRoot, async (write) => {
  1070. writeLockCalls += 1;
  1071. await write();
  1072. });
  1073. await Promise.resolve();
  1074. expect(writeLockCalls).toBe(0);
  1075. resolveFetch(
  1076. new Response(
  1077. JSON.stringify([{ name: "figma", icon: "figma/icon.png", mimeType: "image/png" }]),
  1078. { status: 200 },
  1079. ),
  1080. );
  1081. await migration;
  1082. await enrichCachedClaudeMarketplaceIcons(storageRoot);
  1083. expect(fetchMock).toHaveBeenCalledTimes(1);
  1084. expect(writeLockCalls).toBe(1);
  1085. expect(
  1086. loadMarketplaceManifestSync(storageRoot, "claude-plugins-official")?.raw,
  1087. ).toMatchObject({
  1088. plugins: [
  1089. {
  1090. name: "figma",
  1091. icon: "https://cdn-zcode.z.ai/zcode/official-plugin/assets/figma/icon.png",
  1092. },
  1093. ],
  1094. });
  1095. expect(
  1096. JSON.parse(await readFile(join(storageRoot, "known_marketplaces.json"), "utf8")),
  1097. ).toMatchObject({
  1098. marketplaces: [{ lastUpdated: "2026-01-02T00:00:00.000Z" }],
  1099. });
  1100. } finally {
  1101. await rm(dir, { force: true, recursive: true });
  1102. }
  1103. });
  1104. it("uses the cached icon mapping when the optional CDN request fails", async () => {
  1105. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-cached-claude-icons-"));
  1106. const storageRoot = join(dir, "storage");
  1107. const sourceDir = join(dir, "claude-marketplace");
  1108. try {
  1109. await writeMarketplaceManifest(sourceDir, {
  1110. name: "claude-plugins-official",
  1111. plugins: [{ name: "figma", source: "./figma" }],
  1112. });
  1113. await mkdir(storageRoot, { recursive: true });
  1114. await writeFile(
  1115. join(storageRoot, "icon-sources.json"),
  1116. JSON.stringify([{ name: "figma", icon: "figma/icon.png", mimeType: "image/png" }]),
  1117. );
  1118. await writeKnownMarketplaces(storageRoot, [
  1119. {
  1120. id: "claude-plugins-official",
  1121. source: { source: "directory", path: sourceDir },
  1122. name: "claude-plugins-official",
  1123. addedAt: "2026-01-01T00:00:00.000Z",
  1124. pluginCount: 1,
  1125. },
  1126. ]);
  1127. vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline")));
  1128. await updateMarketplace({ marketplace: "claude-plugins-official", storageRoot });
  1129. expect(
  1130. loadMarketplaceManifestSync(storageRoot, "claude-plugins-official")?.raw,
  1131. ).toMatchObject({
  1132. plugins: [
  1133. {
  1134. name: "figma",
  1135. icon: "https://cdn-zcode.z.ai/zcode/official-plugin/assets/figma/icon.png",
  1136. },
  1137. ],
  1138. });
  1139. } finally {
  1140. await rm(dir, { force: true, recursive: true });
  1141. }
  1142. });
  1143. it("injects explicit ZCode proxy env into marketplace Git commands", () => {
  1144. const env = buildMarketplaceGitEnv({
  1145. [ZCODE_AGENT_CA_CERT_ENV_KEY]: "/tmp/root-ca.pem",
  1146. [ZCODE_HTTP_PROXY_ENV_KEY]: "127.0.0.1:7890",
  1147. [ZCODE_NO_PROXY_ENV_KEY]: "localhost,127.0.0.1",
  1148. PATH: "/usr/bin:/bin",
  1149. http_proxy: "http://ambient-proxy:8080",
  1150. });
  1151. expect(env).toMatchObject({
  1152. ALL_PROXY: "http://127.0.0.1:7890",
  1153. CURL_CA_BUNDLE: "/tmp/root-ca.pem",
  1154. GIT_SSL_CAINFO: "/tmp/root-ca.pem",
  1155. HTTPS_PROXY: "http://127.0.0.1:7890",
  1156. HTTP_PROXY: "http://127.0.0.1:7890",
  1157. NODE_EXTRA_CA_CERTS: "/tmp/root-ca.pem",
  1158. NO_PROXY: "localhost,127.0.0.1",
  1159. PATH: "/usr/bin:/bin",
  1160. REQUESTS_CA_BUNDLE: "/tmp/root-ca.pem",
  1161. SSL_CERT_FILE: "/tmp/root-ca.pem",
  1162. all_proxy: "http://127.0.0.1:7890",
  1163. http_proxy: "http://127.0.0.1:7890",
  1164. https_proxy: "http://127.0.0.1:7890",
  1165. no_proxy: "localhost,127.0.0.1",
  1166. });
  1167. });
  1168. // Finding #4 (defense-in-depth): the lowest-level discovery adapter must drop official
  1169. // candidates whose id is in config.suppressedBuiltins, even when their cache dirs still
  1170. // exist on disk. scanOfficialCache walks EVERY version dir, so a stale old-version dir left
  1171. // by an app upgrade (seeding only deletes the current version's targetRoot) used to
  1172. // re-surface an uninstalled built-in. Suppression must not depend on physical deletion.
  1173. it("suppresses official plugins from discovery even when stale cache version dirs exist", async () => {
  1174. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-suppress-official-cache-"));
  1175. const storageRoot = join(dir, "storage");
  1176. const officialCacheRoot = join(storageRoot, "cache", "zcode-plugins-official");
  1177. try {
  1178. // Suppressed built-in seeded at TWO versions (mirrors an upgrade that left an old dir).
  1179. for (const version of ["0.1.0", "0.2.0"]) {
  1180. await writePluginManifest(join(officialCacheRoot, "skill-creator", version), {
  1181. name: "skill-creator",
  1182. version,
  1183. });
  1184. }
  1185. // A different, NON-suppressed official built-in in the same cache must still appear.
  1186. await writePluginManifest(join(officialCacheRoot, "document-skills", "0.1.0"), {
  1187. name: "document-skills",
  1188. version: "0.1.0",
  1189. });
  1190. const outcome = await discoverNodePlugins({
  1191. config: {
  1192. dirs: [],
  1193. enabled: true,
  1194. enabledPlugins: {},
  1195. options: {},
  1196. suppressedBuiltins: ["skill-creator@zcode-plugins-official"],
  1197. },
  1198. env: {},
  1199. storageRoot,
  1200. workingDirectory: join(dir, "workspace"),
  1201. });
  1202. expect(
  1203. outcome.plugins.find((plugin) => plugin.id === "skill-creator@zcode-plugins-official"),
  1204. ).toBeUndefined();
  1205. expect(
  1206. outcome.plugins.find((plugin) => plugin.id === "document-skills@zcode-plugins-official"),
  1207. ).toMatchObject({ source: "official" });
  1208. } finally {
  1209. await rm(dir, { force: true, recursive: true });
  1210. }
  1211. });
  1212. it("prefers the official marketplace cache path when stale plugin versions coexist", async () => {
  1213. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-current-official-cache-"));
  1214. const storageRoot = join(dir, "storage");
  1215. const pluginRoot = join(storageRoot, "cache", "zcode-plugins-official", "browser-use");
  1216. const staleRoot = join(pluginRoot, "0.2.1");
  1217. const currentRoot = join(pluginRoot, "0.4.1");
  1218. try {
  1219. // 真实升级现场会保留旧目录,bundled partition 必须继续只认当前发布版本。
  1220. await writePluginManifest(staleRoot, {
  1221. name: "browser-use",
  1222. version: "0.2.1",
  1223. });
  1224. await writePluginManifest(currentRoot, {
  1225. name: "browser-use",
  1226. version: "0.4.1",
  1227. });
  1228. await writeBundledOfficialMarketplacePartition({
  1229. manifest: {
  1230. name: "zcode-plugins-official",
  1231. plugins: [
  1232. {
  1233. cachePath: currentRoot,
  1234. name: "browser-use",
  1235. source: "filesystem",
  1236. version: "0.4.1",
  1237. },
  1238. ],
  1239. },
  1240. storageRoot,
  1241. });
  1242. const outcome = await discoverNodePlugins({
  1243. config: {
  1244. dirs: [],
  1245. enabled: true,
  1246. enabledPlugins: {},
  1247. options: {},
  1248. suppressedBuiltins: [],
  1249. },
  1250. env: {},
  1251. storageRoot,
  1252. workingDirectory: join(dir, "workspace"),
  1253. });
  1254. expect(
  1255. outcome.plugins.find((plugin) => plugin.id === "browser-use@zcode-plugins-official"),
  1256. ).toMatchObject({
  1257. rootPath: currentRoot,
  1258. version: "0.4.1",
  1259. });
  1260. expect(
  1261. outcome.diagnostics.filter(
  1262. (diagnostic) =>
  1263. diagnostic.code === "plugin_duplicate_id" &&
  1264. diagnostic.pluginId === "browser-use@zcode-plugins-official",
  1265. ),
  1266. ).toHaveLength(0);
  1267. } finally {
  1268. await rm(dir, { force: true, recursive: true });
  1269. }
  1270. });
  1271. // Guard: suppression only targets official candidates. An inline/cache plugin whose id
  1272. // collides with a suppressed string must NOT be dropped.
  1273. it("does not suppress inline plugins that share a suppressed built-in's name", async () => {
  1274. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-suppress-inline-guard-"));
  1275. const pluginRoot = join(dir, "skill-creator-inline");
  1276. try {
  1277. await writePluginManifest(pluginRoot, { name: "skill-creator" });
  1278. const outcome = await discoverNodePlugins({
  1279. config: {
  1280. dirs: [pluginRoot],
  1281. enabled: true,
  1282. enabledPlugins: {},
  1283. options: {},
  1284. // Same bare name, but the inline id is skill-creator@inline — different from the
  1285. // official id, so the inline plugin must survive.
  1286. suppressedBuiltins: ["skill-creator@zcode-plugins-official", "skill-creator@inline"],
  1287. },
  1288. env: {},
  1289. storageRoot: join(dir, "storage"),
  1290. workingDirectory: join(dir, "workspace"),
  1291. });
  1292. expect(outcome.plugins.find((plugin) => plugin.id === "skill-creator@inline")).toMatchObject({
  1293. source: "inline",
  1294. });
  1295. } finally {
  1296. await rm(dir, { force: true, recursive: true });
  1297. }
  1298. });
  1299. it("rejects an untrusted marketplace that impersonates an official id", async () => {
  1300. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-official-impersonate-"));
  1301. const storageRoot = join(dir, "storage");
  1302. try {
  1303. // Both reserved ids must be protected via the untrusted (user-facing) path.
  1304. // claude-plugins-official is a DEFAULT marketplace (always seeded as "known"),
  1305. // so a known-state heuristic would never fire for it — the explicit trusted
  1306. // flag is what closes that hole.
  1307. for (const reservedId of ["zcode-plugins-official", "claude-plugins-official"]) {
  1308. const sourceDir = join(dir, `evil-${reservedId}`);
  1309. await writeMarketplaceManifest(sourceDir, { name: reservedId, plugins: [] });
  1310. await expect(
  1311. addMarketplace({ source: { source: "directory", path: sourceDir }, storageRoot }),
  1312. ).rejects.toThrow(/official marketplace/i);
  1313. }
  1314. } finally {
  1315. await rm(dir, { force: true, recursive: true });
  1316. }
  1317. });
  1318. it("does not clobber the local official manifest dir when rejecting an impersonator", async () => {
  1319. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-official-clobber-"));
  1320. const storageRoot = join(dir, "storage");
  1321. const sourceDir = join(dir, "evil");
  1322. try {
  1323. // Seed an existing local claude-plugins-official manifest dir with a sentinel.
  1324. const officialDir = join(storageRoot, "marketplaces", "claude-plugins-official");
  1325. await mkdir(officialDir, { recursive: true });
  1326. await writeFile(
  1327. join(officialDir, "marketplace.json"),
  1328. JSON.stringify({ name: "claude-plugins-official", plugins: [] }),
  1329. );
  1330. await writeFile(join(officialDir, "SENTINEL"), "real-official");
  1331. // Attacker source whose manifest impersonates the official id.
  1332. await writeMarketplaceManifest(sourceDir, { name: "claude-plugins-official", plugins: [] });
  1333. await expect(
  1334. addMarketplace({ source: { source: "directory", path: sourceDir }, storageRoot }),
  1335. ).rejects.toThrow(/official marketplace/i);
  1336. // The guard must run BEFORE persistence: the original dir + sentinel survive intact.
  1337. expect(await readFile(join(officialDir, "SENTINEL"), "utf8")).toBe("real-official");
  1338. } finally {
  1339. await rm(dir, { force: true, recursive: true });
  1340. }
  1341. });
  1342. // Review #2: a trusted refresh must NOT let a non-official known marketplace claim an official
  1343. // id by renaming its manifest. trustedId pins the refresh to the record's own id, so an
  1344. // official name coming from a record whose id is not that official id is rejected.
  1345. it("records a failed trusted refresh when a non-official manifest renames to an official id", async () => {
  1346. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-official-rename-attack-"));
  1347. const storageRoot = join(dir, "storage");
  1348. const sourceDir = join(dir, "evil-source");
  1349. try {
  1350. // A user-added marketplace "evil" becomes known.
  1351. await writeMarketplaceManifest(sourceDir, { name: "evil", plugins: [] });
  1352. await writeKnownMarketplaces(storageRoot, [
  1353. {
  1354. id: "evil",
  1355. source: { source: "directory", path: sourceDir },
  1356. name: "evil",
  1357. addedAt: "2026-01-01T00:00:00.000Z",
  1358. pluginCount: 0,
  1359. },
  1360. ]);
  1361. // Later the attacker renames the source manifest to impersonate the official id.
  1362. await writeMarketplaceManifest(sourceDir, { name: "claude-plugins-official", plugins: [] });
  1363. // The trusted internal refresh must reject the official-id claim without aborting the
  1364. // refresh envelope; the durable failure is surfaced by overview/protocol diagnostics.
  1365. expect(await updateMarketplace({ marketplace: "evil", storageRoot })).toEqual([]);
  1366. expect(
  1367. loadKnownMarketplacesSync(storageRoot).find((record) => record.id === "evil")
  1368. ?.lastRefreshFailure,
  1369. ).toMatchObject({
  1370. code: "plugin_marketplace_invalid",
  1371. message: expect.stringMatching(/official marketplace/i),
  1372. });
  1373. } finally {
  1374. await rm(dir, { force: true, recursive: true });
  1375. }
  1376. });
  1377. it("seeds Claude official marketplace without overwriting an existing record", async () => {
  1378. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-default-marketplace-"));
  1379. const storageRoot = join(dir, "storage");
  1380. try {
  1381. await writeKnownMarketplaces(storageRoot, [
  1382. {
  1383. id: "claude-plugins-official",
  1384. source: { source: "directory", path: join(dir, "custom-claude") },
  1385. name: "claude-plugins-official",
  1386. description: "Custom Claude mirror",
  1387. addedAt: "2026-01-01T00:00:00.000Z",
  1388. lastUpdated: "2026-01-02T00:00:00.000Z",
  1389. pluginCount: 123,
  1390. },
  1391. ]);
  1392. const known = await ensureDefaultPluginMarketplaces(storageRoot);
  1393. // 默认市场现在有两个:claude-plugins-official(已有记录不被覆盖)+ 唯一 ZCode
  1394. // 官方市场 zcode-plugins-official(缺失时补种)。
  1395. expect(known).toHaveLength(2);
  1396. const claude = known.find((record) => record.id === "claude-plugins-official");
  1397. expect(claude).toMatchObject({
  1398. description: "Custom Claude mirror",
  1399. lastUpdated: "2026-01-02T00:00:00.000Z",
  1400. pluginCount: 123,
  1401. source: { source: "directory", path: join(dir, "custom-claude") },
  1402. });
  1403. expect(
  1404. JSON.parse(await readFile(join(storageRoot, "known_marketplaces.json"), "utf8")),
  1405. ).toMatchObject({
  1406. marketplaces: [
  1407. {
  1408. description: "Custom Claude mirror",
  1409. pluginCount: 123,
  1410. },
  1411. {
  1412. id: "zcode-plugins-official",
  1413. },
  1414. ],
  1415. });
  1416. } finally {
  1417. await rm(dir, { force: true, recursive: true });
  1418. }
  1419. });
  1420. it("lazy-loads a known marketplace manifest before installing", async () => {
  1421. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-known-marketplace-install-"));
  1422. const storageRoot = join(dir, "storage");
  1423. const marketplaceRoot = join(dir, "marketplace");
  1424. const pluginRoot = join(marketplaceRoot, "plugins", "hello");
  1425. try {
  1426. await writeKnownMarketplaces(storageRoot, [
  1427. {
  1428. id: "lazy-market",
  1429. source: { source: "directory", path: marketplaceRoot },
  1430. name: "lazy-market",
  1431. addedAt: "2026-01-01T00:00:00.000Z",
  1432. pluginCount: 0,
  1433. },
  1434. ]);
  1435. await writeMarketplaceManifest(marketplaceRoot, {
  1436. name: "lazy-market",
  1437. plugins: [
  1438. {
  1439. name: "hello",
  1440. source: "./plugins/hello",
  1441. },
  1442. ],
  1443. });
  1444. await writePluginManifest(pluginRoot, { name: "hello", skills: "skills" }, ".claude-plugin");
  1445. await mkdir(join(pluginRoot, "skills", "hello"), { recursive: true });
  1446. await writeFile(join(pluginRoot, "skills", "hello", "SKILL.md"), "# hello");
  1447. const install = await installMarketplacePlugin({
  1448. marketplace: "lazy-market",
  1449. name: "hello",
  1450. storageRoot,
  1451. });
  1452. expect(install.closure).toEqual(["hello@lazy-market"]);
  1453. expect(install.installed[0]?.id).toBe("hello@lazy-market");
  1454. expect(
  1455. JSON.parse(
  1456. await readFile(
  1457. join(storageRoot, "marketplaces", "lazy-market", "marketplace.json"),
  1458. "utf8",
  1459. ),
  1460. ),
  1461. ).toMatchObject({ name: "lazy-market" });
  1462. } finally {
  1463. await rm(dir, { force: true, recursive: true });
  1464. }
  1465. });
  1466. // 扩展摘要只属于目录(docs/plugins/plugin-publishing.md §4.2):没有 plugin.json 的条目合成清单时
  1467. // 必须剔除,否则一份不完整的扩展信息会被当成清单内容。
  1468. it("strips the catalog extension summary when it synthesizes a manifest", async () => {
  1469. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-synth-extension-summary-"));
  1470. const storageRoot = join(dir, "storage");
  1471. const marketplaceRoot = join(dir, "marketplace");
  1472. const pluginRoot = join(marketplaceRoot, "plugins", "ext-entry");
  1473. try {
  1474. await writeKnownMarketplaces(storageRoot, [
  1475. {
  1476. id: "ext-market",
  1477. source: { source: "directory", path: marketplaceRoot },
  1478. name: "ext-market",
  1479. addedAt: "2026-01-01T00:00:00.000Z",
  1480. pluginCount: 0,
  1481. },
  1482. ]);
  1483. await writeMarketplaceManifest(marketplaceRoot, {
  1484. name: "ext-market",
  1485. plugins: [
  1486. {
  1487. name: "ext-entry",
  1488. source: "./plugins/ext-entry",
  1489. strict: false,
  1490. skills: "skills",
  1491. displayName: "Ext Entry",
  1492. componentTypes: ["extension"],
  1493. extensionSummary: { engines: { zcode: "^1.4.0" }, grants: ["sessions.read"] },
  1494. },
  1495. ],
  1496. });
  1497. await mkdir(join(pluginRoot, "skills", "ext-entry"), { recursive: true });
  1498. await writeFile(join(pluginRoot, "skills", "ext-entry", "SKILL.md"), "# ext");
  1499. const install = await installMarketplacePlugin({
  1500. marketplace: "ext-market",
  1501. name: "ext-entry",
  1502. storageRoot,
  1503. });
  1504. const installPath = install.installed[0]?.installPath;
  1505. expect(installPath).toBeDefined();
  1506. const manifest = JSON.parse(
  1507. await readFile(join(installPath!, ".claude-plugin", "plugin.json"), "utf8"),
  1508. ) as Record<string, unknown>;
  1509. expect(manifest).toMatchObject({ name: "ext-entry", skills: "skills" });
  1510. expect(manifest).not.toHaveProperty("extensionSummary");
  1511. expect(manifest).not.toHaveProperty("displayName");
  1512. } finally {
  1513. await rm(dir, { force: true, recursive: true });
  1514. }
  1515. });
  1516. it("loads Claude-compatible local plugin components", async () => {
  1517. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-"));
  1518. const pluginRoot = join(dir, "ios-plugin");
  1519. try {
  1520. await writePluginManifest(pluginRoot, {
  1521. commands: "commands",
  1522. hooks: "hooks/hooks.json",
  1523. name: "ios-dev",
  1524. skills: "skills",
  1525. userConfig: {
  1526. default_device: {
  1527. default: "iPhone 16",
  1528. type: "string",
  1529. },
  1530. },
  1531. });
  1532. await mkdir(join(pluginRoot, "skills", "ios-dev"), { recursive: true });
  1533. await mkdir(join(pluginRoot, "skills", "pdf-dev"), { recursive: true });
  1534. await mkdir(join(pluginRoot, "commands"), { recursive: true });
  1535. await mkdir(join(pluginRoot, "hooks"), { recursive: true });
  1536. await writeFile(join(pluginRoot, "skills", "ios-dev", "SKILL.md"), "# skill");
  1537. await writeFile(join(pluginRoot, "skills", "pdf-dev", "SKILL.md"), "# skill");
  1538. await writeFile(join(pluginRoot, "commands", "ios-dev.md"), "# command");
  1539. await writeFile(
  1540. join(pluginRoot, "hooks", "hooks.json"),
  1541. JSON.stringify({
  1542. hooks: {
  1543. SessionStart: [
  1544. {
  1545. matcher: "startup",
  1546. hooks: [
  1547. {
  1548. type: "command",
  1549. command: '"${CLAUDE_PLUGIN_ROOT}/hooks/session-start"',
  1550. },
  1551. ],
  1552. },
  1553. ],
  1554. },
  1555. }),
  1556. );
  1557. await writeFile(
  1558. join(pluginRoot, ".mcp.json"),
  1559. JSON.stringify({
  1560. mcpServers: {
  1561. "ios-simulator": {
  1562. command: "bun",
  1563. args: ["${CLAUDE_PLUGIN_ROOT}/src/mcp/server.ts"],
  1564. cwd: "${ZCODE_PROJECT_DIR}",
  1565. env: {
  1566. IOS_SIM_DEFAULT_DEVICE: "${user_config.default_device}",
  1567. IOS_SIM_PLUGIN_DATA: "${ZCODE_PLUGIN_DATA}",
  1568. },
  1569. },
  1570. },
  1571. }),
  1572. );
  1573. const outcome = await createNodePluginAdapter({
  1574. storageRoot: join(dir, "plugins"),
  1575. }).discoverPlugins({
  1576. config: {
  1577. dirs: [pluginRoot],
  1578. enabled: true,
  1579. enabledPlugins: {},
  1580. options: {},
  1581. },
  1582. env: {},
  1583. storageRoot: join(dir, "plugins"),
  1584. workingDirectory: join(dir, "workspace"),
  1585. });
  1586. expect(outcome.plugins[0]?.id).toBe("ios-dev@inline");
  1587. expect(outcome.plugins[0]).toMatchObject({
  1588. declaredMcpServerNames: ["ios-simulator"],
  1589. hookDetails: [
  1590. {
  1591. command: '"${CLAUDE_PLUGIN_ROOT}/hooks/session-start"',
  1592. event: "SessionStart",
  1593. matcher: "startup",
  1594. runnable: true,
  1595. sourcePath: join(pluginRoot, "hooks", "hooks.json"),
  1596. type: "command",
  1597. },
  1598. ],
  1599. skillCount: 2,
  1600. skillRootCount: 1,
  1601. });
  1602. expect(outcome.skillRoots[0]?.path).toBe(join(pluginRoot, "skills"));
  1603. expect(outcome.commandRoots[0]?.path).toBe(join(pluginRoot, "commands"));
  1604. const mcpKey = "plugin:ios-dev:ios-simulator";
  1605. expect(outcome.mcpServers[mcpKey]).toMatchObject({
  1606. command: "bun",
  1607. cwd: join(dir, "workspace"),
  1608. type: "stdio",
  1609. });
  1610. expect(outcome.mcpServers[mcpKey]?.env).toMatchObject({
  1611. IOS_SIM_DEFAULT_DEVICE: "iPhone 16",
  1612. });
  1613. expect(outcome.hooks.SessionStart?.[0]?.hooks[0]).toMatchObject({
  1614. command: '"${CLAUDE_PLUGIN_ROOT}/hooks/session-start"',
  1615. plugin: {
  1616. id: "ios-dev@inline",
  1617. rootPath: pluginRoot,
  1618. },
  1619. type: "command",
  1620. });
  1621. const disabledOutcome = await createNodePluginAdapter({
  1622. storageRoot: join(dir, "plugins"),
  1623. }).discoverPlugins({
  1624. config: {
  1625. dirs: [pluginRoot],
  1626. enabled: true,
  1627. enabledPlugins: { "ios-dev@inline": false },
  1628. options: {},
  1629. },
  1630. env: {},
  1631. storageRoot: join(dir, "plugins"),
  1632. workingDirectory: join(dir, "workspace"),
  1633. });
  1634. expect(disabledOutcome.hooks).toEqual({});
  1635. expect(disabledOutcome.plugins[0]).toMatchObject({
  1636. enabled: false,
  1637. hookDetails: [
  1638. {
  1639. event: "SessionStart",
  1640. runnable: true,
  1641. },
  1642. ],
  1643. });
  1644. } finally {
  1645. await rm(dir, { force: true, recursive: true });
  1646. }
  1647. });
  1648. it("loads representative Claude marketplace plugin layouts for skills, commands, and MCP servers", async () => {
  1649. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-triplet-marketplace-"));
  1650. const storageRoot = join(dir, "storage");
  1651. const marketplaceRoot = join(dir, "marketplace");
  1652. const workingDirectory = join(dir, "workspace");
  1653. const cases = claudeMarketplaceTripletFixtures();
  1654. try {
  1655. await mkdir(workingDirectory, { recursive: true });
  1656. await writeMarketplaceManifest(marketplaceRoot, {
  1657. name: "claude-plugins-official",
  1658. plugins: cases.map((fixture) => ({
  1659. name: fixture.name,
  1660. source: `./plugins/${fixture.name}`,
  1661. })),
  1662. });
  1663. for (const fixture of cases) {
  1664. await writeTripletPluginFixture(join(marketplaceRoot, "plugins", fixture.name), fixture);
  1665. }
  1666. // trusted: this fixture legitimately stands up the official catalog from a local dir,
  1667. // mirroring the internal refresh path; the official-id lock only blocks untrusted adds.
  1668. await addMarketplace({
  1669. source: { source: "directory", path: marketplaceRoot },
  1670. storageRoot,
  1671. trustedId: "claude-plugins-official",
  1672. });
  1673. for (const fixture of cases) {
  1674. const install = await installMarketplacePlugin({
  1675. marketplace: "claude-plugins-official",
  1676. name: fixture.name,
  1677. storageRoot,
  1678. });
  1679. expect(install.installed[0]?.id).toBe(`${fixture.name}@claude-plugins-official`);
  1680. }
  1681. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  1682. config: {
  1683. dirs: [],
  1684. enabled: true,
  1685. enabledPlugins: Object.fromEntries(
  1686. cases.map((fixture) => [`${fixture.name}@claude-plugins-official`, true]),
  1687. ),
  1688. options: {},
  1689. },
  1690. env: {},
  1691. storageRoot,
  1692. workingDirectory,
  1693. });
  1694. expect(outcome.diagnostics.filter((diagnostic) => diagnostic.severity === "error")).toEqual(
  1695. [],
  1696. );
  1697. expect(outcome.plugins.filter((plugin) => plugin.enabled)).toHaveLength(cases.length);
  1698. expect(outcome.skillRoots).toHaveLength(cases.length);
  1699. expect(outcome.commandRoots).toHaveLength(cases.length);
  1700. for (const fixture of cases) {
  1701. const plugin = outcome.plugins.find(
  1702. (candidate) => candidate.id === `${fixture.name}@claude-plugins-official`,
  1703. );
  1704. expect(plugin).toMatchObject({
  1705. commandRootCount: 1,
  1706. declaredMcpServerNames: [fixture.mcpServerName],
  1707. enabled: true,
  1708. skillCount: fixture.skillCount,
  1709. skillRootCount: 1,
  1710. });
  1711. // 权威 components 随 list 下发:技能名应齐全且与 skillCount 一致(修复「只有数量没有名称」)。
  1712. const skillNames = componentNames(plugin?.components ?? [], "skill");
  1713. expect(skillNames).toHaveLength(fixture.skillCount);
  1714. expect(skillNames).toContain(`${fixture.name}-skill-1`);
  1715. expect(outcome.mcpServers[`plugin:${fixture.name}:${fixture.mcpServerName}`]).toMatchObject(
  1716. {
  1717. command: "node",
  1718. env: {
  1719. PLUGIN_DATA: expect.stringContaining(`${fixture.name}@claude-plugins-official`),
  1720. PROJECT_DIR: workingDirectory,
  1721. },
  1722. type: "stdio",
  1723. },
  1724. );
  1725. }
  1726. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  1727. roots: outcome.skillRoots,
  1728. workingDirectory,
  1729. });
  1730. const commandOutcome = await createNodeCustomCommandAdapter().discoverCommands({
  1731. roots: outcome.commandRoots,
  1732. workingDirectory,
  1733. });
  1734. expect(skillOutcome.diagnostics).toEqual([]);
  1735. expect(commandOutcome.diagnostics).toEqual([]);
  1736. expect(skillOutcome.skills).toHaveLength(
  1737. cases.reduce((total, fixture) => total + fixture.skillCount, 0),
  1738. );
  1739. expect(commandOutcome.commands).toHaveLength(
  1740. cases.reduce((total, fixture) => total + fixture.commandCount, 0),
  1741. );
  1742. for (const fixture of cases) {
  1743. expect(skillOutcome.skills.map((skill) => skill.name)).toContain(`${fixture.name}-skill-1`);
  1744. expect(commandOutcome.commands.map((command) => command.name)).toContain(
  1745. `${fixture.commandPrefix}:cmd01`,
  1746. );
  1747. }
  1748. } finally {
  1749. await rm(dir, { force: true, recursive: true });
  1750. }
  1751. });
  1752. it("still projects authoritative skill component names for a DISABLED plugin", async () => {
  1753. // 核心回归:停用插件过去走 emptyComponents() 使 skillCount=0,UI join 也拿不到名称,
  1754. // 导致详情弹窗整个技能分组消失。现在 components 由插件根目录权威枚举,与启用态无关。
  1755. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-disabled-components-"));
  1756. const storageRoot = join(dir, "storage");
  1757. const marketplaceRoot = join(dir, "marketplace");
  1758. const workingDirectory = join(dir, "workspace");
  1759. const fixture: TripletPluginFixture = {
  1760. commandCount: 2,
  1761. commandPrefix: "superpowers",
  1762. mcpServerName: "superpowers",
  1763. name: "superpowers",
  1764. skillCount: 14,
  1765. };
  1766. try {
  1767. await mkdir(workingDirectory, { recursive: true });
  1768. await writeMarketplaceManifest(marketplaceRoot, {
  1769. name: "claude-plugins-official",
  1770. plugins: [{ name: fixture.name, source: `./plugins/${fixture.name}` }],
  1771. });
  1772. await writeTripletPluginFixture(join(marketplaceRoot, "plugins", fixture.name), fixture);
  1773. await addMarketplace({
  1774. source: { source: "directory", path: marketplaceRoot },
  1775. storageRoot,
  1776. trustedId: "claude-plugins-official",
  1777. });
  1778. await installMarketplacePlugin({
  1779. marketplace: "claude-plugins-official",
  1780. name: fixture.name,
  1781. storageRoot,
  1782. });
  1783. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  1784. config: {
  1785. dirs: [],
  1786. enabled: true,
  1787. // 显式停用该插件。
  1788. enabledPlugins: { "superpowers@claude-plugins-official": false },
  1789. options: {},
  1790. },
  1791. env: {},
  1792. storageRoot,
  1793. workingDirectory,
  1794. });
  1795. const plugin = outcome.plugins.find(
  1796. (candidate) => candidate.id === "superpowers@claude-plugins-official",
  1797. );
  1798. expect(plugin?.enabled).toBe(false);
  1799. // 停用:runtime 不注入技能根(skillCount=0、skillRootCount=0)……
  1800. expect(plugin?.skillCount).toBe(0);
  1801. expect(outcome.skillRoots).toHaveLength(0);
  1802. // ……但 components 仍权威枚举出全部 14 个技能名,详情 UI 才能展示。
  1803. const skillNames = componentNames(plugin?.components ?? [], "skill");
  1804. expect(skillNames).toHaveLength(14);
  1805. expect(skillNames).toContain("superpowers-skill-1");
  1806. } finally {
  1807. await rm(dir, { force: true, recursive: true });
  1808. }
  1809. });
  1810. it("describes a bundled official plugin whose marketplace source is 'filesystem'", async () => {
  1811. // Bugfix 回归:内置 official 插件 seed 时 source 写裸字符串 "filesystem",describe 过去把它
  1812. // 当路径解析后抛错,市场详情页对内置插件枚举不出组件。现在按 cachePath 直接定位缓存目录。
  1813. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-filesystem-describe-"));
  1814. const storageRoot = join(dir, "storage");
  1815. const cacheRoot = join(storageRoot, "cache", "zcode-plugins-official", "superpowers", "5.1.0");
  1816. const marketplaceRoot = join(storageRoot, "marketplaces", "zcode-plugins-official");
  1817. try {
  1818. // 在缓存目录里铺一个含 manifest + 2 个技能的内置插件。
  1819. await writePluginManifest(cacheRoot, {
  1820. name: "superpowers",
  1821. version: "5.1.0",
  1822. skills: "skills",
  1823. });
  1824. for (const skillName of ["brainstorming", "writing-plans"]) {
  1825. const skillDir = join(cacheRoot, "skills", skillName);
  1826. await mkdir(skillDir, { recursive: true });
  1827. await writeFile(
  1828. join(skillDir, "SKILL.md"),
  1829. ["---", `name: ${skillName}`, `description: ${skillName} desc`, "---", "", "# body"].join(
  1830. "\n",
  1831. ),
  1832. );
  1833. }
  1834. // seeded marketplace.json:source 为裸 "filesystem",并带 cachePath(模拟 bundled-plugins 写入)。
  1835. await mkdir(marketplaceRoot, { recursive: true });
  1836. await writeFile(
  1837. join(marketplaceRoot, "marketplace.json"),
  1838. JSON.stringify({
  1839. name: "zcode-plugins-official",
  1840. version: 1,
  1841. plugins: [
  1842. { name: "superpowers", version: "5.1.0", source: "filesystem", cachePath: cacheRoot },
  1843. ],
  1844. }),
  1845. );
  1846. const result = await describeMarketplacePlugin({
  1847. marketplace: "zcode-plugins-official",
  1848. name: "superpowers",
  1849. storageRoot,
  1850. });
  1851. expect(result.diagnostics.filter((d) => d.severity === "error")).toEqual([]);
  1852. expect(componentNames(result.components, "skill").toSorted()).toEqual([
  1853. "brainstorming",
  1854. "writing-plans",
  1855. ]);
  1856. expect(componentDescription(result.components, "skill", "brainstorming")).toBe(
  1857. "brainstorming desc",
  1858. );
  1859. } finally {
  1860. await rm(dir, { force: true, recursive: true });
  1861. }
  1862. });
  1863. it("describes MCP and hook components from loader-compatible convention files", async () => {
  1864. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-describe-components-"));
  1865. const storageRoot = join(dir, "storage");
  1866. const marketplaceRoot = join(dir, "marketplace");
  1867. const pluginRoot = join(marketplaceRoot, "plugins", "airtable");
  1868. try {
  1869. await writeMarketplaceManifest(marketplaceRoot, {
  1870. name: "claude-plugins-official",
  1871. plugins: [
  1872. {
  1873. name: "airtable",
  1874. source: "./plugins/airtable",
  1875. },
  1876. ],
  1877. });
  1878. await writePluginManifest(
  1879. pluginRoot,
  1880. {
  1881. hooks: {
  1882. PreToolUse: [
  1883. {
  1884. hooks: [{ command: "echo pre", type: "command" }],
  1885. },
  1886. ],
  1887. },
  1888. name: "airtable",
  1889. skills: "skills",
  1890. },
  1891. ".claude-plugin",
  1892. );
  1893. await mkdir(join(pluginRoot, "skills", "airtable-overview"), { recursive: true });
  1894. await mkdir(join(pluginRoot, "hooks"), { recursive: true });
  1895. await writeFile(
  1896. join(pluginRoot, "skills", "airtable-overview", "SKILL.md"),
  1897. [
  1898. "---",
  1899. "name: airtable-overview",
  1900. // 用 `>` 折叠块标量覆盖回归:描述应折叠成完整句子,而不是只剩指示符 `>`。
  1901. "description: >",
  1902. " Explains the Airtable data model and how",
  1903. " to query bases from the agent.",
  1904. "---",
  1905. "",
  1906. "# Airtable overview",
  1907. ].join("\n"),
  1908. );
  1909. await writeFile(
  1910. join(pluginRoot, "hooks", "hooks.json"),
  1911. JSON.stringify({
  1912. hooks: {
  1913. Stop: [
  1914. {
  1915. hooks: [{ command: "echo stop", type: "command" }],
  1916. },
  1917. ],
  1918. },
  1919. }),
  1920. );
  1921. await writeFile(
  1922. join(pluginRoot, ".mcp.json"),
  1923. JSON.stringify({
  1924. airtable: {
  1925. type: "http",
  1926. url: "https://mcp.airtable.test/mcp",
  1927. },
  1928. }),
  1929. );
  1930. await addMarketplace({
  1931. source: { source: "directory", path: marketplaceRoot },
  1932. storageRoot,
  1933. trustedId: "claude-plugins-official",
  1934. });
  1935. const sourceDescribe = await describeMarketplacePlugin({
  1936. marketplace: "claude-plugins-official",
  1937. name: "airtable",
  1938. storageRoot,
  1939. });
  1940. expect(componentNames(sourceDescribe.components, "skill")).toEqual(["airtable-overview"]);
  1941. expect(componentDescription(sourceDescribe.components, "skill", "airtable-overview")).toBe(
  1942. "Explains the Airtable data model and how to query bases from the agent.",
  1943. );
  1944. expect(componentNames(sourceDescribe.components, "hook")).toEqual(["Stop", "PreToolUse"]);
  1945. expect(componentNames(sourceDescribe.components, "mcp")).toEqual(["airtable"]);
  1946. await installMarketplacePlugin({
  1947. marketplace: "claude-plugins-official",
  1948. name: "airtable",
  1949. storageRoot,
  1950. });
  1951. const cacheDescribe = await describeMarketplacePlugin({
  1952. marketplace: "claude-plugins-official",
  1953. name: "airtable",
  1954. storageRoot,
  1955. });
  1956. expect(componentNames(cacheDescribe.components, "hook")).toEqual(["Stop", "PreToolUse"]);
  1957. expect(componentNames(cacheDescribe.components, "mcp")).toEqual(["airtable"]);
  1958. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  1959. config: {
  1960. dirs: [],
  1961. enabled: true,
  1962. enabledPlugins: {
  1963. "airtable@claude-plugins-official": true,
  1964. },
  1965. options: {},
  1966. },
  1967. env: {},
  1968. storageRoot,
  1969. workingDirectory: dir,
  1970. });
  1971. expect(componentNames(cacheDescribe.components, "mcp")).toEqual(
  1972. outcome.plugins[0]?.declaredMcpServerNames,
  1973. );
  1974. expect(componentNames(cacheDescribe.components, "hook")).toEqual(
  1975. outcome.plugins[0]?.hookDetails.map((hook) => hook.event),
  1976. );
  1977. } finally {
  1978. await rm(dir, { force: true, recursive: true });
  1979. }
  1980. });
  1981. it("describes valid components when convention MCP config is invalid", async () => {
  1982. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-describe-invalid-mcp-"));
  1983. const storageRoot = join(dir, "storage");
  1984. const marketplaceRoot = join(dir, "marketplace");
  1985. const pluginRoot = join(marketplaceRoot, "plugins", "broken-mcp");
  1986. try {
  1987. await writeMarketplaceManifest(marketplaceRoot, {
  1988. name: "broken-market",
  1989. plugins: [{ name: "broken-mcp", source: "./plugins/broken-mcp" }],
  1990. });
  1991. await writePluginManifest(
  1992. pluginRoot,
  1993. { name: "broken-mcp", skills: "skills" },
  1994. ".claude-plugin",
  1995. );
  1996. await mkdir(join(pluginRoot, "skills", "still-visible"), { recursive: true });
  1997. await writeFile(join(pluginRoot, "skills", "still-visible", "SKILL.md"), "# skill");
  1998. await writeFile(join(pluginRoot, ".mcp.json"), "{not-json");
  1999. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2000. const result = await describeMarketplacePlugin({
  2001. marketplace: "broken-market",
  2002. name: "broken-mcp",
  2003. storageRoot,
  2004. });
  2005. expect(componentNames(result.components, "skill")).toEqual(["still-visible"]);
  2006. expect(componentNames(result.components, "mcp")).toEqual([]);
  2007. expect(result.diagnostics).toContainEqual(
  2008. expect.objectContaining({
  2009. code: "plugin_mcp_read_failed",
  2010. pluginId: "broken-mcp@broken-market",
  2011. }),
  2012. );
  2013. } finally {
  2014. await rm(dir, { force: true, recursive: true });
  2015. }
  2016. });
  2017. it("adds a Claude marketplace directory and installs relative plugin sources", async () => {
  2018. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-"));
  2019. const storageRoot = join(dir, "storage");
  2020. const marketplaceRoot = join(dir, "marketplace");
  2021. const pluginRoot = join(marketplaceRoot, "plugins", "hello");
  2022. const depRoot = join(marketplaceRoot, "plugins", "dep");
  2023. try {
  2024. await writeMarketplaceManifest(marketplaceRoot, {
  2025. name: "third-party",
  2026. plugins: [
  2027. {
  2028. name: "hello",
  2029. version: "1.2.3",
  2030. source: "./plugins/hello",
  2031. dependencies: ["dep"],
  2032. },
  2033. {
  2034. name: "dep",
  2035. version: "0.1.0",
  2036. source: "./plugins/dep",
  2037. },
  2038. ],
  2039. });
  2040. await writePluginManifest(
  2041. pluginRoot,
  2042. {
  2043. mcpServers: {
  2044. local: {
  2045. command: "node",
  2046. args: ["${CLAUDE_PLUGIN_ROOT}/server.js"],
  2047. },
  2048. },
  2049. name: "hello",
  2050. skills: "skills",
  2051. },
  2052. ".claude-plugin",
  2053. );
  2054. await mkdir(join(pluginRoot, "skills", "hello"), { recursive: true });
  2055. await writeFile(join(pluginRoot, "skills", "hello", "SKILL.md"), "# hello");
  2056. await writePluginManifest(depRoot, { name: "dep" }, ".claude-plugin");
  2057. const marketplace = await addMarketplace({
  2058. source: { source: "directory", path: marketplaceRoot },
  2059. storageRoot,
  2060. });
  2061. expect(marketplace.id).toBe("third-party");
  2062. const validation = await validateMarketplacePlugin({
  2063. marketplace: "third-party",
  2064. name: "hello",
  2065. storageRoot,
  2066. });
  2067. expect(validation.filter((item) => item.severity === "error")).toEqual([]);
  2068. const install = await installMarketplacePlugin({
  2069. marketplace: "third-party",
  2070. name: "hello",
  2071. storageRoot,
  2072. });
  2073. expect(install.closure).toEqual(["dep@third-party", "hello@third-party"]);
  2074. expect(listInstalledPluginRecords(storageRoot).map((record) => record.id)).toEqual([
  2075. "dep@third-party",
  2076. "hello@third-party",
  2077. ]);
  2078. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  2079. config: {
  2080. dirs: [],
  2081. enabled: true,
  2082. enabledPlugins: {
  2083. "hello@third-party": true,
  2084. },
  2085. options: {},
  2086. },
  2087. env: {},
  2088. storageRoot,
  2089. workingDirectory: dir,
  2090. });
  2091. expect(outcome.plugins.find((plugin) => plugin.id === "hello@third-party")).toMatchObject({
  2092. enabled: true,
  2093. source: "cache",
  2094. });
  2095. expect(outcome.skillRoots[0]?.path).toContain(join("hello", "1.2.3", "skills"));
  2096. expect(outcome.mcpServers["plugin:hello:local"]).toMatchObject({
  2097. command: "node",
  2098. type: "stdio",
  2099. });
  2100. } finally {
  2101. await rm(dir, { force: true, recursive: true });
  2102. }
  2103. });
  2104. it("installs Claude marketplace url sources that point at pinned plugin subdirectories", async () => {
  2105. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-url-path-"));
  2106. const storageRoot = join(dir, "storage");
  2107. const marketplaceRoot = join(dir, "marketplace");
  2108. const repoRoot = join(dir, "remote-plugin");
  2109. const pluginRoot = join(repoRoot, "claude-plugin", "atomic-agents");
  2110. try {
  2111. await mkdir(repoRoot, { recursive: true });
  2112. await execFileAsync("git", ["init"], { cwd: repoRoot });
  2113. await writePluginManifest(
  2114. pluginRoot,
  2115. {
  2116. commands: "commands",
  2117. name: "wrong-name",
  2118. },
  2119. ".claude-plugin",
  2120. );
  2121. await execFileAsync("git", ["add", "."], { cwd: repoRoot });
  2122. await execFileAsync(
  2123. "git",
  2124. [
  2125. "-c",
  2126. "user.name=ZCode Test",
  2127. "-c",
  2128. "user.email=zcode-test@example.com",
  2129. "commit",
  2130. "-m",
  2131. "wrong plugin",
  2132. ],
  2133. { cwd: repoRoot },
  2134. );
  2135. await writePluginManifest(
  2136. pluginRoot,
  2137. {
  2138. commands: "commands",
  2139. name: "atomic-agents",
  2140. },
  2141. ".claude-plugin",
  2142. );
  2143. await mkdir(join(pluginRoot, "commands"), { recursive: true });
  2144. await writeFile(join(pluginRoot, "commands", "agent.md"), "# agent");
  2145. await execFileAsync("git", ["add", "."], { cwd: repoRoot });
  2146. await execFileAsync(
  2147. "git",
  2148. [
  2149. "-c",
  2150. "user.name=ZCode Test",
  2151. "-c",
  2152. "user.email=zcode-test@example.com",
  2153. "commit",
  2154. "-m",
  2155. "test plugin",
  2156. ],
  2157. { cwd: repoRoot },
  2158. );
  2159. const pinnedCommit = (
  2160. await execFileAsync("git", ["rev-parse", "HEAD"], { cwd: repoRoot })
  2161. ).stdout.trim();
  2162. await writePluginManifest(
  2163. pluginRoot,
  2164. {
  2165. commands: "commands",
  2166. name: "wrong-name-after-pin",
  2167. },
  2168. ".claude-plugin",
  2169. );
  2170. await execFileAsync("git", ["add", "."], { cwd: repoRoot });
  2171. await execFileAsync(
  2172. "git",
  2173. [
  2174. "-c",
  2175. "user.name=ZCode Test",
  2176. "-c",
  2177. "user.email=zcode-test@example.com",
  2178. "commit",
  2179. "-m",
  2180. "wrong plugin after pin",
  2181. ],
  2182. { cwd: repoRoot },
  2183. );
  2184. await writeMarketplaceManifest(marketplaceRoot, {
  2185. name: "official-like-url-path",
  2186. plugins: [
  2187. {
  2188. name: "atomic-agents",
  2189. source: {
  2190. source: "url",
  2191. url: repoRoot,
  2192. path: "claude-plugin/atomic-agents",
  2193. commit: pinnedCommit,
  2194. },
  2195. },
  2196. ],
  2197. });
  2198. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2199. const diagnostics = await validateMarketplacePlugin({
  2200. marketplace: "official-like-url-path",
  2201. name: "atomic-agents",
  2202. storageRoot,
  2203. });
  2204. expect(diagnostics.filter((item) => item.severity === "error")).toEqual([]);
  2205. const install = await installMarketplacePlugin({
  2206. marketplace: "official-like-url-path",
  2207. name: "atomic-agents",
  2208. storageRoot,
  2209. });
  2210. expect(install.installed[0]?.id).toBe("atomic-agents@official-like-url-path");
  2211. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  2212. config: {
  2213. dirs: [],
  2214. enabled: true,
  2215. enabledPlugins: {
  2216. "atomic-agents@official-like-url-path": true,
  2217. },
  2218. options: {},
  2219. },
  2220. env: {},
  2221. storageRoot,
  2222. workingDirectory: dir,
  2223. });
  2224. expect(outcome.commandRoots[0]?.path).toContain(join("atomic-agents", "0.0.0", "commands"));
  2225. const installedManifest = await readFile(
  2226. join(
  2227. storageRoot,
  2228. "cache",
  2229. "official-like-url-path",
  2230. "atomic-agents",
  2231. "0.0.0",
  2232. ".claude-plugin",
  2233. "plugin.json",
  2234. ),
  2235. "utf8",
  2236. );
  2237. expect(JSON.parse(installedManifest)).toMatchObject({ name: "atomic-agents" });
  2238. } finally {
  2239. await rm(dir, { force: true, recursive: true });
  2240. }
  2241. });
  2242. // Bugfix(插件版本 0.0.0):git/url 源插件(如 superpowers)的 marketplace 条目通常不带 version,
  2243. // 旧逻辑用 entry.version ?? "0.0.0" 拼缓存路径,导致 Root path 落到 .../<name>/0.0.0,而 UI 展示
  2244. // 读插件自带 plugin.json 的真实版本(6.0.3),两者割裂。修复后缓存路径段与安装记录均取真实版本。
  2245. it("uses the cloned plugin.json version for the cache path when the marketplace entry omits version", async () => {
  2246. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-version-from-manifest-"));
  2247. const storageRoot = join(dir, "storage");
  2248. const marketplaceRoot = join(dir, "marketplace");
  2249. const repoRoot = join(dir, "remote-plugin");
  2250. try {
  2251. await mkdir(repoRoot, { recursive: true });
  2252. await execFileAsync("git", ["init"], { cwd: repoRoot });
  2253. // 真实版本只存在于插件自带 manifest 里,marketplace 条目刻意不写 version。
  2254. await writePluginManifest(
  2255. repoRoot,
  2256. { name: "superpowers", version: "6.0.3" },
  2257. ".claude-plugin",
  2258. );
  2259. await execFileAsync("git", ["add", "."], { cwd: repoRoot });
  2260. await execFileAsync(
  2261. "git",
  2262. [
  2263. "-c",
  2264. "user.name=ZCode Test",
  2265. "-c",
  2266. "user.email=zcode-test@example.com",
  2267. "commit",
  2268. "-m",
  2269. "superpowers plugin",
  2270. ],
  2271. { cwd: repoRoot },
  2272. );
  2273. const pinnedCommit = (
  2274. await execFileAsync("git", ["rev-parse", "HEAD"], { cwd: repoRoot })
  2275. ).stdout.trim();
  2276. await writeMarketplaceManifest(marketplaceRoot, {
  2277. name: "claude-plugins-official",
  2278. plugins: [
  2279. {
  2280. name: "superpowers",
  2281. source: { source: "url", url: repoRoot, sha: pinnedCommit },
  2282. },
  2283. ],
  2284. });
  2285. await addMarketplace({
  2286. source: { source: "directory", path: marketplaceRoot },
  2287. storageRoot,
  2288. trustedId: "claude-plugins-official",
  2289. });
  2290. const install = await installMarketplacePlugin({
  2291. marketplace: "claude-plugins-official",
  2292. name: "superpowers",
  2293. storageRoot,
  2294. });
  2295. const record = install.installed.find(
  2296. (item) => item.id === "superpowers@claude-plugins-official",
  2297. );
  2298. expect(record?.version).toBe("6.0.3");
  2299. expect(record?.installPath).toContain(join("superpowers", "6.0.3"));
  2300. expect(record?.installPath).not.toContain(join("superpowers", "0.0.0"));
  2301. const installedManifest = await readFile(
  2302. join(
  2303. storageRoot,
  2304. "cache",
  2305. "claude-plugins-official",
  2306. "superpowers",
  2307. "6.0.3",
  2308. ".claude-plugin",
  2309. "plugin.json",
  2310. ),
  2311. "utf8",
  2312. );
  2313. expect(JSON.parse(installedManifest)).toMatchObject({
  2314. name: "superpowers",
  2315. version: "6.0.3",
  2316. });
  2317. } finally {
  2318. await rm(dir, { force: true, recursive: true });
  2319. }
  2320. });
  2321. it("installs a marketplace plugin from a real zip URL source", async () => {
  2322. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-url-zip-"));
  2323. const storageRoot = join(dir, "storage");
  2324. const marketplaceRoot = join(dir, "marketplace");
  2325. let server: Server | undefined;
  2326. try {
  2327. const zipBuffer = createStoredZip([
  2328. {
  2329. path: "cdn-plugin-1.2.3/.claude-plugin/plugin.json",
  2330. content: JSON.stringify({
  2331. commands: "commands",
  2332. name: "cdn-plugin",
  2333. version: "1.2.3",
  2334. }),
  2335. },
  2336. {
  2337. path: "cdn-plugin-1.2.3/commands/deploy.md",
  2338. content: [
  2339. "---",
  2340. "description: Deploy through CDN plugin",
  2341. "allowed-tools: Bash",
  2342. "---",
  2343. "",
  2344. "Run deploy with $ARGUMENTS.",
  2345. ].join("\n"),
  2346. },
  2347. ]);
  2348. const sha256 = sha256Buffer(zipBuffer);
  2349. const fixture = await startZipFixtureServer({ "/cdn-plugin.zip": zipBuffer });
  2350. server = fixture.server;
  2351. await writeMarketplaceManifest(marketplaceRoot, {
  2352. name: "cdn-market",
  2353. plugins: [
  2354. {
  2355. name: "cdn-plugin",
  2356. source: {
  2357. source: "url",
  2358. type: "zip",
  2359. url: `${fixture.baseUrl}/cdn-plugin.zip`,
  2360. sha256,
  2361. },
  2362. },
  2363. ],
  2364. });
  2365. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2366. const diagnostics = await validateMarketplacePlugin({
  2367. marketplace: "cdn-market",
  2368. name: "cdn-plugin",
  2369. storageRoot,
  2370. });
  2371. expect(diagnostics.filter((item) => item.severity === "error")).toEqual([]);
  2372. const sourceDescribe = await describeMarketplacePlugin({
  2373. marketplace: "cdn-market",
  2374. name: "cdn-plugin",
  2375. storageRoot,
  2376. });
  2377. expect(componentNames(sourceDescribe.components, "command")).toEqual(["deploy"]);
  2378. const install = await installMarketplacePlugin({
  2379. marketplace: "cdn-market",
  2380. name: "cdn-plugin",
  2381. storageRoot,
  2382. });
  2383. const record = install.installed.find((item) => item.id === "cdn-plugin@cdn-market");
  2384. expect(record).toMatchObject({
  2385. marketplace: "cdn-market",
  2386. name: "cdn-plugin",
  2387. version: "1.2.3",
  2388. });
  2389. expect(record?.installPath).toContain(join("cache", "cdn-market", "cdn-plugin", "1.2.3"));
  2390. expect(record?.source).toMatchObject({ source: "url", type: "zip", sha256 });
  2391. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  2392. config: {
  2393. dirs: [],
  2394. enabled: true,
  2395. enabledPlugins: {
  2396. "cdn-plugin@cdn-market": true,
  2397. },
  2398. options: {},
  2399. },
  2400. env: {},
  2401. storageRoot,
  2402. workingDirectory: dir,
  2403. });
  2404. expect(outcome.plugins.find((plugin) => plugin.id === "cdn-plugin@cdn-market")).toMatchObject(
  2405. {
  2406. version: "1.2.3",
  2407. },
  2408. );
  2409. expect(outcome.commandRoots[0]?.path).toContain(join("cdn-plugin", "1.2.3", "commands"));
  2410. } finally {
  2411. await closeServer(server);
  2412. await rm(dir, { force: true, recursive: true });
  2413. }
  2414. });
  2415. it("does not fall back to a local plugin when an explicit URL source is invalid", async () => {
  2416. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-invalid-url-source-"));
  2417. const storageRoot = join(dir, "storage");
  2418. const marketplaceRoot = join(dir, "marketplace");
  2419. try {
  2420. await writeMarketplaceManifest(marketplaceRoot, {
  2421. name: "invalid-url-market",
  2422. plugins: [
  2423. {
  2424. name: "invalid-url-plugin",
  2425. source: {
  2426. source: "url",
  2427. type: "zip",
  2428. sha256: "0".repeat(64),
  2429. },
  2430. },
  2431. ],
  2432. });
  2433. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2434. const localFallbackRoot = join(
  2435. storageRoot,
  2436. "marketplaces",
  2437. "invalid-url-market",
  2438. "invalid-url-plugin",
  2439. );
  2440. await writePluginManifest(localFallbackRoot, {
  2441. name: "invalid-url-plugin",
  2442. version: "1.0.0",
  2443. });
  2444. await expect(
  2445. installMarketplacePlugin({
  2446. marketplace: "invalid-url-market",
  2447. name: "invalid-url-plugin",
  2448. storageRoot,
  2449. }),
  2450. ).rejects.toThrow(/requires a non-empty url/u);
  2451. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  2452. expect(existsSync(join(storageRoot, "cache", "invalid-url-market"))).toBe(false);
  2453. } finally {
  2454. await rm(dir, { force: true, recursive: true });
  2455. }
  2456. });
  2457. it("reports invalid zip source option shapes", async () => {
  2458. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-invalid-zip-shape-"));
  2459. const marketplaceRoot = join(dir, "marketplace");
  2460. try {
  2461. await writeMarketplaceManifest(marketplaceRoot, {
  2462. name: "invalid-zip-shape-market",
  2463. plugins: [
  2464. {
  2465. name: "invalid-headers",
  2466. source: {
  2467. headers: [],
  2468. sha256: "0".repeat(64),
  2469. source: "url",
  2470. type: "zip",
  2471. url: "https://cdn.example.com/plugin.zip",
  2472. },
  2473. },
  2474. {
  2475. name: "invalid-path",
  2476. source: {
  2477. path: 42,
  2478. sha256: "0".repeat(64),
  2479. source: "url",
  2480. type: "zip",
  2481. url: "https://cdn.example.com/plugin.zip",
  2482. },
  2483. },
  2484. {
  2485. name: "invalid-strip-root",
  2486. source: {
  2487. sha256: "0".repeat(64),
  2488. source: "url",
  2489. stripRoot: "true",
  2490. type: "zip",
  2491. url: "https://cdn.example.com/plugin.zip",
  2492. },
  2493. },
  2494. ],
  2495. });
  2496. const diagnostics = await validateMarketplaceSource({
  2497. source: { source: "directory", path: marketplaceRoot },
  2498. storageRoot: join(dir, "storage"),
  2499. });
  2500. const errors = diagnostics
  2501. .filter((diagnostic) => diagnostic.severity === "error")
  2502. .map((diagnostic) => diagnostic.message);
  2503. expect(errors).toEqual(
  2504. expect.arrayContaining([
  2505. "Plugin zip source headers must be an object",
  2506. "Plugin zip source path must be a string",
  2507. "Plugin zip source stripRoot must be a boolean",
  2508. ]),
  2509. );
  2510. } finally {
  2511. await rm(dir, { force: true, recursive: true });
  2512. }
  2513. });
  2514. it("retries source cleanup without replacing the primary error", async () => {
  2515. const cleanupError = new Error("temporary directory is locked");
  2516. const cleanup = vi.fn(async () => {
  2517. throw cleanupError;
  2518. });
  2519. const returnedCleanupError = await cleanupPluginSourceBestEffort(cleanup, [0, 0, 0]);
  2520. const primaryError = new Error("Plugin zip sha256 mismatch");
  2521. const combinedError = appendPluginSourceCleanupError(primaryError, returnedCleanupError);
  2522. expect(cleanup).toHaveBeenCalledTimes(3);
  2523. expect(returnedCleanupError).toBe(cleanupError);
  2524. expect(combinedError).toBe(primaryError);
  2525. expect(primaryError.message).toContain("Plugin zip sha256 mismatch");
  2526. expect(primaryError.message).toContain("plugin source cleanup also failed");
  2527. expect(primaryError.message).toContain("temporary directory is locked");
  2528. });
  2529. it.each([
  2530. { persistent: false, proxied: true },
  2531. { persistent: true, proxied: true },
  2532. { persistent: false, proxied: false },
  2533. { persistent: true, proxied: false },
  2534. ])(
  2535. "retries a reset ZIP connection once ($persistent, proxy=$proxied)",
  2536. async ({ persistent, proxied }) => {
  2537. const zipBuffer = createStoredZip([
  2538. {
  2539. path: ".claude-plugin/plugin.json",
  2540. content: JSON.stringify({ name: "reset-zip", version: "1.0.0" }),
  2541. },
  2542. ]);
  2543. let requestCount = 0;
  2544. const proxy = createServer((request, response) => {
  2545. requestCount += 1;
  2546. if (persistent || requestCount === 1) {
  2547. request.socket.destroy();
  2548. return;
  2549. }
  2550. response.writeHead(200, { "content-type": "application/zip" });
  2551. response.end(zipBuffer);
  2552. });
  2553. let resolved: Awaited<ReturnType<typeof resolveZipPluginSource>> | undefined;
  2554. try {
  2555. const proxyBaseUrl = await listenLoopbackServer(proxy);
  2556. vi.stubEnv(ZCODE_HTTP_PROXY_ENV_KEY, proxied ? proxyBaseUrl : "");
  2557. vi.stubEnv(ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY, "{}");
  2558. vi.stubEnv(ZCODE_NO_PROXY_ENV_KEY, "");
  2559. const download = resolveZipPluginSource({
  2560. sha256: sha256Buffer(zipBuffer),
  2561. url: proxied ? "http://127.0.0.2/reset.zip" : `${proxyBaseUrl}/reset.zip`,
  2562. });
  2563. if (persistent) {
  2564. await expect(download).rejects.toMatchObject({
  2565. code: proxied ? "proxy_error" : "network_error",
  2566. });
  2567. } else {
  2568. resolved = await download;
  2569. expect(
  2570. JSON.parse(await readFile(join(resolved.path, ".claude-plugin/plugin.json"), "utf8")),
  2571. ).toEqual({ name: "reset-zip", version: "1.0.0" });
  2572. }
  2573. expect(requestCount).toBe(2);
  2574. } finally {
  2575. await resolved?.cleanup();
  2576. await closeServer(proxy);
  2577. }
  2578. },
  2579. );
  2580. it.each(["CERT_HAS_EXPIRED", "ERR_TLS_CERT_ALTNAME_INVALID", "ENOTFOUND"])(
  2581. "does not retry ZIP failures with code %s",
  2582. async (code) => {
  2583. const fetchMock = vi.fn().mockRejectedValue(
  2584. new TypeError("fetch failed", {
  2585. cause: Object.assign(new Error("download failed"), { code }),
  2586. }),
  2587. );
  2588. vi.stubGlobal("fetch", fetchMock);
  2589. await expect(
  2590. resolveZipPluginSource({
  2591. sha256: "0".repeat(64),
  2592. url: "https://cdn.example.com/plugin.zip",
  2593. }),
  2594. ).rejects.toMatchObject({ code: "network_error" });
  2595. expect(fetchMock).toHaveBeenCalledTimes(1);
  2596. },
  2597. );
  2598. it("cancels ZIP download without retrying a reset connection", async () => {
  2599. const controller = new AbortController();
  2600. const fetchMock = vi.fn(async () => {
  2601. controller.abort();
  2602. throw Object.assign(new Error("connection reset"), { code: "ECONNRESET" });
  2603. });
  2604. vi.stubGlobal("fetch", fetchMock);
  2605. await expect(
  2606. resolveZipPluginSource({
  2607. sha256: "0".repeat(64),
  2608. url: "https://cdn.example.com/plugin.zip",
  2609. signal: controller.signal,
  2610. }),
  2611. ).rejects.toMatchObject({ code: "cancelled" });
  2612. expect(fetchMock).toHaveBeenCalledTimes(1);
  2613. });
  2614. it("downloads a zip through captured user proxy env", async () => {
  2615. const zipBuffer = createStoredZip([
  2616. {
  2617. path: ".claude-plugin/plugin.json",
  2618. content: JSON.stringify({ name: "proxied-zip", version: "1.0.0" }),
  2619. },
  2620. ]);
  2621. const proxyRequests: string[] = [];
  2622. const proxy = createServer((request, response) => {
  2623. proxyRequests.push(request.url ?? "");
  2624. response.writeHead(200, {
  2625. "content-length": String(zipBuffer.byteLength),
  2626. "content-type": "application/zip",
  2627. });
  2628. response.end(zipBuffer);
  2629. });
  2630. let resolved: Awaited<ReturnType<typeof resolveZipPluginSource>> | undefined;
  2631. try {
  2632. const proxyBaseUrl = await listenLoopbackServer(proxy);
  2633. vi.stubEnv(ZCODE_HTTP_PROXY_ENV_KEY, "");
  2634. vi.stubEnv(ZCODE_NO_PROXY_ENV_KEY, "");
  2635. vi.stubEnv(ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY, JSON.stringify({ HTTP_PROXY: proxyBaseUrl }));
  2636. const sourceUrl = "http://127.0.0.2/captured-proxy.zip";
  2637. resolved = await resolveZipPluginSource({
  2638. sha256: sha256Buffer(zipBuffer),
  2639. url: sourceUrl,
  2640. });
  2641. expect(existsSync(join(resolved.path, ".claude-plugin", "plugin.json"))).toBe(true);
  2642. expect(proxyRequests).toEqual([sourceUrl]);
  2643. } finally {
  2644. await resolved?.cleanup();
  2645. await closeServer(proxy);
  2646. }
  2647. });
  2648. it("drops custom zip headers on cross-origin redirects", async () => {
  2649. const zipBuffer = createStoredZip([
  2650. {
  2651. path: ".claude-plugin/plugin.json",
  2652. content: JSON.stringify({ name: "redirected-zip", version: "1.0.0" }),
  2653. },
  2654. ]);
  2655. let originHeader: string | undefined;
  2656. let targetHeader: string | undefined;
  2657. const target = createServer((request, response) => {
  2658. targetHeader = request.headers["x-zcode-channel"] as string | undefined;
  2659. response.writeHead(200, {
  2660. "content-length": String(zipBuffer.byteLength),
  2661. "content-type": "application/zip",
  2662. });
  2663. response.end(zipBuffer);
  2664. });
  2665. let origin: Server | undefined;
  2666. let resolved: Awaited<ReturnType<typeof resolveZipPluginSource>> | undefined;
  2667. try {
  2668. const targetBaseUrl = await listenLoopbackServer(target);
  2669. origin = createServer((request, response) => {
  2670. originHeader = request.headers["x-zcode-channel"] as string | undefined;
  2671. response.writeHead(302, { location: `${targetBaseUrl}/plugin.zip` });
  2672. response.end();
  2673. });
  2674. const originBaseUrl = await listenLoopbackServer(origin);
  2675. vi.stubEnv(ZCODE_NO_PROXY_ENV_KEY, "127.0.0.1");
  2676. resolved = await resolveZipPluginSource({
  2677. headers: { "x-zcode-channel": "internal" },
  2678. sha256: sha256Buffer(zipBuffer),
  2679. url: `${originBaseUrl}/redirect.zip`,
  2680. });
  2681. expect(originHeader).toBe("internal");
  2682. expect(targetHeader).toBeUndefined();
  2683. } finally {
  2684. await resolved?.cleanup();
  2685. await closeServer(origin);
  2686. await closeServer(target);
  2687. }
  2688. });
  2689. it("rejects a zip redirect to non-loopback HTTP", async () => {
  2690. const origin = createServer((_request, response) => {
  2691. response.writeHead(302, { location: "http://example.com/plugin.zip" });
  2692. response.end();
  2693. });
  2694. try {
  2695. const originBaseUrl = await listenLoopbackServer(origin);
  2696. vi.stubEnv(ZCODE_NO_PROXY_ENV_KEY, "127.0.0.1");
  2697. await expect(
  2698. resolveZipPluginSource({
  2699. sha256: "0".repeat(64),
  2700. url: `${originBaseUrl}/redirect.zip`,
  2701. }),
  2702. ).rejects.toThrow(/must be HTTPS/u);
  2703. } finally {
  2704. await closeServer(origin);
  2705. }
  2706. });
  2707. it("rejects a zip root without a manifest before replacing existing cache", async () => {
  2708. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-url-zip-root-"));
  2709. const storageRoot = join(dir, "storage");
  2710. const marketplaceRoot = join(dir, "marketplace");
  2711. const existingCacheRoot = join(
  2712. storageRoot,
  2713. "cache",
  2714. "invalid-root-market",
  2715. "invalid-root",
  2716. "1.0.0",
  2717. );
  2718. let server: Server | undefined;
  2719. try {
  2720. const zipBuffer = createStoredZip([
  2721. {
  2722. path: "bundle-a/README.md",
  2723. content: "First top-level directory.",
  2724. },
  2725. {
  2726. path: "bundle-b/.claude-plugin/plugin.json",
  2727. content: JSON.stringify({ name: "invalid-root", version: "1.0.0" }),
  2728. },
  2729. ]);
  2730. const fixture = await startZipFixtureServer({ "/invalid-root.zip": zipBuffer });
  2731. server = fixture.server;
  2732. await writeMarketplaceManifest(marketplaceRoot, {
  2733. name: "invalid-root-market",
  2734. plugins: [
  2735. {
  2736. name: "invalid-root",
  2737. version: "1.0.0",
  2738. source: {
  2739. source: "url",
  2740. type: "zip",
  2741. url: `${fixture.baseUrl}/invalid-root.zip`,
  2742. sha256: sha256Buffer(zipBuffer),
  2743. },
  2744. },
  2745. ],
  2746. });
  2747. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2748. await mkdir(existingCacheRoot, { recursive: true });
  2749. await writeFile(join(existingCacheRoot, "keep.txt"), "existing cache");
  2750. await expect(
  2751. installMarketplacePlugin({
  2752. marketplace: "invalid-root-market",
  2753. name: "invalid-root",
  2754. storageRoot,
  2755. }),
  2756. ).rejects.toThrow("Plugin manifest not found: invalid-root@invalid-root-market");
  2757. expect(await readFile(join(existingCacheRoot, "keep.txt"), "utf8")).toBe("existing cache");
  2758. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  2759. } finally {
  2760. await closeServer(server);
  2761. await rm(dir, { force: true, recursive: true });
  2762. }
  2763. });
  2764. it("rejects marketplace zip sources with mismatched sha256 without installing", async () => {
  2765. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-url-zip-sha-"));
  2766. const storageRoot = join(dir, "storage");
  2767. const marketplaceRoot = join(dir, "marketplace");
  2768. let server: Server | undefined;
  2769. try {
  2770. const zipBuffer = createStoredZip([
  2771. {
  2772. path: ".claude-plugin/plugin.json",
  2773. content: JSON.stringify({ name: "bad-zip", version: "1.0.0" }),
  2774. },
  2775. ]);
  2776. const fixture = await startZipFixtureServer({ "/bad.zip": zipBuffer });
  2777. server = fixture.server;
  2778. await writeMarketplaceManifest(marketplaceRoot, {
  2779. name: "bad-zip-market",
  2780. plugins: [
  2781. {
  2782. name: "bad-zip",
  2783. source: {
  2784. source: "url",
  2785. type: "zip",
  2786. url: `${fixture.baseUrl}/bad.zip`,
  2787. sha256: "0".repeat(64),
  2788. },
  2789. },
  2790. ],
  2791. });
  2792. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2793. await expect(
  2794. installMarketplacePlugin({
  2795. marketplace: "bad-zip-market",
  2796. name: "bad-zip",
  2797. storageRoot,
  2798. }),
  2799. ).rejects.toThrow("sha256 mismatch");
  2800. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  2801. expect(existsSync(join(storageRoot, "cache", "bad-zip-market", "bad-zip"))).toBe(false);
  2802. } finally {
  2803. await closeServer(server);
  2804. await rm(dir, { force: true, recursive: true });
  2805. }
  2806. });
  2807. it("rejects unsafe zip entry paths before cache materialization", async () => {
  2808. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-url-zip-slip-"));
  2809. const storageRoot = join(dir, "storage");
  2810. const marketplaceRoot = join(dir, "marketplace");
  2811. let server: Server | undefined;
  2812. try {
  2813. const zipBuffer = createStoredZip([
  2814. {
  2815. path: "../escape.txt",
  2816. content: "escape",
  2817. },
  2818. {
  2819. path: ".claude-plugin/plugin.json",
  2820. content: JSON.stringify({ name: "zip-slip", version: "1.0.0" }),
  2821. },
  2822. ]);
  2823. const fixture = await startZipFixtureServer({ "/slip.zip": zipBuffer });
  2824. server = fixture.server;
  2825. await writeMarketplaceManifest(marketplaceRoot, {
  2826. name: "zip-slip-market",
  2827. plugins: [
  2828. {
  2829. name: "zip-slip",
  2830. source: {
  2831. source: "url",
  2832. type: "zip",
  2833. url: `${fixture.baseUrl}/slip.zip`,
  2834. sha256: sha256Buffer(zipBuffer),
  2835. },
  2836. },
  2837. ],
  2838. });
  2839. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2840. await expect(
  2841. installMarketplacePlugin({
  2842. marketplace: "zip-slip-market",
  2843. name: "zip-slip",
  2844. storageRoot,
  2845. }),
  2846. ).rejects.toThrow(/Unsafe plugin zip path|invalid relative path/u);
  2847. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  2848. expect(existsSync(join(storageRoot, "cache", "zip-slip-market", "zip-slip"))).toBe(false);
  2849. } finally {
  2850. await closeServer(server);
  2851. await rm(dir, { force: true, recursive: true });
  2852. }
  2853. });
  2854. it("adds a public GitHub marketplace and installs its GitHub plugin without system Git", async () => {
  2855. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-github-archive-no-git-"));
  2856. const storageRoot = join(dir, "storage");
  2857. const marketplaceArchive = createStoredZip([
  2858. {
  2859. path: "catalog-release/.claude-plugin/marketplace.json",
  2860. content: JSON.stringify({
  2861. name: "archive-market",
  2862. plugins: [
  2863. {
  2864. name: "archive-plugin",
  2865. source: {
  2866. source: "github",
  2867. repo: "acme/archive-plugin",
  2868. sha: "abc123def456",
  2869. path: "packages/archive-plugin",
  2870. },
  2871. },
  2872. ],
  2873. }),
  2874. },
  2875. ]);
  2876. const pluginArchive = createStoredZip([
  2877. {
  2878. path: "archive-plugin-abc123/packages/archive-plugin/.claude-plugin/plugin.json",
  2879. content: JSON.stringify({ name: "archive-plugin", version: "1.2.3" }),
  2880. },
  2881. {
  2882. path: "archive-plugin-abc123/packages/archive-plugin/skills/demo/SKILL.md",
  2883. content: "# demo",
  2884. },
  2885. ]);
  2886. const requestedUrls: string[] = [];
  2887. try {
  2888. vi.stubEnv("PATH", join(dir, "no-system-git"));
  2889. vi.stubEnv("HTTP_PROXY", "");
  2890. vi.stubEnv("HTTPS_PROXY", "");
  2891. vi.stubGlobal(
  2892. "fetch",
  2893. vi.fn(async (url: string | URL | Request) => {
  2894. const value = String(url);
  2895. requestedUrls.push(value);
  2896. const body = value.includes("/acme/archive-plugin/") ? pluginArchive : marketplaceArchive;
  2897. return new Response(body, {
  2898. headers: { "content-type": "application/zip" },
  2899. status: 200,
  2900. });
  2901. }),
  2902. );
  2903. const marketplace = await addMarketplace({
  2904. source: { source: "github", repo: "acme/catalog", ref: "release" },
  2905. storageRoot,
  2906. });
  2907. const install = await installMarketplacePlugin({
  2908. marketplace: "archive-market",
  2909. name: "archive-plugin",
  2910. storageRoot,
  2911. });
  2912. expect(marketplace.id).toBe("archive-market");
  2913. expect(requestedUrls).toEqual([
  2914. "https://api.github.com/repos/acme/catalog/zipball/release",
  2915. "https://api.github.com/repos/acme/archive-plugin/zipball/abc123def456",
  2916. ]);
  2917. expect(install.installed[0]).toMatchObject({
  2918. id: "archive-plugin@archive-market",
  2919. version: "1.2.3",
  2920. });
  2921. expect(
  2922. existsSync(join(install.installed[0]?.installPath ?? "", "skills", "demo", "SKILL.md")),
  2923. ).toBe(true);
  2924. } finally {
  2925. await rm(dir, { force: true, recursive: true });
  2926. }
  2927. });
  2928. it("preserves Git sparse checkout semantics for public GitHub marketplace sources", async () => {
  2929. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-github-sparse-marketplace-"));
  2930. const storageRoot = join(dir, "storage");
  2931. const archive = createStoredZip([
  2932. {
  2933. path: "catalog-main/.claude-plugin/marketplace.json",
  2934. content: JSON.stringify({ name: "sparse-market", plugins: [] }),
  2935. },
  2936. ]);
  2937. const fetchMock = vi.fn(
  2938. async () =>
  2939. new Response(archive, { headers: { "content-type": "application/zip" }, status: 200 }),
  2940. );
  2941. try {
  2942. vi.stubEnv("PATH", join(dir, "no-system-git"));
  2943. vi.stubEnv("HTTP_PROXY", "");
  2944. vi.stubEnv("HTTPS_PROXY", "");
  2945. vi.stubGlobal("fetch", fetchMock);
  2946. await expect(
  2947. addMarketplace({
  2948. source: {
  2949. source: "github",
  2950. repo: "acme/sparse-catalog",
  2951. sparsePaths: [".claude-plugin"],
  2952. },
  2953. storageRoot,
  2954. }),
  2955. ).rejects.toThrow(/System Git is required.*acme\/sparse-catalog.*Agent Host/u);
  2956. expect(fetchMock).not.toHaveBeenCalled();
  2957. } finally {
  2958. await rm(dir, { force: true, recursive: true });
  2959. }
  2960. });
  2961. it("falls back to Git when a plugin subdirectory inherits LFS attributes from an ancestor", async () => {
  2962. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-github-ancestor-lfs-"));
  2963. const storageRoot = join(dir, "storage");
  2964. const marketplaceRoot = join(dir, "marketplace");
  2965. const archive = createStoredZip([
  2966. {
  2967. path: "lfs-plugin-main/packages/.gitattributes",
  2968. content: "*.bin filter=lfs diff=lfs merge=lfs -text\n",
  2969. },
  2970. {
  2971. path: "lfs-plugin-main/packages/plugin/.claude-plugin/plugin.json",
  2972. content: JSON.stringify({ name: "lfs-plugin", version: "1.0.0" }),
  2973. },
  2974. {
  2975. path: "lfs-plugin-main/packages/plugin/model.bin",
  2976. content:
  2977. "version https://git-lfs.github.com/spec/v1\noid sha256:0123456789abcdef\nsize 42\n",
  2978. },
  2979. ]);
  2980. try {
  2981. await writeMarketplaceManifest(marketplaceRoot, {
  2982. name: "ancestor-lfs-market",
  2983. plugins: [
  2984. {
  2985. name: "lfs-plugin",
  2986. source: {
  2987. source: "github",
  2988. repo: "acme/lfs-plugin",
  2989. path: "packages/plugin",
  2990. },
  2991. },
  2992. ],
  2993. });
  2994. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  2995. vi.stubEnv("PATH", join(dir, "no-system-git"));
  2996. vi.stubEnv("HTTP_PROXY", "");
  2997. vi.stubEnv("HTTPS_PROXY", "");
  2998. vi.stubGlobal(
  2999. "fetch",
  3000. vi.fn(
  3001. async () =>
  3002. new Response(archive, {
  3003. headers: { "content-type": "application/zip" },
  3004. status: 200,
  3005. }),
  3006. ),
  3007. );
  3008. await expect(
  3009. installMarketplacePlugin({
  3010. marketplace: "ancestor-lfs-market",
  3011. name: "lfs-plugin",
  3012. storageRoot,
  3013. }),
  3014. ).rejects.toThrow(/System Git is required.*acme\/lfs-plugin.*Agent Host/u);
  3015. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  3016. } finally {
  3017. await rm(dir, { force: true, recursive: true });
  3018. }
  3019. });
  3020. it.each([
  3021. [
  3022. "git",
  3023. {
  3024. source: "git",
  3025. url: "https://github.com/acme/source-variants.git",
  3026. ref: "ignored-ref",
  3027. sha: "pinned-sha",
  3028. path: "packages/source-variant",
  3029. },
  3030. ],
  3031. [
  3032. "url:git",
  3033. {
  3034. source: "url",
  3035. type: "git",
  3036. url: "https://github.com/acme/source-variants.git",
  3037. ref: "ignored-ref",
  3038. commit: "pinned-sha",
  3039. path: "packages/source-variant",
  3040. },
  3041. ],
  3042. [
  3043. "git-subdir",
  3044. {
  3045. source: "git-subdir",
  3046. url: "acme/source-variants",
  3047. ref: "ignored-ref",
  3048. sha: "pinned-sha",
  3049. path: "packages/source-variant",
  3050. },
  3051. ],
  3052. ])(
  3053. "materializes public GitHub %s plugin sources through the pinned Archive",
  3054. async (_label, source) => {
  3055. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-github-source-variant-"));
  3056. const storageRoot = join(dir, "storage");
  3057. const marketplaceRoot = join(dir, "marketplace");
  3058. const archive = createStoredZip([
  3059. {
  3060. path: "source-variants-pin/packages/source-variant/.claude-plugin/plugin.json",
  3061. content: JSON.stringify({ name: "source-variant", version: "2.0.0" }),
  3062. },
  3063. ]);
  3064. const fetchMock = vi.fn(
  3065. async () =>
  3066. new Response(archive, { headers: { "content-type": "application/zip" }, status: 200 }),
  3067. );
  3068. try {
  3069. await writeMarketplaceManifest(marketplaceRoot, {
  3070. name: "source-variant-market",
  3071. plugins: [{ name: "source-variant", source }],
  3072. });
  3073. await addMarketplace({
  3074. source: { source: "directory", path: marketplaceRoot },
  3075. storageRoot,
  3076. });
  3077. vi.stubEnv("PATH", join(dir, "no-system-git"));
  3078. vi.stubEnv("HTTP_PROXY", "");
  3079. vi.stubEnv("HTTPS_PROXY", "");
  3080. vi.stubGlobal("fetch", fetchMock);
  3081. const install = await installMarketplacePlugin({
  3082. marketplace: "source-variant-market",
  3083. name: "source-variant",
  3084. storageRoot,
  3085. });
  3086. expect(fetchMock).toHaveBeenCalledWith(
  3087. "https://api.github.com/repos/acme/source-variants/zipball/pinned-sha",
  3088. expect.anything(),
  3089. );
  3090. expect(install.installed[0]?.version).toBe("2.0.0");
  3091. } finally {
  3092. await rm(dir, { force: true, recursive: true });
  3093. }
  3094. },
  3095. );
  3096. it("returns an actionable error when a non-GitHub source requires unavailable system Git", async () => {
  3097. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-system-git-unavailable-"));
  3098. const storageRoot = join(dir, "storage");
  3099. const marketplaceRoot = join(dir, "marketplace");
  3100. try {
  3101. await writeMarketplaceManifest(marketplaceRoot, {
  3102. name: "git-required-market",
  3103. plugins: [
  3104. {
  3105. name: "private-plugin",
  3106. source: {
  3107. source: "git",
  3108. url: "ssh://git@example.test/private/plugin.git",
  3109. },
  3110. },
  3111. ],
  3112. });
  3113. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  3114. vi.stubEnv("PATH", join(dir, "no-system-git"));
  3115. await expect(
  3116. installMarketplacePlugin({
  3117. marketplace: "git-required-market",
  3118. name: "private-plugin",
  3119. storageRoot,
  3120. }),
  3121. ).rejects.toThrow(
  3122. /System Git is required.*ssh:\/\/example\.test\/private\/plugin\.git.*Agent Host/u,
  3123. );
  3124. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  3125. } finally {
  3126. await rm(dir, { force: true, recursive: true });
  3127. }
  3128. });
  3129. it("redacts Git URL credentials from unavailable and persisted refresh diagnostics", async () => {
  3130. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-git-credential-redaction-"));
  3131. const storageRoot = join(dir, "storage");
  3132. const credentialSource = "https://private-user:private-secret@example.test/plugins.git";
  3133. try {
  3134. await writeKnownMarketplaces(storageRoot, [
  3135. {
  3136. id: "credential-market",
  3137. source: { source: "git", url: credentialSource },
  3138. name: "credential-market",
  3139. addedAt: "2026-01-01T00:00:00.000Z",
  3140. pluginCount: 0,
  3141. },
  3142. ]);
  3143. vi.stubEnv("ZCODE_GIT_BINARY", join(dir, "missing-git"));
  3144. expect(await updateMarketplace({ marketplace: "credential-market", storageRoot })).toEqual(
  3145. [],
  3146. );
  3147. const message = loadKnownMarketplacesSync(storageRoot)[0]?.lastRefreshFailure?.message ?? "";
  3148. expect(message).toContain("https://example.test/plugins.git");
  3149. expect(message).not.toContain("private-user");
  3150. expect(message).not.toContain("private-secret");
  3151. } finally {
  3152. await rm(dir, { force: true, recursive: true });
  3153. }
  3154. });
  3155. it("redacts credentials from nested GitHub Archive failure messages", () => {
  3156. const error = createArchiveFetchError(
  3157. "https://source-user:source-secret@github.com/acme/plugin.git",
  3158. new Error(
  3159. "request to https://cause-user:cause-secret@codeload.github.com/acme/plugin/zip failed",
  3160. ),
  3161. );
  3162. expect(error.message).toContain("https://github.com/acme/plugin.git");
  3163. expect(error.message).toContain("https://codeload.github.com/acme/plugin/zip");
  3164. expect(error.message).not.toMatch(/source-user|source-secret|cause-user|cause-secret/u);
  3165. expect((error.cause as Error | undefined)?.message).not.toMatch(/cause-user|cause-secret/u);
  3166. });
  3167. it("does not fall back to system Git for a GitHub Archive server failure", async () => {
  3168. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-github-archive-network-failure-"));
  3169. const storageRoot = join(dir, "storage");
  3170. const marketplaceRoot = join(dir, "marketplace");
  3171. try {
  3172. await writeMarketplaceManifest(marketplaceRoot, {
  3173. name: "archive-failure-market",
  3174. plugins: [
  3175. {
  3176. name: "archive-failure",
  3177. source: { source: "git", url: "https://github.com/acme/archive-failure.git" },
  3178. },
  3179. ],
  3180. });
  3181. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  3182. vi.stubEnv("PATH", join(dir, "no-system-git"));
  3183. vi.stubEnv("HTTP_PROXY", "");
  3184. vi.stubEnv("HTTPS_PROXY", "");
  3185. vi.stubGlobal(
  3186. "fetch",
  3187. vi.fn(async () => new Response("unavailable", { status: 503 })),
  3188. );
  3189. await expect(
  3190. installMarketplacePlugin({
  3191. marketplace: "archive-failure-market",
  3192. name: "archive-failure",
  3193. storageRoot,
  3194. }),
  3195. ).rejects.toThrow(/Failed to materialize public GitHub plugin source archive.*503/u);
  3196. } finally {
  3197. await rm(dir, { force: true, recursive: true });
  3198. }
  3199. });
  3200. it("falls back from an anonymous GitHub 404 and explains when system Git is unavailable", async () => {
  3201. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-github-private-fallback-"));
  3202. const storageRoot = join(dir, "storage");
  3203. const marketplaceRoot = join(dir, "marketplace");
  3204. try {
  3205. await writeMarketplaceManifest(marketplaceRoot, {
  3206. name: "private-github-market",
  3207. plugins: [
  3208. {
  3209. name: "private-github",
  3210. source: { source: "github", repo: "acme/private-github" },
  3211. },
  3212. ],
  3213. });
  3214. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  3215. vi.stubEnv("PATH", join(dir, "no-system-git"));
  3216. vi.stubEnv("HTTP_PROXY", "");
  3217. vi.stubEnv("HTTPS_PROXY", "");
  3218. vi.stubGlobal(
  3219. "fetch",
  3220. vi.fn(async () => new Response("not found", { status: 404 })),
  3221. );
  3222. await expect(
  3223. installMarketplacePlugin({
  3224. marketplace: "private-github-market",
  3225. name: "private-github",
  3226. storageRoot,
  3227. }),
  3228. ).rejects.toThrow(
  3229. /System Git is required.*https:\/\/github\.com\/acme\/private-github\.git/u,
  3230. );
  3231. } finally {
  3232. await rm(dir, { force: true, recursive: true });
  3233. }
  3234. });
  3235. it("isolates marketplace refresh failures and clears the persisted failure after recovery", async () => {
  3236. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-refresh-isolation-"));
  3237. const storageRoot = join(dir, "storage");
  3238. const goodSource = join(dir, "good-source");
  3239. const badSource = join(dir, "bad-source");
  3240. const oldBadSnapshot = join(storageRoot, "marketplaces", "bad-market");
  3241. try {
  3242. await writeMarketplaceManifest(goodSource, {
  3243. name: "good-market",
  3244. plugins: [{ name: "good-v2", source: "./good-v2" }],
  3245. });
  3246. await mkdir(oldBadSnapshot, { recursive: true });
  3247. await writeFile(
  3248. join(oldBadSnapshot, "marketplace.json"),
  3249. JSON.stringify({ name: "bad-market", plugins: [{ name: "bad-v1", source: "./bad-v1" }] }),
  3250. );
  3251. await writeKnownMarketplaces(storageRoot, [
  3252. {
  3253. id: "good-market",
  3254. source: { source: "directory", path: goodSource },
  3255. name: "good-market",
  3256. addedAt: "2026-01-01T00:00:00.000Z",
  3257. lastUpdated: "2026-01-01T00:00:00.000Z",
  3258. pluginCount: 1,
  3259. },
  3260. {
  3261. id: "bad-market",
  3262. source: { source: "directory", path: badSource },
  3263. name: "bad-market",
  3264. addedAt: "2026-01-01T00:00:00.000Z",
  3265. lastUpdated: "2026-01-01T00:00:00.000Z",
  3266. pluginCount: 1,
  3267. },
  3268. ]);
  3269. vi.stubGlobal(
  3270. "fetch",
  3271. vi.fn(async () => new Response("[]", { status: 200 })),
  3272. );
  3273. const updated = await updateMarketplace({ storageRoot });
  3274. expect(updated.map((record) => record.id)).toContain("good-market");
  3275. expect(loadMarketplaceManifestSync(storageRoot, "bad-market")?.plugins[0]?.name).toBe(
  3276. "bad-v1",
  3277. );
  3278. expect(
  3279. loadKnownMarketplacesSync(storageRoot).find((record) => record.id === "bad-market")
  3280. ?.lastRefreshFailure,
  3281. ).toMatchObject({ code: "plugin_marketplace_invalid", failedAt: expect.any(String) });
  3282. await writeMarketplaceManifest(badSource, {
  3283. name: "bad-market",
  3284. plugins: [{ name: "bad-v2", source: "./bad-v2" }],
  3285. });
  3286. await updateMarketplace({ marketplace: "bad-market", storageRoot });
  3287. expect(loadMarketplaceManifestSync(storageRoot, "bad-market")?.plugins[0]?.name).toBe(
  3288. "bad-v2",
  3289. );
  3290. expect(
  3291. loadKnownMarketplacesSync(storageRoot).find((record) => record.id === "bad-market")
  3292. ?.lastRefreshFailure,
  3293. ).toBeUndefined();
  3294. } finally {
  3295. await rm(dir, { force: true, recursive: true });
  3296. }
  3297. });
  3298. it("does not persist an operation cancellation as a marketplace refresh failure", async () => {
  3299. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-refresh-cancel-"));
  3300. const storageRoot = join(dir, "storage");
  3301. const controller = new AbortController();
  3302. try {
  3303. await writeKnownMarketplaces(storageRoot, [
  3304. {
  3305. id: "cancelled-market",
  3306. source: { source: "github", repo: "acme/cancelled-market" },
  3307. name: "cancelled-market",
  3308. addedAt: "2026-01-01T00:00:00.000Z",
  3309. lastUpdated: "2026-01-01T00:00:00.000Z",
  3310. pluginCount: 0,
  3311. },
  3312. ]);
  3313. vi.stubGlobal(
  3314. "fetch",
  3315. vi.fn(
  3316. (_input: RequestInfo | URL, init?: RequestInit) =>
  3317. new Promise<Response>((_resolve, reject) => {
  3318. const signal = init?.signal;
  3319. if (signal?.aborted) {
  3320. reject(signal.reason);
  3321. return;
  3322. }
  3323. signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
  3324. }),
  3325. ),
  3326. );
  3327. const refresh = updateMarketplace({
  3328. marketplace: "cancelled-market",
  3329. signal: controller.signal,
  3330. storageRoot,
  3331. });
  3332. await vi.waitFor(() => expect(fetch).toHaveBeenCalled());
  3333. controller.abort();
  3334. await expect(refresh).rejects.toBeDefined();
  3335. expect(
  3336. loadKnownMarketplacesSync(storageRoot).find((record) => record.id === "cancelled-market")
  3337. ?.lastRefreshFailure,
  3338. ).toBeUndefined();
  3339. } finally {
  3340. await rm(dir, { force: true, recursive: true });
  3341. }
  3342. });
  3343. it("keeps the previous Claude settings snapshot when timeout fires during manifest persistence", async () => {
  3344. vi.useFakeTimers();
  3345. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-claude-settings-timeout-"));
  3346. const storageRoot = join(dir, "storage");
  3347. const marketplaceRoot = join(storageRoot, "marketplaces", "claude-plugins-official");
  3348. try {
  3349. await mkdir(marketplaceRoot, { recursive: true });
  3350. await writeFile(
  3351. join(marketplaceRoot, "marketplace.json"),
  3352. JSON.stringify({
  3353. name: "claude-plugins-official",
  3354. plugins: [{ name: "cached", source: "./cached" }],
  3355. }),
  3356. );
  3357. await writeKnownMarketplaces(storageRoot, [
  3358. {
  3359. id: "claude-plugins-official",
  3360. source: {
  3361. source: "settings",
  3362. marketplace: {
  3363. name: "claude-plugins-official",
  3364. plugins: [],
  3365. raw: { name: "claude-plugins-official", plugins: [] },
  3366. },
  3367. },
  3368. name: "claude-plugins-official",
  3369. addedAt: "2026-01-01T00:00:00.000Z",
  3370. lastUpdated: "2026-01-02T00:00:00.000Z",
  3371. pluginCount: 1,
  3372. },
  3373. ]);
  3374. for (const key of [
  3375. ZCODE_HTTP_PROXY_ENV_KEY,
  3376. "HTTP_PROXY",
  3377. "HTTPS_PROXY",
  3378. "ALL_PROXY",
  3379. "http_proxy",
  3380. "https_proxy",
  3381. "all_proxy",
  3382. ZCODE_AGENT_CA_CERT_ENV_KEY,
  3383. "NODE_EXTRA_CA_CERTS",
  3384. ]) {
  3385. vi.stubEnv(key, "");
  3386. }
  3387. vi.stubEnv(ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY, "{}");
  3388. vi.stubGlobal(
  3389. "fetch",
  3390. vi.fn(async () => new Response("[]", { status: 200 })),
  3391. );
  3392. const freshRaw = {
  3393. name: "claude-plugins-official",
  3394. plugins: [{ name: "fresh", source: "./fresh" }],
  3395. // 回归触发点:旧实现会在序列化 active manifest 时触发 deadline,但仍覆盖旧文件。
  3396. toJSON: () => {
  3397. vi.advanceTimersByTime(30_000);
  3398. return {
  3399. name: "claude-plugins-official",
  3400. plugins: [{ name: "fresh", source: "./fresh" }],
  3401. };
  3402. },
  3403. };
  3404. await expect(
  3405. addMarketplace({
  3406. source: {
  3407. source: "settings",
  3408. marketplace: {
  3409. name: "claude-plugins-official",
  3410. plugins: [
  3411. {
  3412. name: "fresh",
  3413. source: "./fresh",
  3414. raw: { name: "fresh", source: "./fresh" },
  3415. },
  3416. ],
  3417. raw: freshRaw,
  3418. },
  3419. },
  3420. storageRoot,
  3421. trustedId: "claude-plugins-official",
  3422. }),
  3423. ).rejects.toThrow("30 seconds");
  3424. expect(
  3425. loadMarketplaceManifestSync(storageRoot, "claude-plugins-official")?.plugins[0]?.name,
  3426. ).toBe("cached");
  3427. expect(
  3428. loadKnownMarketplacesSync(storageRoot).find(
  3429. (record) => record.id === "claude-plugins-official",
  3430. ),
  3431. ).toMatchObject({
  3432. lastUpdated: "2026-01-02T00:00:00.000Z",
  3433. pluginCount: 1,
  3434. });
  3435. } finally {
  3436. await rm(dir, { force: true, recursive: true });
  3437. vi.useRealTimers();
  3438. }
  3439. });
  3440. it("rolls back a settings marketplace manifest when known state persistence fails", async () => {
  3441. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-settings-known-state-failure-"));
  3442. const storageRoot = join(dir, "storage");
  3443. const marketplaceRoot = join(storageRoot, "marketplaces", "settings-market");
  3444. try {
  3445. await mkdir(marketplaceRoot, { recursive: true });
  3446. await writeFile(
  3447. join(marketplaceRoot, "marketplace.json"),
  3448. JSON.stringify({
  3449. name: "settings-market",
  3450. plugins: [{ name: "cached", source: "./cached" }],
  3451. }),
  3452. );
  3453. await writeKnownMarketplaces(storageRoot, [
  3454. {
  3455. id: "settings-market",
  3456. source: {
  3457. source: "settings",
  3458. marketplace: {
  3459. name: "settings-market",
  3460. plugins: [],
  3461. raw: { name: "settings-market", plugins: [] },
  3462. },
  3463. },
  3464. name: "settings-market",
  3465. addedAt: "2026-01-01T00:00:00.000Z",
  3466. lastUpdated: "2026-01-02T00:00:00.000Z",
  3467. pluginCount: 1,
  3468. },
  3469. ]);
  3470. let serializationCount = 0;
  3471. const freshRaw = {
  3472. name: "settings-market",
  3473. plugins: [{ name: "fresh", source: "./fresh" }],
  3474. toJSON: () => {
  3475. serializationCount += 1;
  3476. if (serializationCount === 2) {
  3477. throw new Error("known state persistence failed");
  3478. }
  3479. return {
  3480. name: "settings-market",
  3481. plugins: [{ name: "fresh", source: "./fresh" }],
  3482. };
  3483. },
  3484. };
  3485. await expect(
  3486. addMarketplace({
  3487. source: {
  3488. source: "settings",
  3489. marketplace: {
  3490. name: "settings-market",
  3491. plugins: [
  3492. {
  3493. name: "fresh",
  3494. source: "./fresh",
  3495. raw: { name: "fresh", source: "./fresh" },
  3496. },
  3497. ],
  3498. raw: freshRaw,
  3499. },
  3500. },
  3501. storageRoot,
  3502. }),
  3503. ).rejects.toThrow("known state persistence failed");
  3504. expect(loadMarketplaceManifestSync(storageRoot, "settings-market")?.plugins[0]?.name).toBe(
  3505. "cached",
  3506. );
  3507. expect(
  3508. loadKnownMarketplacesSync(storageRoot).find((record) => record.id === "settings-market"),
  3509. ).toMatchObject({
  3510. lastUpdated: "2026-01-02T00:00:00.000Z",
  3511. pluginCount: 1,
  3512. });
  3513. } finally {
  3514. await rm(dir, { force: true, recursive: true });
  3515. }
  3516. });
  3517. it("rolls back Claude manifest and known state when timeout fires during authority persistence", async () => {
  3518. vi.useFakeTimers();
  3519. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-claude-authority-timeout-"));
  3520. const storageRoot = join(dir, "storage");
  3521. const marketplaceRoot = join(storageRoot, "marketplaces", "claude-plugins-official");
  3522. try {
  3523. await mkdir(marketplaceRoot, { recursive: true });
  3524. await writeFile(
  3525. join(marketplaceRoot, "marketplace.json"),
  3526. JSON.stringify({
  3527. name: "claude-plugins-official",
  3528. plugins: [{ name: "cached", source: "./cached" }],
  3529. }),
  3530. );
  3531. await writeKnownMarketplaces(storageRoot, [
  3532. {
  3533. id: "claude-plugins-official",
  3534. source: {
  3535. source: "settings",
  3536. marketplace: {
  3537. name: "claude-plugins-official",
  3538. plugins: [],
  3539. raw: { name: "claude-plugins-official", plugins: [] },
  3540. },
  3541. },
  3542. name: "claude-plugins-official",
  3543. addedAt: "2026-01-01T00:00:00.000Z",
  3544. lastUpdated: "2026-01-02T00:00:00.000Z",
  3545. pluginCount: 1,
  3546. },
  3547. ]);
  3548. for (const key of [
  3549. ZCODE_HTTP_PROXY_ENV_KEY,
  3550. "HTTP_PROXY",
  3551. "HTTPS_PROXY",
  3552. "ALL_PROXY",
  3553. "http_proxy",
  3554. "https_proxy",
  3555. "all_proxy",
  3556. ZCODE_AGENT_CA_CERT_ENV_KEY,
  3557. "NODE_EXTRA_CA_CERTS",
  3558. ]) {
  3559. vi.stubEnv(key, "");
  3560. }
  3561. vi.stubEnv(ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY, "{}");
  3562. vi.stubGlobal(
  3563. "fetch",
  3564. vi.fn(async () => new Response("[]", { status: 200 })),
  3565. );
  3566. let serializationCount = 0;
  3567. const freshRaw = {
  3568. name: "claude-plugins-official",
  3569. plugins: [{ name: "fresh", source: "./fresh" }],
  3570. toJSON: () => {
  3571. serializationCount += 1;
  3572. // 第一次序列化 staging manifest,第二次序列化 authority state。
  3573. if (serializationCount === 2) {
  3574. vi.advanceTimersByTime(30_000);
  3575. }
  3576. return {
  3577. name: "claude-plugins-official",
  3578. plugins: [{ name: "fresh", source: "./fresh" }],
  3579. };
  3580. },
  3581. };
  3582. await expect(
  3583. addMarketplace({
  3584. source: {
  3585. source: "settings",
  3586. marketplace: {
  3587. name: "claude-plugins-official",
  3588. plugins: [
  3589. {
  3590. name: "fresh",
  3591. source: "./fresh",
  3592. raw: { name: "fresh", source: "./fresh" },
  3593. },
  3594. ],
  3595. raw: freshRaw,
  3596. },
  3597. },
  3598. storageRoot,
  3599. trustedId: "claude-plugins-official",
  3600. }),
  3601. ).rejects.toThrow("30 seconds");
  3602. expect(
  3603. loadMarketplaceManifestSync(storageRoot, "claude-plugins-official")?.plugins[0]?.name,
  3604. ).toBe("cached");
  3605. expect(
  3606. loadKnownMarketplacesSync(storageRoot).find(
  3607. (record) => record.id === "claude-plugins-official",
  3608. ),
  3609. ).toMatchObject({
  3610. lastUpdated: "2026-01-02T00:00:00.000Z",
  3611. pluginCount: 1,
  3612. });
  3613. expect(
  3614. existsSync(join(storageRoot, "marketplaces", ".claude-plugins-official.transaction.json")),
  3615. ).toBe(false);
  3616. } finally {
  3617. await rm(dir, { force: true, recursive: true });
  3618. vi.useRealTimers();
  3619. }
  3620. });
  3621. it("fails Claude marketplace refresh after 30 seconds without blocking other markets", async () => {
  3622. vi.useFakeTimers();
  3623. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-claude-marketplace-timeout-"));
  3624. const storageRoot = join(dir, "storage");
  3625. const claudeSnapshot = join(storageRoot, "marketplaces", "claude-plugins-official");
  3626. const goodSource = join(dir, "good-source");
  3627. try {
  3628. await mkdir(claudeSnapshot, { recursive: true });
  3629. await writeFile(
  3630. join(claudeSnapshot, "marketplace.json"),
  3631. JSON.stringify({
  3632. name: "claude-plugins-official",
  3633. plugins: [{ name: "cached", source: "./cached" }],
  3634. }),
  3635. );
  3636. await writeMarketplaceManifest(goodSource, {
  3637. name: "good-market",
  3638. plugins: [{ name: "good-v2", source: "./good-v2" }],
  3639. });
  3640. await writeKnownMarketplaces(storageRoot, [
  3641. {
  3642. id: "claude-plugins-official",
  3643. source: { source: "github", repo: "anthropics/claude-plugins-official" },
  3644. name: "claude-plugins-official",
  3645. addedAt: "2026-01-01T00:00:00.000Z",
  3646. lastUpdated: "2026-01-02T00:00:00.000Z",
  3647. pluginCount: 1,
  3648. },
  3649. {
  3650. id: "good-market",
  3651. source: { source: "directory", path: goodSource },
  3652. name: "good-market",
  3653. addedAt: "2026-01-01T00:00:00.000Z",
  3654. lastUpdated: "2026-01-01T00:00:00.000Z",
  3655. pluginCount: 1,
  3656. },
  3657. {
  3658. id: "zcode-plugins-official",
  3659. source: {
  3660. source: "settings",
  3661. marketplace: {
  3662. name: "zcode-plugins-official",
  3663. plugins: [],
  3664. raw: { name: "zcode-plugins-official", plugins: [] },
  3665. },
  3666. },
  3667. name: "zcode-plugins-official",
  3668. addedAt: "2026-01-01T00:00:00.000Z",
  3669. pluginCount: 0,
  3670. },
  3671. ]);
  3672. vi.stubGlobal(
  3673. "fetch",
  3674. vi.fn(
  3675. (_input: RequestInfo | URL, init?: RequestInit) =>
  3676. new Promise<Response>((_resolve, reject) => {
  3677. const signal = init?.signal;
  3678. if (signal?.aborted) {
  3679. reject(signal.reason);
  3680. return;
  3681. }
  3682. signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
  3683. }),
  3684. ),
  3685. );
  3686. const refresh = updateMarketplace({ storageRoot });
  3687. for (let turn = 0; turn < 10 && vi.mocked(fetch).mock.calls.length === 0; turn += 1) {
  3688. await Promise.resolve();
  3689. await vi.advanceTimersByTimeAsync(0);
  3690. }
  3691. await vi.advanceTimersByTimeAsync(30_000);
  3692. const updated = await refresh;
  3693. expect(updated.map((record) => record.id)).toContain("good-market");
  3694. expect(updated.map((record) => record.id)).not.toContain("claude-plugins-official");
  3695. expect(
  3696. loadMarketplaceManifestSync(storageRoot, "claude-plugins-official")?.plugins[0]?.name,
  3697. ).toBe("cached");
  3698. expect(
  3699. loadKnownMarketplacesSync(storageRoot).find(
  3700. (record) => record.id === "claude-plugins-official",
  3701. )?.lastRefreshFailure,
  3702. ).toMatchObject({
  3703. code: "plugin_archive_fetch_failed",
  3704. message: expect.stringContaining("30 seconds"),
  3705. });
  3706. expect(loadMarketplaceManifestSync(storageRoot, "good-market")?.plugins[0]?.name).toBe(
  3707. "good-v2",
  3708. );
  3709. } finally {
  3710. await rm(dir, { force: true, recursive: true });
  3711. vi.useRealTimers();
  3712. }
  3713. });
  3714. it("keeps the active directory when atomic staging cannot copy the replacement", async () => {
  3715. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-atomic-directory-"));
  3716. const targetPath = join(dir, "active");
  3717. try {
  3718. await mkdir(targetPath, { recursive: true });
  3719. await writeFile(join(targetPath, "keep.txt"), "v1");
  3720. await expect(
  3721. replaceDirectoryAtomically({
  3722. sourcePath: join(dir, "missing-source"),
  3723. targetPath,
  3724. }),
  3725. ).rejects.toThrow();
  3726. expect(await readFile(join(targetPath, "keep.txt"), "utf8")).toBe("v1");
  3727. } finally {
  3728. await rm(dir, { force: true, recursive: true });
  3729. }
  3730. });
  3731. it("recovers state files and marketplace directories left in the atomic commit window", async () => {
  3732. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-atomic-recovery-"));
  3733. const storageRoot = join(dir, "storage");
  3734. const installedPath = join(storageRoot, "installed_plugins.json");
  3735. const marketplacePath = join(storageRoot, "marketplaces", "recover-market");
  3736. try {
  3737. await mkdir(marketplacePath, { recursive: true });
  3738. await writeFile(
  3739. installedPath,
  3740. JSON.stringify({
  3741. version: 1,
  3742. plugins: [
  3743. {
  3744. id: "recover-plugin@recover-market",
  3745. name: "recover-plugin",
  3746. marketplace: "recover-market",
  3747. version: "1.0.0",
  3748. installPath: join(storageRoot, "cache", "recover-market", "recover-plugin", "1.0.0"),
  3749. installedAt: "2026-01-01T00:00:00.000Z",
  3750. updatedAt: "2026-01-01T00:00:00.000Z",
  3751. scope: "user",
  3752. },
  3753. ],
  3754. }),
  3755. );
  3756. await writeFile(
  3757. join(marketplacePath, "marketplace.json"),
  3758. JSON.stringify({
  3759. name: "recover-market",
  3760. plugins: [{ name: "recover-plugin", source: "./recover-plugin" }],
  3761. }),
  3762. );
  3763. await rename(installedPath, join(storageRoot, ".installed_plugins.json.backup"));
  3764. await rename(marketplacePath, join(storageRoot, "marketplaces", ".recover-market.backup"));
  3765. expect(
  3766. (await listInstalledPluginRecordsAsync(storageRoot)).map((record) => record.id),
  3767. ).toEqual(["recover-plugin@recover-market"]);
  3768. expect(listInstalledPluginRecords(storageRoot).map((record) => record.id)).toEqual([
  3769. "recover-plugin@recover-market",
  3770. ]);
  3771. expect(loadMarketplaceManifestSync(storageRoot, "recover-market")?.name).toBe(
  3772. "recover-market",
  3773. );
  3774. expect(existsSync(installedPath)).toBe(true);
  3775. expect(existsSync(marketplacePath)).toBe(true);
  3776. } finally {
  3777. await rm(dir, { force: true, recursive: true });
  3778. }
  3779. });
  3780. it("does not let a normal read recover an active directory transaction", async () => {
  3781. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-atomic-active-read-"));
  3782. const authorityPath = join(dir, "installed_plugins.json");
  3783. const sourcePath = join(dir, "source");
  3784. const targetPath = join(dir, "active");
  3785. try {
  3786. await mkdir(sourcePath, { recursive: true });
  3787. await mkdir(targetPath, { recursive: true });
  3788. await writeFile(join(sourcePath, "version.txt"), "v2");
  3789. await writeFile(join(targetPath, "version.txt"), "v1");
  3790. await writeFile(authorityPath, JSON.stringify({ version: 1, plugins: [] }));
  3791. const activation = await activateDirectoryAtomically({
  3792. authorityPath,
  3793. sourcePath,
  3794. targetPath,
  3795. });
  3796. expect(
  3797. await readFile(join(await resolveAtomicReadPath(targetPath), "version.txt"), "utf8"),
  3798. ).toBe("v1");
  3799. const readablePath = recoverAtomicTargetSync(targetPath);
  3800. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v2");
  3801. expect(await readFile(join(readablePath, "version.txt"), "utf8")).toBe("v1");
  3802. expect(existsSync(join(dir, ".active.backup"))).toBe(true);
  3803. await activation.rollback();
  3804. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v1");
  3805. const committedActivation = await activateDirectoryAtomically({
  3806. authorityPath,
  3807. sourcePath,
  3808. targetPath,
  3809. });
  3810. await writeFile(
  3811. authorityPath,
  3812. JSON.stringify({
  3813. version: 1,
  3814. plugins: [{ cacheTransactionId: committedActivation.transactionId }],
  3815. }),
  3816. );
  3817. expect(await resolveAtomicReadPath(targetPath)).toBe(targetPath);
  3818. const committedReadablePath = recoverAtomicTargetSync(targetPath);
  3819. expect(await readFile(join(committedReadablePath, "version.txt"), "utf8")).toBe("v2");
  3820. expect(existsSync(join(dir, ".active.backup"))).toBe(true);
  3821. await committedActivation.finalize();
  3822. expect(existsSync(join(dir, ".active.backup"))).toBe(false);
  3823. } finally {
  3824. await rm(dir, { force: true, recursive: true });
  3825. }
  3826. });
  3827. it("rejects a concurrent activation for the same target without losing its rollback snapshot", async () => {
  3828. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-atomic-concurrent-target-"));
  3829. const authorityPath = join(dir, "installed_plugins.json");
  3830. const firstSourcePath = join(dir, "source-first");
  3831. const secondSourcePath = join(dir, "source-second");
  3832. const targetPath = join(dir, "active");
  3833. let firstActivation: Awaited<ReturnType<typeof activateDirectoryAtomically>> | undefined;
  3834. try {
  3835. await mkdir(firstSourcePath, { recursive: true });
  3836. await mkdir(secondSourcePath, { recursive: true });
  3837. await mkdir(targetPath, { recursive: true });
  3838. await writeFile(join(firstSourcePath, "version.txt"), "v2");
  3839. await writeFile(join(secondSourcePath, "version.txt"), "v3");
  3840. await writeFile(join(targetPath, "version.txt"), "v1");
  3841. await writeFile(authorityPath, JSON.stringify({ version: 1, plugins: [] }));
  3842. firstActivation = await activateDirectoryAtomically({
  3843. authorityPath,
  3844. sourcePath: firstSourcePath,
  3845. targetPath,
  3846. });
  3847. await expect(
  3848. activateDirectoryAtomically({
  3849. authorityPath,
  3850. sourcePath: secondSourcePath,
  3851. targetPath,
  3852. }),
  3853. ).rejects.toThrow("already active");
  3854. expect(
  3855. await readFile(join(await resolveAtomicReadPath(targetPath), "version.txt"), "utf8"),
  3856. ).toBe("v1");
  3857. const readablePath = recoverAtomicTargetSync(targetPath);
  3858. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v2");
  3859. expect(await readFile(join(readablePath, "version.txt"), "utf8")).toBe("v1");
  3860. expect(existsSync(join(dir, ".active.backup"))).toBe(true);
  3861. expect(existsSync(join(dir, ".active.transaction.json"))).toBe(true);
  3862. await firstActivation.rollback();
  3863. firstActivation = undefined;
  3864. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v1");
  3865. expect(existsSync(join(dir, ".active.backup"))).toBe(false);
  3866. expect(existsSync(join(dir, ".active.transaction.json"))).toBe(false);
  3867. } finally {
  3868. await firstActivation?.rollback().catch(() => {});
  3869. await rm(dir, { force: true, recursive: true });
  3870. }
  3871. });
  3872. it("does not overwrite an atomic transaction owned by another live process", async () => {
  3873. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-atomic-live-owner-"));
  3874. const sourcePath = join(dir, "source");
  3875. const targetPath = join(dir, "active");
  3876. const transactionPath = join(dir, ".active.transaction.json");
  3877. try {
  3878. await mkdir(sourcePath, { recursive: true });
  3879. await mkdir(targetPath, { recursive: true });
  3880. await writeFile(join(sourcePath, "version.txt"), "v2");
  3881. await writeFile(join(targetPath, "version.txt"), "v1");
  3882. await writeFile(
  3883. transactionPath,
  3884. JSON.stringify({
  3885. hadTarget: true,
  3886. mode: "standalone",
  3887. ownerId: "another-live-process",
  3888. ownerPid: process.ppid,
  3889. stageName: ".active.stage-other",
  3890. transactionId: "live-transaction",
  3891. version: 2,
  3892. }),
  3893. );
  3894. await expect(
  3895. activateDirectoryAtomically({
  3896. sourcePath,
  3897. targetPath,
  3898. }),
  3899. ).rejects.toThrow("already active");
  3900. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v1");
  3901. expect(JSON.parse(await readFile(transactionPath, "utf8"))).toMatchObject({
  3902. ownerId: "another-live-process",
  3903. transactionId: "live-transaction",
  3904. });
  3905. expect(existsSync(join(dir, ".active.backup"))).toBe(false);
  3906. } finally {
  3907. await rm(dir, { force: true, recursive: true });
  3908. }
  3909. });
  3910. it("recovers a coordinated directory according to the authority transaction generation", async () => {
  3911. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-atomic-generation-"));
  3912. const authorityPath = join(dir, "installed_plugins.json");
  3913. const targetPath = join(dir, "active");
  3914. const backupPath = join(dir, ".active.backup");
  3915. const transactionPath = join(dir, ".active.transaction.json");
  3916. const transactionId = "dead-transaction";
  3917. const writeTransaction = async (): Promise<void> => {
  3918. await writeFile(
  3919. transactionPath,
  3920. JSON.stringify({
  3921. authorityPath,
  3922. hadTarget: true,
  3923. mode: "coordinated",
  3924. ownerId: "dead-owner",
  3925. ownerPid: 999_999_999,
  3926. stageName: ".active.stage-dead",
  3927. transactionId,
  3928. version: 2,
  3929. }),
  3930. );
  3931. };
  3932. try {
  3933. await mkdir(targetPath, { recursive: true });
  3934. await mkdir(backupPath, { recursive: true });
  3935. await writeFile(join(targetPath, "version.txt"), "v2");
  3936. await writeFile(join(backupPath, "version.txt"), "v1");
  3937. await writeFile(authorityPath, JSON.stringify({ version: 1, plugins: [] }));
  3938. await writeTransaction();
  3939. // 已死亡事务:读取先按权威代际恢复,再返回稳定 target;未提交 → 回滚到 backup 的 v1。
  3940. expect(await resolveAtomicReadPath(targetPath)).toBe(targetPath);
  3941. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v1");
  3942. expect(existsSync(backupPath)).toBe(false);
  3943. expect(existsSync(transactionPath)).toBe(false);
  3944. await rm(targetPath, { force: true, recursive: true });
  3945. await mkdir(targetPath, { recursive: true });
  3946. await mkdir(backupPath, { recursive: true });
  3947. await writeFile(join(targetPath, "version.txt"), "v2");
  3948. await writeFile(join(backupPath, "version.txt"), "v1");
  3949. await writeFile(
  3950. authorityPath,
  3951. JSON.stringify({
  3952. version: 1,
  3953. plugins: [{ cacheTransactionId: transactionId }],
  3954. }),
  3955. );
  3956. await writeTransaction();
  3957. // 已提交 → 保留 target 的 v2,清理 backup。
  3958. expect(await resolveAtomicReadPath(targetPath)).toBe(targetPath);
  3959. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v2");
  3960. expect(existsSync(backupPath)).toBe(false);
  3961. recoverAtomicTargetSync(targetPath);
  3962. expect(await readFile(join(targetPath, "version.txt"), "utf8")).toBe("v2");
  3963. expect(existsSync(backupPath)).toBe(false);
  3964. } finally {
  3965. await rm(dir, { force: true, recursive: true });
  3966. }
  3967. });
  3968. it("rolls back earlier dependency cache activations when a later dependency install fails", async () => {
  3969. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-install-transaction-rollback-"));
  3970. const storageRoot = join(dir, "storage");
  3971. const marketplaceRoot = join(dir, "marketplace");
  3972. const rootSource = join(dir, "root-source");
  3973. const goodSource = join(dir, "good-source");
  3974. const badSource = join(dir, "bad-source");
  3975. try {
  3976. await writePluginManifest(rootSource, { name: "root", version: "1.0.0" }, ".claude-plugin");
  3977. await writePluginManifest(goodSource, { name: "good", version: "1.0.0" }, ".claude-plugin");
  3978. await writePluginManifest(badSource, { name: "bad", version: "1.0.0" }, ".claude-plugin");
  3979. await writeFile(join(goodSource, "marker.txt"), "v1");
  3980. await writeMarketplaceManifest(marketplaceRoot, {
  3981. name: "transaction-market",
  3982. plugins: [
  3983. {
  3984. name: "root",
  3985. dependencies: ["good", "bad"],
  3986. source: { source: "directory", path: rootSource },
  3987. },
  3988. { name: "good", source: { source: "directory", path: goodSource } },
  3989. { name: "bad", source: { source: "directory", path: badSource } },
  3990. ],
  3991. });
  3992. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  3993. await installMarketplacePlugin({
  3994. marketplace: "transaction-market",
  3995. name: "root",
  3996. storageRoot,
  3997. });
  3998. const goodRecord = listInstalledPluginRecords(storageRoot).find(
  3999. (record) => record.id === "good@transaction-market",
  4000. );
  4001. expect(await readFile(join(goodRecord?.installPath ?? "", "marker.txt"), "utf8")).toBe("v1");
  4002. await writeFile(join(goodSource, "marker.txt"), "v2");
  4003. await rm(badSource, { force: true, recursive: true });
  4004. await expect(
  4005. installMarketplacePlugin({
  4006. marketplace: "transaction-market",
  4007. name: "root",
  4008. storageRoot,
  4009. }),
  4010. ).rejects.toThrow(/does not exist/u);
  4011. expect(await readFile(join(goodRecord?.installPath ?? "", "marker.txt"), "utf8")).toBe("v1");
  4012. expect(
  4013. listInstalledPluginRecords(storageRoot).find(
  4014. (record) => record.id === "good@transaction-market",
  4015. ),
  4016. ).toEqual(goodRecord);
  4017. } finally {
  4018. await rm(dir, { force: true, recursive: true });
  4019. }
  4020. });
  4021. it("discovers an installed cache offline without system Git or source network access", async () => {
  4022. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-offline-installed-cache-"));
  4023. const storageRoot = join(dir, "storage");
  4024. const marketplaceRoot = join(dir, "marketplace");
  4025. const pluginRoot = join(marketplaceRoot, "plugins", "offline-plugin");
  4026. try {
  4027. await writeMarketplaceManifest(marketplaceRoot, {
  4028. name: "offline-cache-market",
  4029. plugins: [{ name: "offline-plugin", source: "./plugins/offline-plugin" }],
  4030. });
  4031. await writePluginManifest(
  4032. pluginRoot,
  4033. { name: "offline-plugin", skills: "skills", version: "1.0.0" },
  4034. ".claude-plugin",
  4035. );
  4036. await mkdir(join(pluginRoot, "skills", "offline"), { recursive: true });
  4037. await writeFile(join(pluginRoot, "skills", "offline", "SKILL.md"), "# offline");
  4038. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  4039. await installMarketplacePlugin({
  4040. marketplace: "offline-cache-market",
  4041. name: "offline-plugin",
  4042. storageRoot,
  4043. });
  4044. vi.stubEnv("PATH", join(dir, "no-system-git"));
  4045. vi.stubGlobal(
  4046. "fetch",
  4047. vi.fn(async () => Promise.reject(new Error("offline"))),
  4048. );
  4049. const outcome = await discoverNodePlugins({
  4050. config: {
  4051. dirs: [],
  4052. enabled: true,
  4053. enabledPlugins: { "offline-plugin@offline-cache-market": true },
  4054. options: {},
  4055. },
  4056. env: {},
  4057. storageRoot,
  4058. workingDirectory: dir,
  4059. });
  4060. expect(outcome.plugins).toContainEqual(
  4061. expect.objectContaining({
  4062. id: "offline-plugin@offline-cache-market",
  4063. source: "cache",
  4064. }),
  4065. );
  4066. expect(outcome.skillRoots).toContainEqual(
  4067. expect.objectContaining({ path: expect.stringContaining(join("offline-plugin", "1.0.0")) }),
  4068. );
  4069. } finally {
  4070. await rm(dir, { force: true, recursive: true });
  4071. }
  4072. });
  4073. it("recovers a crashed cache replacement before discovery publishes runtime paths", async () => {
  4074. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-crashed-cache-discovery-"));
  4075. const storageRoot = join(dir, "storage");
  4076. const marketplaceRoot = join(dir, "marketplace");
  4077. const pluginRoot = join(marketplaceRoot, "plugins", "crash-plugin");
  4078. const config = {
  4079. dirs: [],
  4080. enabled: true,
  4081. enabledPlugins: { "crash-plugin@crash-market": true },
  4082. options: {},
  4083. };
  4084. try {
  4085. await writeMarketplaceManifest(marketplaceRoot, {
  4086. name: "crash-market",
  4087. plugins: [{ name: "crash-plugin", source: "./plugins/crash-plugin" }],
  4088. });
  4089. await writePluginManifest(
  4090. pluginRoot,
  4091. { hooks: "hooks/hooks.json", name: "crash-plugin", skills: "skills", version: "1.0.0" },
  4092. ".claude-plugin",
  4093. );
  4094. await mkdir(join(pluginRoot, "skills", "crash"), { recursive: true });
  4095. await mkdir(join(pluginRoot, "hooks"), { recursive: true });
  4096. await writeFile(join(pluginRoot, "skills", "crash", "SKILL.md"), "# crash");
  4097. await writeFile(join(pluginRoot, "hooks", "session-start"), "echo start");
  4098. await writeFile(
  4099. join(pluginRoot, "hooks", "hooks.json"),
  4100. JSON.stringify({
  4101. hooks: {
  4102. SessionStart: [
  4103. {
  4104. hooks: [
  4105. { command: '"${CLAUDE_PLUGIN_ROOT}/hooks/session-start"', type: "command" },
  4106. ],
  4107. },
  4108. ],
  4109. },
  4110. }),
  4111. );
  4112. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  4113. await installMarketplacePlugin({
  4114. marketplace: "crash-market",
  4115. name: "crash-plugin",
  4116. storageRoot,
  4117. });
  4118. const [record] = listInstalledPluginRecords(storageRoot);
  4119. const cachePath = record!.installPath!;
  4120. const cacheParent = join(cachePath, "..");
  4121. const backupPath = join(cacheParent, ".1.0.0.backup");
  4122. // 模拟替换在 target→backup 之后、staging→target 之前崩溃:target 缺失,只剩 backup 和死亡 owner 的 marker。
  4123. await rename(cachePath, backupPath);
  4124. await writeFile(
  4125. join(cacheParent, ".1.0.0.transaction.json"),
  4126. JSON.stringify({
  4127. hadTarget: true,
  4128. mode: "standalone",
  4129. ownerId: "dead-owner",
  4130. ownerPid: 999_999_999,
  4131. stageName: ".1.0.0.stage-dead",
  4132. transactionId: "dead-transaction",
  4133. version: 2,
  4134. }),
  4135. );
  4136. const outcome = await discoverNodePlugins({
  4137. config,
  4138. env: {},
  4139. storageRoot,
  4140. workingDirectory: dir,
  4141. });
  4142. // 发布给会话的是稳定 target,而不是会被后续恢复改名走的 backup。
  4143. const skillRoot = outcome.skillRoots.find((root) => root.path.includes("crash-plugin"));
  4144. expect(skillRoot?.path).toBe(join(cachePath, "skills"));
  4145. const hook = outcome.hooks.SessionStart?.[0]?.hooks[0];
  4146. expect(hook).toMatchObject({ plugin: { rootPath: cachePath } });
  4147. expect(existsSync(backupPath)).toBe(false);
  4148. expect(existsSync(join(cacheParent, ".1.0.0.transaction.json"))).toBe(false);
  4149. // 会话持有路径期间打开详情,不能再把会话正在用的目录移走。
  4150. await describeMarketplacePlugin({
  4151. marketplace: "crash-market",
  4152. name: "crash-plugin",
  4153. storageRoot,
  4154. });
  4155. expect(await readFile(join(skillRoot!.path, "crash", "SKILL.md"), "utf8")).toBe("# crash");
  4156. expect(
  4157. await readFile(
  4158. join(
  4159. (hook as { plugin: { rootPath: string } }).plugin.rootPath,
  4160. "hooks",
  4161. "session-start",
  4162. ),
  4163. "utf8",
  4164. ),
  4165. ).toBe("echo start");
  4166. } finally {
  4167. await rm(dir, { force: true, recursive: true });
  4168. }
  4169. });
  4170. it("keeps reading the committed generation of a live replacement during discovery", async () => {
  4171. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-live-cache-discovery-"));
  4172. const storageRoot = join(dir, "storage");
  4173. const marketplaceRoot = join(dir, "marketplace");
  4174. const pluginRoot = join(marketplaceRoot, "plugins", "live-plugin");
  4175. const nextSource = join(dir, "next-source");
  4176. let activation: Awaited<ReturnType<typeof activateDirectoryAtomically>> | undefined;
  4177. try {
  4178. await writeMarketplaceManifest(marketplaceRoot, {
  4179. name: "live-market",
  4180. plugins: [{ name: "live-plugin", source: "./plugins/live-plugin" }],
  4181. });
  4182. await writePluginManifest(
  4183. pluginRoot,
  4184. { name: "live-plugin", skills: "skills", version: "1.0.0" },
  4185. ".claude-plugin",
  4186. );
  4187. await mkdir(join(pluginRoot, "skills", "live"), { recursive: true });
  4188. await writeFile(join(pluginRoot, "skills", "live", "SKILL.md"), "# v1");
  4189. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  4190. await installMarketplacePlugin({
  4191. marketplace: "live-market",
  4192. name: "live-plugin",
  4193. storageRoot,
  4194. });
  4195. const [record] = listInstalledPluginRecords(storageRoot);
  4196. const cachePath = record!.installPath!;
  4197. await cp(cachePath, nextSource, { recursive: true });
  4198. await writeFile(join(nextSource, "skills", "live", "SKILL.md"), "# v2");
  4199. // 同进程 writer 已激活但未 finalize:读者不能接管它的 backup。
  4200. activation = await activateDirectoryAtomically({
  4201. sourcePath: nextSource,
  4202. targetPath: cachePath,
  4203. });
  4204. const outcome = await discoverNodePlugins({
  4205. config: {
  4206. dirs: [],
  4207. enabled: true,
  4208. enabledPlugins: { "live-plugin@live-market": true },
  4209. options: {},
  4210. },
  4211. env: {},
  4212. storageRoot,
  4213. workingDirectory: dir,
  4214. });
  4215. const backupPath = join(cachePath, "..", ".1.0.0.backup");
  4216. const skillRoot = outcome.skillRoots.find((root) => root.path.includes("live-plugin"));
  4217. expect(skillRoot?.path).toBe(join(backupPath, "skills"));
  4218. expect(existsSync(backupPath)).toBe(true);
  4219. await activation.rollback();
  4220. activation = undefined;
  4221. expect(await readFile(join(cachePath, "skills", "live", "SKILL.md"), "utf8")).toBe("# v1");
  4222. } finally {
  4223. await activation?.rollback().catch(() => {});
  4224. await rm(dir, { force: true, recursive: true });
  4225. }
  4226. });
  4227. it("materializes Claude command object mappings into custom command roots", async () => {
  4228. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-command-metadata-"));
  4229. const pluginRoot = join(dir, "commands-plugin");
  4230. try {
  4231. await writePluginManifest(pluginRoot, {
  4232. commands: {
  4233. "from-file": {
  4234. argumentHint: "[topic]",
  4235. description: "Generated from a source file",
  4236. source: "./extra-command.md",
  4237. },
  4238. inline: {
  4239. allowedTools: ["Bash", "Read"],
  4240. content: "# Inline command\n\nRun the inline command.",
  4241. description: "Generated from inline content",
  4242. },
  4243. },
  4244. name: "commands-plugin",
  4245. });
  4246. await writeFile(
  4247. join(pluginRoot, "extra-command.md"),
  4248. "# Source command\n\nRun the source command.",
  4249. );
  4250. const outcome = await createNodePluginAdapter({
  4251. storageRoot: join(dir, "plugins"),
  4252. }).discoverPlugins({
  4253. config: {
  4254. dirs: [pluginRoot],
  4255. enabled: true,
  4256. enabledPlugins: {},
  4257. options: {},
  4258. },
  4259. env: {},
  4260. storageRoot: join(dir, "plugins"),
  4261. workingDirectory: dir,
  4262. });
  4263. const commands = await createNodeCustomCommandAdapter().discoverCommands({
  4264. roots: outcome.commandRoots,
  4265. workingDirectory: dir,
  4266. });
  4267. expect(commands.commands.map((command) => command.name)).toEqual(["from-file", "inline"]);
  4268. expect(commands.commands.find((command) => command.name === "from-file")).toMatchObject({
  4269. argumentHint: "[topic]",
  4270. description: "Generated from a source file",
  4271. });
  4272. expect(commands.commands.find((command) => command.name === "inline")).toMatchObject({
  4273. allowedTools: ["Bash", "Read"],
  4274. description: "Generated from inline content",
  4275. });
  4276. } finally {
  4277. await rm(dir, { force: true, recursive: true });
  4278. }
  4279. });
  4280. it("dry-runs marketplace source validation against real plugin manifests", async () => {
  4281. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-dry-run-"));
  4282. const storageRoot = join(dir, "storage");
  4283. const marketplaceRoot = join(dir, "marketplace");
  4284. const pluginRoot = join(marketplaceRoot, "plugins", "risky");
  4285. try {
  4286. await writeMarketplaceManifest(marketplaceRoot, {
  4287. name: "dry-run-market",
  4288. plugins: [
  4289. {
  4290. name: "risky",
  4291. source: "./plugins/risky",
  4292. },
  4293. ],
  4294. });
  4295. await writePluginManifest(
  4296. pluginRoot,
  4297. {
  4298. agents: "./agents/risky.md",
  4299. hooks: "./hooks/hooks.json",
  4300. mcpServers: {
  4301. risky: {
  4302. command: "node",
  4303. env: {
  4304. TOKEN: "${ZCODE_MISSING_TOKEN}",
  4305. },
  4306. },
  4307. },
  4308. name: "risky",
  4309. userConfig: {
  4310. api_key: {
  4311. sensitive: true,
  4312. type: "string",
  4313. },
  4314. },
  4315. },
  4316. ".claude-plugin",
  4317. );
  4318. const diagnostics = await validateMarketplaceSource({
  4319. source: { source: "directory", path: marketplaceRoot },
  4320. storageRoot,
  4321. });
  4322. expect(diagnostics).toContainEqual(
  4323. expect.objectContaining({
  4324. code: "plugin_variable_missing",
  4325. pluginId: "risky@dry-run-market",
  4326. }),
  4327. );
  4328. expect(listInstalledPluginRecords(storageRoot)).toEqual([]);
  4329. } finally {
  4330. await rm(dir, { force: true, recursive: true });
  4331. }
  4332. });
  4333. it("defers remote plugin roots while validating marketplace sources", async () => {
  4334. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-remote-dry-run-"));
  4335. const storageRoot = join(dir, "storage");
  4336. const marketplaceRoot = join(dir, "marketplace");
  4337. const localRoot = join(marketplaceRoot, "plugins", "local-risky");
  4338. try {
  4339. await writeMarketplaceManifest(marketplaceRoot, {
  4340. name: "official-like",
  4341. plugins: [
  4342. {
  4343. name: "remote-git-subdir",
  4344. source: {
  4345. source: "git-subdir",
  4346. url: join(dir, "missing-remote.git"),
  4347. path: "plugins/remote-git-subdir",
  4348. sha: "abc123",
  4349. },
  4350. },
  4351. {
  4352. name: "local-risky",
  4353. source: "./plugins/local-risky",
  4354. },
  4355. ],
  4356. });
  4357. await writePluginManifest(
  4358. localRoot,
  4359. {
  4360. hooks: "hooks/hooks.json",
  4361. name: "local-risky",
  4362. },
  4363. ".claude-plugin",
  4364. );
  4365. const diagnostics = await validateMarketplaceSource({
  4366. source: { source: "directory", path: marketplaceRoot },
  4367. storageRoot,
  4368. });
  4369. expect(diagnostics).toContainEqual(
  4370. expect.objectContaining({
  4371. code: "plugin_validation_deferred",
  4372. pluginId: "remote-git-subdir@official-like",
  4373. severity: "warning",
  4374. }),
  4375. );
  4376. expect(diagnostics).not.toContainEqual(
  4377. expect.objectContaining({
  4378. code: "plugin_unsupported_component",
  4379. pluginId: "local-risky@official-like",
  4380. }),
  4381. );
  4382. expect(diagnostics).not.toContainEqual(
  4383. expect.objectContaining({
  4384. code: "plugin_marketplace_invalid",
  4385. pluginId: "remote-git-subdir@official-like",
  4386. }),
  4387. );
  4388. } finally {
  4389. await rm(dir, { force: true, recursive: true });
  4390. }
  4391. });
  4392. it("runs Marketplace cache hooks from third-party marketplaces when enabled", async () => {
  4393. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-hooks-"));
  4394. const storageRoot = join(dir, "storage");
  4395. const marketplaceRoot = join(dir, "marketplace");
  4396. const pluginRoot = join(marketplaceRoot, "plugins", "hooked");
  4397. try {
  4398. await writeMarketplaceManifest(marketplaceRoot, {
  4399. name: "hook-market",
  4400. plugins: [
  4401. {
  4402. name: "hooked",
  4403. source: "./plugins/hooked",
  4404. },
  4405. ],
  4406. });
  4407. await writePluginManifest(
  4408. pluginRoot,
  4409. {
  4410. hooks: "hooks/hooks.json",
  4411. name: "hooked",
  4412. },
  4413. ".claude-plugin",
  4414. );
  4415. await mkdir(join(pluginRoot, "hooks"), { recursive: true });
  4416. await writeFile(
  4417. join(pluginRoot, "hooks", "hooks.json"),
  4418. JSON.stringify({
  4419. hooks: {
  4420. SessionStart: [
  4421. {
  4422. hooks: [{ command: "echo hooked", type: "command" }],
  4423. },
  4424. ],
  4425. },
  4426. }),
  4427. );
  4428. await addMarketplace({ source: { source: "directory", path: marketplaceRoot }, storageRoot });
  4429. await installMarketplacePlugin({ marketplace: "hook-market", name: "hooked", storageRoot });
  4430. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  4431. config: {
  4432. dirs: [],
  4433. enabled: true,
  4434. enabledPlugins: {
  4435. "hooked@hook-market": true,
  4436. },
  4437. options: {},
  4438. },
  4439. env: {},
  4440. storageRoot,
  4441. workingDirectory: dir,
  4442. });
  4443. // 三方 marketplace 插件 hook 现在默认放行(与内置/官方一致)。
  4444. expect(outcome.hooks.SessionStart).toBeDefined();
  4445. expect(outcome.plugins[0]?.hookDetails).toMatchObject([
  4446. {
  4447. command: "echo hooked",
  4448. event: "SessionStart",
  4449. runnable: true,
  4450. type: "command",
  4451. },
  4452. ]);
  4453. expect(outcome.diagnostics).not.toContainEqual(
  4454. expect.objectContaining({
  4455. code: "plugin_unsupported_component",
  4456. pluginId: "hooked@hook-market",
  4457. }),
  4458. );
  4459. } finally {
  4460. await rm(dir, { force: true, recursive: true });
  4461. }
  4462. });
  4463. it("runs hooks from official Claude marketplace cache plugins when enabled", async () => {
  4464. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-marketplace-official-hooks-"));
  4465. const storageRoot = join(dir, "storage");
  4466. const marketplaceRoot = join(dir, "marketplace");
  4467. const pluginRoot = join(marketplaceRoot, "plugins", "hookify");
  4468. try {
  4469. await writeMarketplaceManifest(marketplaceRoot, {
  4470. name: "claude-plugins-official",
  4471. plugins: [
  4472. {
  4473. name: "hookify",
  4474. source: "./plugins/hookify",
  4475. },
  4476. ],
  4477. });
  4478. await writePluginManifest(pluginRoot, { name: "hookify" }, ".claude-plugin");
  4479. await mkdir(join(pluginRoot, "hooks"), { recursive: true });
  4480. await writeFile(
  4481. join(pluginRoot, "hooks", "hooks.json"),
  4482. JSON.stringify({
  4483. hooks: {
  4484. PreToolUse: [
  4485. {
  4486. hooks: [
  4487. {
  4488. command: 'python3 "${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.py"',
  4489. type: "command",
  4490. },
  4491. ],
  4492. },
  4493. ],
  4494. },
  4495. }),
  4496. );
  4497. await addMarketplace({
  4498. source: { source: "directory", path: marketplaceRoot },
  4499. storageRoot,
  4500. trustedId: "claude-plugins-official",
  4501. });
  4502. await installMarketplacePlugin({
  4503. marketplace: "claude-plugins-official",
  4504. name: "hookify",
  4505. storageRoot,
  4506. });
  4507. const outcome = await createNodePluginAdapter({ storageRoot }).discoverPlugins({
  4508. config: {
  4509. dirs: [],
  4510. enabled: true,
  4511. enabledPlugins: {
  4512. "hookify@claude-plugins-official": true,
  4513. },
  4514. options: {},
  4515. },
  4516. env: {},
  4517. storageRoot,
  4518. workingDirectory: dir,
  4519. });
  4520. expect(outcome.hooks.PreToolUse?.[0]?.hooks[0]).toMatchObject({
  4521. command: 'python3 "${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.py"',
  4522. plugin: {
  4523. id: "hookify@claude-plugins-official",
  4524. rootPath: expect.stringContaining(join("hookify", "0.0.0")),
  4525. },
  4526. type: "command",
  4527. });
  4528. expect(outcome.plugins[0]?.hookDetails).toMatchObject([
  4529. {
  4530. command: 'python3 "${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.py"',
  4531. event: "PreToolUse",
  4532. runnable: true,
  4533. type: "command",
  4534. },
  4535. ]);
  4536. expect(outcome.diagnostics).not.toContainEqual(
  4537. expect.objectContaining({
  4538. code: "plugin_unsupported_component",
  4539. pluginId: "hookify@claude-plugins-official",
  4540. }),
  4541. );
  4542. } finally {
  4543. await rm(dir, { force: true, recursive: true });
  4544. }
  4545. });
  4546. it("disables an MCP server when a required ZCODE variable is missing", async () => {
  4547. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-env-"));
  4548. const pluginRoot = join(dir, "env-plugin");
  4549. try {
  4550. await writePluginManifest(pluginRoot, {
  4551. mcpServers: {
  4552. local: {
  4553. command: "node",
  4554. env: {
  4555. TOKEN: "${ZCODE_PLUGIN_TOKEN}",
  4556. },
  4557. },
  4558. },
  4559. name: "env-plugin",
  4560. });
  4561. const outcome = await createNodePluginAdapter({
  4562. storageRoot: join(dir, "plugins"),
  4563. }).discoverPlugins({
  4564. config: {
  4565. dirs: [pluginRoot],
  4566. enabled: true,
  4567. enabledPlugins: {},
  4568. options: {},
  4569. },
  4570. env: {},
  4571. storageRoot: join(dir, "plugins"),
  4572. workingDirectory: dir,
  4573. });
  4574. expect(outcome.mcpServers).toEqual({});
  4575. expect(outcome.plugins[0]?.declaredMcpServerNames).toEqual(["local"]);
  4576. expect(outcome.diagnostics.map((diagnostic) => diagnostic.code)).toContain(
  4577. "plugin_variable_missing",
  4578. );
  4579. } finally {
  4580. await rm(dir, { force: true, recursive: true });
  4581. }
  4582. });
  4583. it("expands arbitrary process environment variables only in MCP secret sinks", async () => {
  4584. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-secret-env-"));
  4585. const pluginRoot = join(dir, "secret-env-plugin");
  4586. try {
  4587. await writePluginManifest(pluginRoot, {
  4588. mcpServers: {
  4589. local: {
  4590. command: "node",
  4591. args: ["${TOKEN_PLAN_API_TOKEN}"],
  4592. env: {
  4593. AUTHORIZATION: "Bearer ${TOKEN_PLAN_API_TOKEN}",
  4594. },
  4595. },
  4596. remote: {
  4597. type: "http",
  4598. url: "https://mcp.example.test/${TOKEN_PLAN_API_TOKEN}",
  4599. headers: {
  4600. Authorization: "Bearer ${TOKEN_PLAN_API_TOKEN}",
  4601. },
  4602. },
  4603. },
  4604. name: "secret-env-plugin",
  4605. });
  4606. const outcome = await createNodePluginAdapter({
  4607. storageRoot: join(dir, "plugins"),
  4608. }).discoverPlugins({
  4609. config: {
  4610. dirs: [pluginRoot],
  4611. enabled: true,
  4612. enabledPlugins: {},
  4613. options: {},
  4614. },
  4615. env: {
  4616. TOKEN_PLAN_API_TOKEN: "secret-from-process-env",
  4617. },
  4618. storageRoot: join(dir, "plugins"),
  4619. workingDirectory: dir,
  4620. });
  4621. expect(outcome.mcpServers["plugin:secret-env-plugin:local"]).toMatchObject({
  4622. args: ["${TOKEN_PLAN_API_TOKEN}"],
  4623. env: {
  4624. AUTHORIZATION: "Bearer secret-from-process-env",
  4625. },
  4626. });
  4627. expect(outcome.mcpServers["plugin:secret-env-plugin:remote"]).toMatchObject({
  4628. headers: {
  4629. Authorization: "Bearer secret-from-process-env",
  4630. },
  4631. url: "https://mcp.example.test/${TOKEN_PLAN_API_TOKEN}",
  4632. });
  4633. expect(outcome.diagnostics).not.toContainEqual(
  4634. expect.objectContaining({ code: "plugin_variable_missing" }),
  4635. );
  4636. } finally {
  4637. await rm(dir, { force: true, recursive: true });
  4638. }
  4639. });
  4640. it("disables an MCP server when an arbitrary secret environment variable is missing", async () => {
  4641. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-secret-env-"));
  4642. const pluginRoot = join(dir, "missing-secret-env-plugin");
  4643. try {
  4644. await writePluginManifest(pluginRoot, {
  4645. mcpServers: {
  4646. local: {
  4647. command: "node",
  4648. env: {
  4649. TOKEN: "${TOKEN_PLAN_API_TOKEN}",
  4650. },
  4651. },
  4652. },
  4653. name: "missing-secret-env-plugin",
  4654. });
  4655. const outcome = await createNodePluginAdapter({
  4656. storageRoot: join(dir, "plugins"),
  4657. }).discoverPlugins({
  4658. config: {
  4659. dirs: [pluginRoot],
  4660. enabled: true,
  4661. enabledPlugins: {},
  4662. options: {},
  4663. },
  4664. env: {},
  4665. storageRoot: join(dir, "plugins"),
  4666. workingDirectory: dir,
  4667. });
  4668. expect(outcome.mcpServers).toEqual({});
  4669. expect(outcome.diagnostics).toContainEqual(
  4670. expect.objectContaining({
  4671. code: "plugin_variable_missing",
  4672. message: "Missing environment variable: TOKEN_PLAN_API_TOKEN",
  4673. }),
  4674. );
  4675. } finally {
  4676. await rm(dir, { force: true, recursive: true });
  4677. }
  4678. });
  4679. it("diagnoses MCP variables that require unavailable runtime contexts", async () => {
  4680. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-missing-context-"));
  4681. const pluginRoot = join(dir, "missing-context-plugin");
  4682. try {
  4683. await writePluginManifest(pluginRoot, {
  4684. mcpServers: {
  4685. skillContext: {
  4686. command: "node",
  4687. args: ["${CLAUDE_SKILL_DIR}/server.js"],
  4688. },
  4689. sessionContext: {
  4690. command: "node",
  4691. env: {
  4692. SESSION_ID: "${CLAUDE_SESSION_ID}",
  4693. },
  4694. },
  4695. },
  4696. name: "missing-context-plugin",
  4697. });
  4698. const outcome = await createNodePluginAdapter({
  4699. storageRoot: join(dir, "plugins"),
  4700. }).discoverPlugins({
  4701. config: {
  4702. dirs: [pluginRoot],
  4703. enabled: true,
  4704. enabledPlugins: {},
  4705. options: {},
  4706. },
  4707. env: {},
  4708. storageRoot: join(dir, "plugins"),
  4709. workingDirectory: dir,
  4710. });
  4711. expect(outcome.mcpServers).toEqual({});
  4712. expect(outcome.diagnostics).toEqual(
  4713. expect.arrayContaining([
  4714. expect.objectContaining({
  4715. code: "plugin_variable_missing",
  4716. message: "Plugin variable requires a skill context: CLAUDE_SKILL_DIR",
  4717. }),
  4718. expect.objectContaining({
  4719. code: "plugin_variable_missing",
  4720. message: "Plugin variable requires a runtime session context: CLAUDE_SESSION_ID",
  4721. }),
  4722. ]),
  4723. );
  4724. } finally {
  4725. await rm(dir, { force: true, recursive: true });
  4726. }
  4727. });
  4728. it("loads plugins that only provide a Claude manifest", async () => {
  4729. const dir = await mkdtemp(join(tmpdir(), "zcode-claude-plugin-"));
  4730. const pluginRoot = join(dir, "claude-only");
  4731. try {
  4732. await writePluginManifest(pluginRoot, { name: "claude-only" }, ".claude-plugin");
  4733. await mkdir(join(pluginRoot, "skills", "claude-only"), { recursive: true });
  4734. await writeFile(join(pluginRoot, "skills", "claude-only", "SKILL.md"), "# skill");
  4735. const outcome = await createNodePluginAdapter({
  4736. storageRoot: join(dir, "plugins"),
  4737. }).discoverPlugins({
  4738. config: {
  4739. dirs: [pluginRoot],
  4740. enabled: true,
  4741. enabledPlugins: {},
  4742. options: {},
  4743. },
  4744. env: {},
  4745. storageRoot: join(dir, "plugins"),
  4746. workingDirectory: dir,
  4747. });
  4748. expect(outcome.plugins[0]?.id).toBe("claude-only@inline");
  4749. expect(outcome.plugins[0]?.manifestPath).toBe(
  4750. join(pluginRoot, ".claude-plugin", "plugin.json"),
  4751. );
  4752. expect(outcome.skillRoots[0]?.path).toBe(join(pluginRoot, "skills"));
  4753. } finally {
  4754. await rm(dir, { force: true, recursive: true });
  4755. }
  4756. });
  4757. it("prefers Claude manifest over Codex manifest when no ZCode manifest exists", async () => {
  4758. const dir = await mkdtemp(join(tmpdir(), "zcode-codex-plugin-"));
  4759. const pluginRoot = join(dir, "multi-manifest");
  4760. try {
  4761. await writePluginManifest(pluginRoot, { name: "codex-name" }, ".codex-plugin");
  4762. await writePluginManifest(pluginRoot, { name: "claude-name" }, ".claude-plugin");
  4763. const outcome = await createNodePluginAdapter({
  4764. storageRoot: join(dir, "plugins"),
  4765. }).discoverPlugins({
  4766. config: {
  4767. dirs: [pluginRoot],
  4768. enabled: true,
  4769. enabledPlugins: {},
  4770. options: {},
  4771. },
  4772. env: {},
  4773. storageRoot: join(dir, "plugins"),
  4774. workingDirectory: dir,
  4775. });
  4776. expect(outcome.plugins[0]?.id).toBe("claude-name@inline");
  4777. expect(outcome.plugins[0]?.manifestPath).toBe(
  4778. join(pluginRoot, ".claude-plugin", "plugin.json"),
  4779. );
  4780. } finally {
  4781. await rm(dir, { force: true, recursive: true });
  4782. }
  4783. });
  4784. it("removes the record, cache, and data directory on thorough uninstall", async () => {
  4785. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-uninstall-"));
  4786. const storageRoot = join(dir, "storage");
  4787. const marketplaceRoot = join(dir, "marketplace");
  4788. const pluginRoot = join(marketplaceRoot, "plugins", "hello");
  4789. try {
  4790. await writeKnownMarketplaces(storageRoot, [
  4791. {
  4792. id: "uninstall-market",
  4793. source: { source: "directory", path: marketplaceRoot },
  4794. name: "uninstall-market",
  4795. addedAt: "2026-01-01T00:00:00.000Z",
  4796. pluginCount: 0,
  4797. },
  4798. ]);
  4799. await writeMarketplaceManifest(marketplaceRoot, {
  4800. name: "uninstall-market",
  4801. plugins: [{ name: "hello", source: "./plugins/hello" }],
  4802. });
  4803. await writePluginManifest(pluginRoot, { name: "hello", skills: "skills" }, ".claude-plugin");
  4804. await mkdir(join(pluginRoot, "skills", "hello"), { recursive: true });
  4805. await writeFile(join(pluginRoot, "skills", "hello", "SKILL.md"), "# hello");
  4806. const install = await installMarketplacePlugin({
  4807. marketplace: "uninstall-market",
  4808. name: "hello",
  4809. storageRoot,
  4810. });
  4811. const record = install.installed[0];
  4812. expect(record?.id).toBe("hello@uninstall-market");
  4813. const installPath = record?.installPath ?? "";
  4814. // 模拟运行期产生的 per-plugin data 目录(含 generated-commands)。
  4815. const dataDir = join(storageRoot, "data", "hello@uninstall-market");
  4816. await mkdir(join(dataDir, "generated-commands"), { recursive: true });
  4817. await writeFile(join(dataDir, "generated-commands", "demo.md"), "# demo");
  4818. expect(existsSync(installPath)).toBe(true);
  4819. expect(existsSync(dataDir)).toBe(true);
  4820. const removed = await uninstallMarketplacePlugin({
  4821. pluginId: "hello@uninstall-market",
  4822. removeCache: true,
  4823. storageRoot,
  4824. });
  4825. expect(removed?.id).toBe("hello@uninstall-market");
  4826. expect(listInstalledPluginRecords(storageRoot)).toHaveLength(0);
  4827. expect(existsSync(installPath)).toBe(false);
  4828. expect(existsSync(dataDir)).toBe(false);
  4829. } finally {
  4830. await rm(dir, { force: true, recursive: true });
  4831. }
  4832. });
  4833. it("returns null and keeps state when uninstalling an unknown plugin id", async () => {
  4834. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-uninstall-missing-"));
  4835. const storageRoot = join(dir, "storage");
  4836. try {
  4837. const removed = await uninstallMarketplacePlugin({
  4838. pluginId: "missing@nowhere",
  4839. removeCache: true,
  4840. storageRoot,
  4841. });
  4842. expect(removed).toBeNull();
  4843. expect(listInstalledPluginRecords(storageRoot)).toHaveLength(0);
  4844. } finally {
  4845. await rm(dir, { force: true, recursive: true });
  4846. }
  4847. });
  4848. // Bugfix 回归(差一层目录):Claude 插件规范里 manifest skills 数组项指向「技能目录本身」
  4849. // (项内直接是 SKILL.md),此前 ZCode 把每项当作技能根去项下找子目录,扫描恒为空。
  4850. it("discovers skills for plugin manifest skills array entries pointing at skill directories", async () => {
  4851. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-array-skills-"));
  4852. const pluginRoot = join(dir, "mattpocock");
  4853. const skillEntries = ["./skills/engineering/tdd", "./skills/productivity/writing"];
  4854. try {
  4855. await writePluginManifest(
  4856. pluginRoot,
  4857. { name: "mattpocock-skills", skills: skillEntries },
  4858. ".claude-plugin",
  4859. );
  4860. for (const [index, entry] of skillEntries.entries()) {
  4861. const skillName = entry.split("/").pop() ?? "";
  4862. const skillDir = join(pluginRoot, entry);
  4863. await mkdir(skillDir, { recursive: true });
  4864. await writeFile(
  4865. join(skillDir, "SKILL.md"),
  4866. [
  4867. "---",
  4868. `name: ${skillName}`,
  4869. `description: array-entry skill ${index}`,
  4870. "---",
  4871. "",
  4872. "# skill",
  4873. ].join("\n"),
  4874. );
  4875. }
  4876. const outcome = await createNodePluginAdapter({
  4877. storageRoot: join(dir, "plugins"),
  4878. }).discoverPlugins({
  4879. config: {
  4880. dirs: [pluginRoot],
  4881. enabled: true,
  4882. enabledPlugins: {},
  4883. options: {},
  4884. },
  4885. env: {},
  4886. storageRoot: join(dir, "plugins"),
  4887. workingDirectory: join(dir, "workspace"),
  4888. });
  4889. const plugin = outcome.plugins.find((item) => item.id === "mattpocock-skills@inline");
  4890. expect(plugin).toBeDefined();
  4891. // 显式声明后只注册声明入口,不补扫默认 skills/。
  4892. expect(plugin).toMatchObject({ skillCount: 2, skillRootCount: 2 });
  4893. const skillNames = componentNames(plugin?.components ?? [], "skill").sort();
  4894. expect(skillNames).toEqual(["tdd", "writing"]);
  4895. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  4896. roots: outcome.skillRoots,
  4897. workingDirectory: join(dir, "workspace"),
  4898. });
  4899. expect(skillOutcome.skills).toHaveLength(2);
  4900. // 插件技能带 pluginName 别名,供会话内以 <plugin>:<skill> 引用。
  4901. expect(skillOutcome.skills.map((skill) => skill.qualifiedName).sort()).toEqual([
  4902. "mattpocock-skills:tdd",
  4903. "mattpocock-skills:writing",
  4904. ]);
  4905. } finally {
  4906. await rm(dir, { force: true, recursive: true });
  4907. }
  4908. });
  4909. // Bugfix 回归(评审跟进):数组语义下两个声明项的叶子目录可能同名
  4910. // (./skills/engineering/tdd 与 ./skills/productivity/tdd),组件清单此前在解析
  4911. // frontmatter 之前按目录 basename 提前去重,会把第二个技能丢掉,与按路径去重的
  4912. // 运行时发现结果(skillCount)不一致。必须解析 frontmatter 后按最终 name 去重。
  4913. it("keeps same-named leaf skill directories from different declared roots in components", async () => {
  4914. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-same-leaf-skills-"));
  4915. const pluginRoot = join(dir, "same-leaf");
  4916. const entries: Array<{ entry: string; name: string }> = [
  4917. { entry: "./skills/engineering/tdd", name: "tdd" },
  4918. { entry: "./skills/productivity/tdd", name: "tdd-productivity" },
  4919. ];
  4920. try {
  4921. await writePluginManifest(
  4922. pluginRoot,
  4923. { name: "same-leaf", skills: entries.map((item) => item.entry) },
  4924. ".claude-plugin",
  4925. );
  4926. for (const { entry, name } of entries) {
  4927. const skillDir = join(pluginRoot, entry);
  4928. await mkdir(skillDir, { recursive: true });
  4929. await writeFile(
  4930. join(skillDir, "SKILL.md"),
  4931. `---\nname: ${name}\ndescription: same leaf skill\n---\n\n# ${name}`,
  4932. );
  4933. }
  4934. const outcome = await createNodePluginAdapter({
  4935. storageRoot: join(dir, "plugins"),
  4936. }).discoverPlugins({
  4937. config: {
  4938. dirs: [pluginRoot],
  4939. enabled: true,
  4940. enabledPlugins: {},
  4941. options: {},
  4942. },
  4943. env: {},
  4944. storageRoot: join(dir, "plugins"),
  4945. workingDirectory: join(dir, "workspace"),
  4946. });
  4947. const plugin = outcome.plugins.find((item) => item.id === "same-leaf@inline");
  4948. expect(plugin).toMatchObject({ skillCount: 2 });
  4949. // 组件清单与 skillCount 口径一致:两个同名叶子目录(frontmatter name 不同)都在。
  4950. expect(componentNames(plugin?.components ?? [], "skill").sort()).toEqual([
  4951. "tdd",
  4952. "tdd-productivity",
  4953. ]);
  4954. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  4955. roots: outcome.skillRoots,
  4956. workingDirectory: join(dir, "workspace"),
  4957. });
  4958. expect(skillOutcome.skills.map((skill) => skill.name).sort()).toEqual([
  4959. "tdd",
  4960. "tdd-productivity",
  4961. ]);
  4962. } finally {
  4963. await rm(dir, { force: true, recursive: true });
  4964. }
  4965. });
  4966. it("does not add the default root alongside a declared skill", async () => {
  4967. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-overlap-skills-"));
  4968. const pluginRoot = join(dir, "overlap");
  4969. try {
  4970. await writePluginManifest(
  4971. pluginRoot,
  4972. { name: "overlap", skills: ["./skills/foo"] },
  4973. ".claude-plugin",
  4974. );
  4975. await mkdir(join(pluginRoot, "skills", "foo"), { recursive: true });
  4976. await writeFile(
  4977. join(pluginRoot, "skills", "foo", "SKILL.md"),
  4978. "---\nname: foo\ndescription: overlap skill\n---\n\n# foo",
  4979. );
  4980. const outcome = await createNodePluginAdapter({
  4981. storageRoot: join(dir, "plugins"),
  4982. }).discoverPlugins({
  4983. config: {
  4984. dirs: [pluginRoot],
  4985. enabled: true,
  4986. enabledPlugins: {},
  4987. options: {},
  4988. },
  4989. env: {},
  4990. storageRoot: join(dir, "plugins"),
  4991. workingDirectory: join(dir, "workspace"),
  4992. });
  4993. const plugin = outcome.plugins.find((item) => item.id === "overlap@inline");
  4994. expect(plugin).toMatchObject({ skillCount: 1, skillRootCount: 1 });
  4995. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  4996. roots: outcome.skillRoots,
  4997. workingDirectory: join(dir, "workspace"),
  4998. });
  4999. expect(skillOutcome.skills).toHaveLength(1);
  5000. } finally {
  5001. await rm(dir, { force: true, recursive: true });
  5002. }
  5003. });
  5004. // 信任边界回归(CR-01):manifest skills 声明是插件提供的不可信输入。
  5005. // resolveInside(helpers.ts)在词法层面拒绝绝对路径与 ../ 穿越(rel 以 .. 开头
  5006. // 或含 ..${sep}),越界声明在 resolveComponentRoots 落成 plugin_component_path_invalid
  5007. // error 诊断;本用例把该边界固定,防止后续重构 scanner 时重新引入路径穿越。
  5008. it("rejects skills paths escaping the plugin root and keeps legitimate skills working", async () => {
  5009. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-path-escape-"));
  5010. const pluginRoot = join(dir, "plugin");
  5011. // 插件根外的诱饵技能目录;若防线失效会被扫描进结果。
  5012. const outsideSkill = join(dir, "outside-skill");
  5013. const absoluteOutside = join(dir, "absolute-outside");
  5014. try {
  5015. await writePluginManifest(
  5016. pluginRoot,
  5017. {
  5018. name: "path-escape",
  5019. skills: ["../../outside-skill", absoluteOutside, "./skills/legit"],
  5020. },
  5021. ".claude-plugin",
  5022. );
  5023. await mkdir(outsideSkill, { recursive: true });
  5024. await mkdir(absoluteOutside, { recursive: true });
  5025. await writeFile(join(outsideSkill, "SKILL.md"), "---\nname: outside\n---\n# x");
  5026. await writeFile(join(absoluteOutside, "SKILL.md"), "---\nname: absolute\n---\n# x");
  5027. await mkdir(join(pluginRoot, "skills", "legit"), { recursive: true });
  5028. await writeFile(
  5029. join(pluginRoot, "skills", "legit", "SKILL.md"),
  5030. "---\nname: legit\ndescription: legitimate skill\n---\n# legit",
  5031. );
  5032. const outcome = await createNodePluginAdapter({
  5033. storageRoot: join(dir, "plugins"),
  5034. }).discoverPlugins({
  5035. config: {
  5036. dirs: [pluginRoot],
  5037. enabled: true,
  5038. enabledPlugins: {},
  5039. options: {},
  5040. },
  5041. env: {},
  5042. storageRoot: join(dir, "plugins"),
  5043. workingDirectory: join(dir, "workspace"),
  5044. });
  5045. // 越界声明(../ 穿越与绝对路径)被拒:error 诊断逐条可见,且不会误报成
  5046. // plugin_skill_root_empty(resolveInside 返回 null 时告警逻辑直接跳过)。
  5047. const invalid = outcome.diagnostics.filter(
  5048. (diagnostic) => diagnostic.code === "plugin_component_path_invalid",
  5049. );
  5050. expect(invalid).toHaveLength(2);
  5051. expect(invalid.every((diagnostic) => diagnostic.severity === "error")).toBe(true);
  5052. expect(invalid.some((diagnostic) => diagnostic.message.includes("../../outside-skill"))).toBe(
  5053. true,
  5054. );
  5055. expect(invalid.some((diagnostic) => diagnostic.message.includes(absoluteOutside))).toBe(true);
  5056. expect(
  5057. outcome.diagnostics.some(
  5058. (diagnostic) =>
  5059. diagnostic.code === "plugin_skill_root_empty" &&
  5060. diagnostic.pluginId === "path-escape@inline",
  5061. ),
  5062. ).toBe(false);
  5063. // 合法声明不受越界项影响:skillCount 只含 legit,越界技能不出现在发现结果。
  5064. const plugin = outcome.plugins.find((item) => item.id === "path-escape@inline");
  5065. expect(plugin).toMatchObject({ skillCount: 1 });
  5066. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  5067. roots: outcome.skillRoots,
  5068. workingDirectory: join(dir, "workspace"),
  5069. });
  5070. expect(skillOutcome.skills.map((skill) => skill.name)).toEqual(["legit"]);
  5071. } finally {
  5072. await rm(dir, { force: true, recursive: true });
  5073. }
  5074. });
  5075. // 信任边界回归(文件级 symlink):目录是真实目录但 SKILL.md 本身是指向插件根
  5076. // 外文件的链接(如 skills/foo/SKILL.md -> ~/.aws/credentials),以及根自身
  5077. // SKILL.md 是链接的形态。文件级与目录级走同一个 isSymbolicLinkSync(lstat)
  5078. // 拒绝路径。Windows 普通权限下创建文件 symlink 会 EPERM,此时才跳过——
  5079. // 开发者模式或管理员 CI 上本用例会真实执行,不整体按平台跳过。
  5080. it("rejects file-level SKILL.md symlinks escaping the plugin root", async (ctx) => {
  5081. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-file-symlink-"));
  5082. const pluginRoot = join(dir, "plugin");
  5083. const outsideFile = join(dir, "outside-secret.md");
  5084. try {
  5085. await writePluginManifest(
  5086. pluginRoot,
  5087. {
  5088. name: "file-symlink-escape",
  5089. skills: ["./skills", "./bundle-root"],
  5090. },
  5091. ".claude-plugin",
  5092. );
  5093. await writeFile(outsideFile, "---\nname: leaked-secret\ndescription: x\n---\nleaked");
  5094. // 形态 1:子目录是真实目录,其 SKILL.md 是指向外部的文件链接。
  5095. // 第一个链接同时作为权限探针:EPERM(Windows 无 symlink 特权)才跳过,
  5096. // 其余错误如实抛出;finally 保证临时目录清理。
  5097. await mkdir(join(pluginRoot, "skills", "foo"), { recursive: true });
  5098. try {
  5099. await symlink(outsideFile, join(pluginRoot, "skills", "foo", "SKILL.md"));
  5100. } catch (error) {
  5101. if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error;
  5102. ctx.skip();
  5103. return;
  5104. }
  5105. // 形态 2:声明根(bundle-root)自身目录真实,SKILL.md 是外部文件链接。
  5106. await mkdir(join(pluginRoot, "bundle-root"), { recursive: true });
  5107. await symlink(outsideFile, join(pluginRoot, "bundle-root", "SKILL.md"));
  5108. // 对照组:真实文件技能正常发现。
  5109. await mkdir(join(pluginRoot, "skills", "legit"), { recursive: true });
  5110. await writeFile(
  5111. join(pluginRoot, "skills", "legit", "SKILL.md"),
  5112. "---\nname: legit\ndescription: legitimate\n---\n# legit",
  5113. );
  5114. const outcome = await createNodePluginAdapter({
  5115. storageRoot: join(dir, "plugins"),
  5116. }).discoverPlugins({
  5117. config: {
  5118. dirs: [pluginRoot],
  5119. enabled: true,
  5120. enabledPlugins: {},
  5121. options: {},
  5122. },
  5123. env: {},
  5124. storageRoot: join(dir, "plugins"),
  5125. workingDirectory: join(dir, "workspace"),
  5126. });
  5127. // 只有真实文件技能被计数;两个文件级链接形态都被剔除。
  5128. const plugin = outcome.plugins.find((item) => item.id === "file-symlink-escape@inline");
  5129. expect(plugin).toMatchObject({ skillCount: 1 });
  5130. expect(componentNames(plugin?.components ?? [], "skill")).toEqual(["legit"]);
  5131. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  5132. roots: outcome.skillRoots,
  5133. workingDirectory: join(dir, "workspace"),
  5134. });
  5135. expect(skillOutcome.skills.map((skill) => skill.name)).toEqual(["legit"]);
  5136. // 泄密文件内容绝不出现在任何技能路径的加载结果里。
  5137. expect(skillOutcome.skills.some((skill) => skill.path === outsideFile)).toBe(false);
  5138. } finally {
  5139. await rm(dir, { force: true, recursive: true });
  5140. }
  5141. });
  5142. // 信任边界回归(目录级 symlink/junction):plugin-scope 扫描不跟随符号链接——
  5143. // skills/evil-link -> ../../outside-skill(子目录是逃逸链接)
  5144. // skills/linked-root -> ../../outside-skill(声明根本身是逃逸链接)
  5145. // 两种形态都被剔除;声明根是链接时扫描为空,落入「没有任何技能」告警。
  5146. // Windows 用 junction 创建(无需特权;lstat/Dirent 对 junction 同样报告
  5147. // isSymbolicLink=true),CR-02 的 Windows 形态在本用例获得真实覆盖。
  5148. it("strips symlink escapes from plugin skills and warns on escaping declared roots", async () => {
  5149. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-symlink-escape-"));
  5150. const pluginRoot = join(dir, "plugin");
  5151. const outsideSkill = join(dir, "outside-skill");
  5152. try {
  5153. await writePluginManifest(
  5154. pluginRoot,
  5155. {
  5156. name: "symlink-escape",
  5157. skills: ["./skills/linked-root", "./skills"],
  5158. },
  5159. ".claude-plugin",
  5160. );
  5161. await mkdir(outsideSkill, { recursive: true });
  5162. await writeFile(
  5163. join(outsideSkill, "SKILL.md"),
  5164. "---\nname: escaped-skill\ndescription: must never load\n---\n# x",
  5165. );
  5166. // 形态 1:声明根本身是指向插件根外的链接(skills/ 需先存在)。
  5167. // Windows 传 junction 类型(目录 symlink 需特权,junction 不需要;
  5168. // POSIX 忽略该参数,行为为普通 symlink)。
  5169. await mkdir(join(pluginRoot, "skills"), { recursive: true });
  5170. await symlinkDir(outsideSkill, join(pluginRoot, "skills", "linked-root"));
  5171. // 形态 2:默认 skills/ 根下的子目录是指向插件根外的链接。
  5172. await symlinkDir(outsideSkill, join(pluginRoot, "skills", "evil-link"));
  5173. const outcome = await createNodePluginAdapter({
  5174. storageRoot: join(dir, "plugins"),
  5175. }).discoverPlugins({
  5176. config: {
  5177. dirs: [pluginRoot],
  5178. enabled: true,
  5179. enabledPlugins: {},
  5180. options: {},
  5181. },
  5182. env: {},
  5183. storageRoot: join(dir, "plugins"),
  5184. workingDirectory: join(dir, "workspace"),
  5185. });
  5186. // 逃逸技能不进计数、不进组件清单。
  5187. const plugin = outcome.plugins.find((item) => item.id === "symlink-escape@inline");
  5188. expect(plugin).toMatchObject({ skillCount: 0 });
  5189. expect(componentNames(plugin?.components ?? [], "skill")).toEqual([]);
  5190. // 声明根本身是链接 → 扫描为空,落入「没有任何技能」告警(词法路径存在,
  5191. // 不误报 does not exist)。
  5192. expect(
  5193. outcome.diagnostics.some(
  5194. (diagnostic) =>
  5195. diagnostic.code === "plugin_skill_root_empty" &&
  5196. diagnostic.pluginId === "symlink-escape@inline" &&
  5197. diagnostic.message.includes("does not contain any skills") &&
  5198. diagnostic.message.includes("skills/linked-root"),
  5199. ),
  5200. ).toBe(true);
  5201. // 运行时发现同样剔除:逃逸技能不出现在 skill adapter 结果。
  5202. const skillOutcome = await createNodeSkillAdapter().discoverSkills({
  5203. roots: outcome.skillRoots,
  5204. workingDirectory: join(dir, "workspace"),
  5205. });
  5206. expect(skillOutcome.skills.map((skill) => skill.name)).toEqual([]);
  5207. } finally {
  5208. await rm(dir, { force: true, recursive: true });
  5209. }
  5210. });
  5211. // 去静默:manifest 显式声明的技能路径扫描为 0 个技能时必须发 warning(路径写进 message,
  5212. // 因为协议 wire schema 不携带 path);纯默认目录为空不告警;显式声明默认目录名同样算声明。
  5213. it("warns when a declared skill path yields no skills", async () => {
  5214. const dir = await mkdtemp(join(tmpdir(), "zcode-plugin-empty-skills-"));
  5215. async function discover(pluginRoot: string, manifest: Record<string, unknown>) {
  5216. await writePluginManifest(pluginRoot, manifest, ".claude-plugin");
  5217. return await createNodePluginAdapter({ storageRoot: join(dir, "plugins") }).discoverPlugins({
  5218. config: {
  5219. dirs: [pluginRoot],
  5220. enabled: true,
  5221. enabledPlugins: {},
  5222. options: {},
  5223. },
  5224. env: {},
  5225. storageRoot: join(dir, "plugins"),
  5226. workingDirectory: join(dir, "workspace"),
  5227. });
  5228. }
  5229. try {
  5230. // 场景 1:数组声明项目录存在但无 SKILL.md(分类目录,mattpocock 复现形态)。
  5231. const missingRoot = join(dir, "declared-missing");
  5232. await mkdir(join(missingRoot, "skills", "engineering"), { recursive: true });
  5233. const missingOutcome = await discover(missingRoot, {
  5234. name: "declared-missing",
  5235. skills: ["./skills/engineering/tdd"],
  5236. });
  5237. const missingWarning = missingOutcome.diagnostics.find(
  5238. (diagnostic) => diagnostic.code === "plugin_skill_root_empty",
  5239. );
  5240. expect(missingWarning).toMatchObject({
  5241. pluginId: "declared-missing@inline",
  5242. severity: "warning",
  5243. });
  5244. expect(missingWarning?.message).toContain("skills/engineering/tdd");
  5245. // 场景 2:显式声明不存在的路径。
  5246. const absentOutcome = await discover(join(dir, "declared-absent"), {
  5247. name: "declared-absent",
  5248. skills: "./skills/nowhere",
  5249. });
  5250. expect(
  5251. absentOutcome.diagnostics.some(
  5252. (diagnostic) =>
  5253. diagnostic.code === "plugin_skill_root_empty" &&
  5254. diagnostic.message.includes("skills/nowhere"),
  5255. ),
  5256. ).toBe(true);
  5257. // 场景 3:纯默认目录为空(manifest 未声明 skills)不告警,避免空插件误报。
  5258. const silentOutcome = await discover(join(dir, "default-only"), {
  5259. name: "default-only",
  5260. });
  5261. expect(
  5262. silentOutcome.diagnostics.every(
  5263. (diagnostic) => diagnostic.code !== "plugin_skill_root_empty",
  5264. ),
  5265. ).toBe(true);
  5266. // 场景 4:显式写默认目录名 "skills" 且目录为空——默认项会在 roots 里被去重合并,
  5267. // 但声明集合独立计算,仍须告警。
  5268. const explicitOutcome = await discover(join(dir, "explicit-default"), {
  5269. name: "explicit-default",
  5270. skills: "skills",
  5271. });
  5272. expect(
  5273. explicitOutcome.diagnostics.some(
  5274. (diagnostic) =>
  5275. diagnostic.code === "plugin_skill_root_empty" &&
  5276. diagnostic.pluginId === "explicit-default@inline",
  5277. ),
  5278. ).toBe(true);
  5279. } finally {
  5280. await rm(dir, { force: true, recursive: true });
  5281. }
  5282. });
  5283. });
  5284. function componentNames(
  5285. components: Awaited<ReturnType<typeof describeMarketplacePlugin>>["components"],
  5286. kind: "agent" | "command" | "skill" | "hook" | "mcp",
  5287. ): string[] {
  5288. return components.find((group) => group.kind === kind)?.items.map((item) => item.name) ?? [];
  5289. }
  5290. function componentDescription(
  5291. components: Awaited<ReturnType<typeof describeMarketplacePlugin>>["components"],
  5292. kind: "agent" | "command" | "skill" | "hook" | "mcp",
  5293. name: string,
  5294. ): string | undefined {
  5295. return components.find((group) => group.kind === kind)?.items.find((item) => item.name === name)
  5296. ?.description;
  5297. }
  5298. async function startZipFixtureServer(
  5299. routes: Record<string, Buffer>,
  5300. ): Promise<{ baseUrl: string; server: Server }> {
  5301. const server = createServer((request, response) => {
  5302. const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
  5303. const body = routes[pathname];
  5304. if (!body) {
  5305. response.writeHead(404);
  5306. response.end("not found");
  5307. return;
  5308. }
  5309. response.writeHead(200, {
  5310. "content-length": String(body.byteLength),
  5311. "content-type": "application/zip",
  5312. });
  5313. response.end(body);
  5314. });
  5315. const baseUrl = await listenLoopbackServer(server);
  5316. return { baseUrl, server };
  5317. }
  5318. async function listenLoopbackServer(server: Server): Promise<string> {
  5319. await new Promise<void>((resolveListen) => {
  5320. server.listen(0, "127.0.0.1", resolveListen);
  5321. });
  5322. const address = server.address();
  5323. if (!address || typeof address === "string") {
  5324. throw new Error("fixture server did not bind to a TCP port");
  5325. }
  5326. return `http://127.0.0.1:${address.port}`;
  5327. }
  5328. async function closeServer(server: Server | undefined): Promise<void> {
  5329. if (!server || !server.listening) return;
  5330. await new Promise<void>((resolveClose, rejectClose) => {
  5331. server.close((error) => {
  5332. if (error) rejectClose(error);
  5333. else resolveClose();
  5334. });
  5335. });
  5336. }
  5337. function sha256Buffer(buffer: Buffer): string {
  5338. return createHash("sha256").update(buffer).digest("hex");
  5339. }
  5340. function createStoredZip(entries: Array<{ content?: string; path: string }>): Buffer {
  5341. const localParts: Buffer[] = [];
  5342. const centralParts: Buffer[] = [];
  5343. let offset = 0;
  5344. for (const entry of entries) {
  5345. const name = Buffer.from(entry.path);
  5346. const data = Buffer.from(entry.content ?? "");
  5347. const crc = crc32(data);
  5348. const local = Buffer.alloc(30);
  5349. local.writeUInt32LE(0x04034b50, 0);
  5350. local.writeUInt16LE(20, 4);
  5351. local.writeUInt16LE(0, 6);
  5352. local.writeUInt16LE(0, 8);
  5353. local.writeUInt16LE(0, 10);
  5354. local.writeUInt16LE(0, 12);
  5355. local.writeUInt32LE(crc, 14);
  5356. local.writeUInt32LE(data.byteLength, 18);
  5357. local.writeUInt32LE(data.byteLength, 22);
  5358. local.writeUInt16LE(name.byteLength, 26);
  5359. local.writeUInt16LE(0, 28);
  5360. localParts.push(local, name, data);
  5361. const central = Buffer.alloc(46);
  5362. central.writeUInt32LE(0x02014b50, 0);
  5363. central.writeUInt16LE(20, 4);
  5364. central.writeUInt16LE(20, 6);
  5365. central.writeUInt16LE(0, 8);
  5366. central.writeUInt16LE(0, 10);
  5367. central.writeUInt16LE(0, 12);
  5368. central.writeUInt16LE(0, 14);
  5369. central.writeUInt32LE(crc, 16);
  5370. central.writeUInt32LE(data.byteLength, 20);
  5371. central.writeUInt32LE(data.byteLength, 24);
  5372. central.writeUInt16LE(name.byteLength, 28);
  5373. central.writeUInt16LE(0, 30);
  5374. central.writeUInt16LE(0, 32);
  5375. central.writeUInt16LE(0, 34);
  5376. central.writeUInt16LE(0, 36);
  5377. central.writeUInt32LE((entry.path.endsWith("/") ? 0o040755 : 0o100644) * 0x10000, 38);
  5378. central.writeUInt32LE(offset, 42);
  5379. centralParts.push(central, name);
  5380. offset += local.byteLength + name.byteLength + data.byteLength;
  5381. }
  5382. const centralDirectory = Buffer.concat(centralParts);
  5383. const end = Buffer.alloc(22);
  5384. end.writeUInt32LE(0x06054b50, 0);
  5385. end.writeUInt16LE(0, 4);
  5386. end.writeUInt16LE(0, 6);
  5387. end.writeUInt16LE(entries.length, 8);
  5388. end.writeUInt16LE(entries.length, 10);
  5389. end.writeUInt32LE(centralDirectory.byteLength, 12);
  5390. end.writeUInt32LE(offset, 16);
  5391. end.writeUInt16LE(0, 20);
  5392. return Buffer.concat([...localParts, centralDirectory, end]);
  5393. }
  5394. const CRC32_TABLE = Array.from({ length: 256 }, (_, index) => {
  5395. let value = index;
  5396. for (let bit = 0; bit < 8; bit += 1) {
  5397. value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
  5398. }
  5399. return value >>> 0;
  5400. });
  5401. function crc32(buffer: Buffer): number {
  5402. let crc = 0xffffffff;
  5403. for (const byte of buffer) {
  5404. crc = CRC32_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
  5405. }
  5406. return (crc ^ 0xffffffff) >>> 0;
  5407. }
  5408. /** 创建指向目录的链接:Windows 用 junction(无需特权),POSIX 忽略 type 参数。 */
  5409. async function symlinkDir(target: string, linkPath: string): Promise<void> {
  5410. await symlink(target, linkPath, process.platform === "win32" ? "junction" : undefined);
  5411. }
  5412. async function writePluginManifest(
  5413. pluginRoot: string,
  5414. manifest: Record<string, unknown>,
  5415. manifestDir = ".zcode-plugin",
  5416. ): Promise<void> {
  5417. await mkdir(join(pluginRoot, manifestDir), { recursive: true });
  5418. await writeFile(join(pluginRoot, manifestDir, "plugin.json"), JSON.stringify(manifest));
  5419. }
  5420. async function writeMarketplaceManifest(
  5421. marketplaceRoot: string,
  5422. manifest: Record<string, unknown>,
  5423. ): Promise<void> {
  5424. await mkdir(join(marketplaceRoot, ".claude-plugin"), { recursive: true });
  5425. await writeFile(
  5426. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  5427. JSON.stringify(manifest),
  5428. );
  5429. }
  5430. async function writeKnownMarketplaces(
  5431. storageRoot: string,
  5432. marketplaces: Array<Record<string, unknown>>,
  5433. ): Promise<void> {
  5434. await mkdir(storageRoot, { recursive: true });
  5435. await writeFile(
  5436. join(storageRoot, "known_marketplaces.json"),
  5437. JSON.stringify({ version: 1, marketplaces }),
  5438. );
  5439. }
  5440. async function listenServer(server: Server): Promise<string> {
  5441. await new Promise<void>((resolve, reject) => {
  5442. server.once("error", reject);
  5443. server.listen(0, "127.0.0.1", () => {
  5444. server.removeListener("error", reject);
  5445. resolve();
  5446. });
  5447. });
  5448. const address = server.address();
  5449. if (!address || typeof address === "string") {
  5450. throw new Error("Test server did not expose a TCP address");
  5451. }
  5452. return `http://127.0.0.1:${address.port}`;
  5453. }
  5454. interface TripletPluginFixture {
  5455. commandCount: number;
  5456. commandPrefix: string;
  5457. manifestPaths?: boolean;
  5458. mcpFileName?: ".mcp.json" | "mcp.json";
  5459. mcpServerName: string;
  5460. name: string;
  5461. skillCount: number;
  5462. }
  5463. function claudeMarketplaceTripletFixtures(): TripletPluginFixture[] {
  5464. return [
  5465. {
  5466. commandCount: 27,
  5467. commandPrefix: "bigdata",
  5468. mcpServerName: "bigdata",
  5469. name: "bigdata-com",
  5470. skillCount: 1,
  5471. },
  5472. {
  5473. commandCount: 1,
  5474. commandPrefix: "convex",
  5475. manifestPaths: true,
  5476. mcpServerName: "convex",
  5477. name: "convex",
  5478. skillCount: 2,
  5479. },
  5480. {
  5481. commandCount: 4,
  5482. commandPrefix: "logfire",
  5483. manifestPaths: true,
  5484. mcpFileName: "mcp.json",
  5485. mcpServerName: "logfire",
  5486. name: "logfire",
  5487. skillCount: 3,
  5488. },
  5489. ];
  5490. }
  5491. async function writeTripletPluginFixture(
  5492. pluginRoot: string,
  5493. fixture: TripletPluginFixture,
  5494. ): Promise<void> {
  5495. const mcpFileName = fixture.mcpFileName ?? ".mcp.json";
  5496. await writePluginManifest(
  5497. pluginRoot,
  5498. {
  5499. ...(fixture.manifestPaths
  5500. ? {
  5501. commands: "./commands/",
  5502. mcpServers: `./${mcpFileName}`,
  5503. skills: "./skills/",
  5504. }
  5505. : {}),
  5506. name: fixture.name,
  5507. version: "1.0.0",
  5508. },
  5509. ".claude-plugin",
  5510. );
  5511. for (let index = 1; index <= fixture.skillCount; index += 1) {
  5512. const skillName = `${fixture.name}-skill-${index}`;
  5513. const skillDir = join(pluginRoot, "skills", skillName);
  5514. await mkdir(skillDir, { recursive: true });
  5515. await writeFile(
  5516. join(skillDir, "SKILL.md"),
  5517. [
  5518. "---",
  5519. `name: ${skillName}`,
  5520. `description: ${fixture.name} marketplace compatibility skill ${index}`,
  5521. "---",
  5522. "",
  5523. `# ${skillName}`,
  5524. "",
  5525. "Validate plugin skill projection.",
  5526. ].join("\n"),
  5527. );
  5528. }
  5529. const commandDir = join(pluginRoot, "commands", fixture.commandPrefix);
  5530. await mkdir(commandDir, { recursive: true });
  5531. for (let index = 1; index <= fixture.commandCount; index += 1) {
  5532. const commandName = `cmd${String(index).padStart(2, "0")}`;
  5533. await writeFile(
  5534. join(commandDir, `${commandName}.md`),
  5535. [
  5536. "---",
  5537. `description: ${fixture.name} marketplace compatibility command ${index}`,
  5538. "allowed-tools: Read, Bash",
  5539. "---",
  5540. "",
  5541. `Run ${fixture.name} command ${index} with $ARGUMENTS.`,
  5542. ].join("\n"),
  5543. );
  5544. }
  5545. await writeFile(
  5546. join(pluginRoot, mcpFileName),
  5547. JSON.stringify({
  5548. mcpServers: {
  5549. [fixture.mcpServerName]: {
  5550. args: ["${CLAUDE_PLUGIN_ROOT}/mcp/server.js"],
  5551. command: "node",
  5552. env: {
  5553. PLUGIN_DATA: "${CLAUDE_PLUGIN_DATA}",
  5554. PROJECT_DIR: "${ZCODE_PROJECT_DIR}",
  5555. },
  5556. },
  5557. },
  5558. }),
  5559. );
  5560. }