plugins.test.ts 168 KB

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