plugins.test.ts 215 KB

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