plugins.test.ts 169 KB

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