plugins.test.ts 166 KB

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