config.test.ts 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { Logger, LoggerFactory } from "@zcode/contracts";
  3. import { withFileLock } from "@zcode/shared/node";
  4. import {
  5. createConfig,
  6. createConfigWithPluginMigrations,
  7. resolveWorkspaceStorageDir,
  8. updateUiLocaleInFileConfig,
  9. } from "../src/config/index.js";
  10. import { parseEnvConfig } from "../src/config/env-config.adapter.js";
  11. import {
  12. addSuppressedBuiltinInFileConfig,
  13. loadFileConfig,
  14. removePluginFromFileConfig,
  15. removeSuppressedBuiltinInFileConfig,
  16. updatePluginEnabledInFileConfig,
  17. updatePluginOptionsInFileConfig,
  18. } from "../src/config/file-config.adapter.js";
  19. import * as fsPromises from "node:fs/promises";
  20. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
  21. import { tmpdir } from "node:os";
  22. import { join } from "node:path";
  23. vi.mock("node:fs/promises", async (importOriginal) => {
  24. const actual = await importOriginal<typeof import("node:fs/promises")>();
  25. return { ...actual, rename: vi.fn(actual.rename) };
  26. });
  27. vi.mock("../src/config/file-config.adapter.js", async (importOriginal) => {
  28. const actual = await importOriginal<typeof import("../src/config/file-config.adapter.js")>();
  29. return { ...actual, loadFileConfig: vi.fn(actual.loadFileConfig) };
  30. });
  31. vi.mock("@zcode/shared/node", async (importOriginal) => {
  32. const actual = await importOriginal<typeof import("@zcode/shared/node")>();
  33. return { ...actual, withFileLock: vi.fn(actual.withFileLock) };
  34. });
  35. function captureConfigLogger() {
  36. const warn = vi.fn();
  37. const logger: Logger = { debug() {}, info() {}, error() {}, warn, child: () => logger };
  38. const loggerFactory: LoggerFactory = {
  39. createLogger: () => logger,
  40. withContext: () => logger,
  41. setLevel() {},
  42. };
  43. return { loggerFactory, warn };
  44. }
  45. describe("config adapters", () => {
  46. it("resets legacy visualize flags per config once and preserves later opt-in", async () => {
  47. const root = await mkdtemp(join(tmpdir(), "zcode-visualize-migration-"));
  48. const userConfigPath = join(root, "user.json");
  49. const projectConfigPath = join(root, ".zcode", "config.json");
  50. const id = "visualize@zcode-plugins-official";
  51. const original = {
  52. keep: "unknown",
  53. plugins: { enabledPlugins: { [id]: true, "other@fixture": true } },
  54. };
  55. try {
  56. await mkdir(join(root, ".zcode"));
  57. await writeFile(userConfigPath, JSON.stringify(original));
  58. await writeFile(projectConfigPath, JSON.stringify(original));
  59. const options = { env: {}, userConfigPath, workingDirectory: root };
  60. const migrated = await createConfigWithPluginMigrations(options);
  61. expect(migrated.config.plugins.enabledPlugins[id]).toBe(false);
  62. for (const path of [userConfigPath, projectConfigPath]) {
  63. expect(JSON.parse(await readFile(path, "utf8"))).toEqual({
  64. ...original,
  65. plugins: {
  66. visualizeDefaultOffMigrated: true,
  67. enabledPlugins: { [id]: false, "other@fixture": true },
  68. },
  69. });
  70. }
  71. await updatePluginEnabledInFileConfig(projectConfigPath, id, true);
  72. const bytes = await readFile(projectConfigPath, "utf8");
  73. const reloaded = await Promise.all(
  74. Array.from({ length: 4 }, () => createConfigWithPluginMigrations(options)),
  75. );
  76. expect(reloaded.every((result) => result.config.plugins.enabledPlugins[id])).toBe(true);
  77. expect(await readFile(projectConfigPath, "utf8")).toBe(bytes);
  78. } finally {
  79. await rm(root, { recursive: true, force: true });
  80. }
  81. });
  82. it("preserves a first enable racing with migration and other config writes", async () => {
  83. const root = await mkdtemp(join(tmpdir(), "zcode-visualize-race-"));
  84. const userConfigPath = join(root, "user.json");
  85. const id = "visualize@zcode-plugins-official";
  86. try {
  87. const options = { env: {}, userConfigPath };
  88. await createConfigWithPluginMigrations(options);
  89. await expect(readFile(userConfigPath)).rejects.toMatchObject({ code: "ENOENT" });
  90. await writeFile(
  91. userConfigPath,
  92. JSON.stringify({ plugins: { enabledPlugins: { [id]: true } } }),
  93. );
  94. await Promise.all([
  95. createConfigWithPluginMigrations(options),
  96. updatePluginEnabledInFileConfig(userConfigPath, id, true),
  97. updateUiLocaleInFileConfig(userConfigPath, "zh-CN"),
  98. ]);
  99. const result = await createConfigWithPluginMigrations(options);
  100. expect(result.config.plugins.enabledPlugins[id]).toBe(true);
  101. expect(result.config.ui.locale).toBe("zh-CN");
  102. } finally {
  103. await rm(root, { recursive: true, force: true });
  104. }
  105. });
  106. it.each(["rename", "lock"])(
  107. "continues with a disabled layer when migration %s fails",
  108. async (stage) => {
  109. const root = await mkdtemp(join(tmpdir(), "zcode-visualize-write-failure-"));
  110. const userConfigPath = join(root, "user.json");
  111. const id = "visualize@zcode-plugins-official";
  112. const original = JSON.stringify({ plugins: { enabledPlugins: { [id]: true } } });
  113. const { loggerFactory, warn } = captureConfigLogger();
  114. const code = stage === "rename" ? "EACCES" : "ZCODE_FILE_LOCK_TIMEOUT";
  115. try {
  116. await writeFile(userConfigPath, original);
  117. const operation =
  118. stage === "rename" ? vi.mocked(fsPromises.rename) : vi.mocked(withFileLock);
  119. operation.mockRejectedValueOnce(Object.assign(new Error("migration blocked"), { code }));
  120. try {
  121. const result = await createConfigWithPluginMigrations({
  122. env: {},
  123. userConfigPath,
  124. loggerFactory,
  125. });
  126. expect(result.config.plugins.enabledPlugins[id]).toBe(false);
  127. expect(result.configPort.getAll().plugins.enabledPlugins[id]).toBe(false);
  128. expect(warn).toHaveBeenCalledExactlyOnceWith(
  129. expect.any(String),
  130. expect.objectContaining({ configPath: userConfigPath, errorCode: code }),
  131. );
  132. } finally {
  133. operation.mockRestore();
  134. }
  135. expect(await readFile(userConfigPath, "utf8")).toBe(original);
  136. expect(await readdir(root)).toEqual(["user.json"]);
  137. expect(
  138. (await createConfigWithPluginMigrations({ env: {}, userConfigPath })).config.plugins
  139. .enabledPlugins[id],
  140. ).toBe(false);
  141. } finally {
  142. await rm(root, { recursive: true, force: true });
  143. }
  144. },
  145. );
  146. it.each(["user", "project", "ancestor", "explicit"])(
  147. "keeps scope priority when the %s migration fails",
  148. async (scope) => {
  149. const root = await mkdtemp(join(tmpdir(), "zcode-visualize-layer-failure-"));
  150. const id = "visualize@zcode-plugins-official";
  151. const userConfigPath = join(root, "user.json");
  152. const parentPath = join(root, ".zcode", "config.json");
  153. const child = join(root, "child");
  154. const childPath = join(child, ".zcode", "config.json");
  155. const explicitPath = join(root, "explicit.json");
  156. const paths = {
  157. user: userConfigPath,
  158. project: parentPath,
  159. ancestor: parentPath,
  160. explicit: explicitPath,
  161. };
  162. const failedPath = paths[scope as keyof typeof paths];
  163. const config = (migrated: boolean) =>
  164. JSON.stringify({
  165. plugins: {
  166. ...(migrated ? { visualizeDefaultOffMigrated: true } : {}),
  167. enabledPlugins: { [id]: true, "other@fixture": true },
  168. },
  169. });
  170. const { loggerFactory, warn } = captureConfigLogger();
  171. try {
  172. await mkdir(join(root, ".git"));
  173. await mkdir(join(root, ".zcode"));
  174. await mkdir(join(child, ".zcode"), { recursive: true });
  175. await writeFile(userConfigPath, config(true));
  176. await writeFile(parentPath, config(true));
  177. if (scope === "ancestor") await writeFile(childPath, config(true));
  178. await writeFile(failedPath, config(false));
  179. vi.mocked(fsPromises.rename).mockRejectedValueOnce(
  180. Object.assign(new Error("read only"), { code: "EROFS" }),
  181. );
  182. try {
  183. const result = await createConfigWithPluginMigrations({
  184. env: {},
  185. userConfigPath,
  186. workingDirectory: scope === "ancestor" ? child : root,
  187. ...(scope === "explicit"
  188. ? {
  189. projectConfigPath: explicitPath,
  190. cliOverrides: { plugins: { enabledPlugins: { [id]: true } } },
  191. }
  192. : {}),
  193. loggerFactory,
  194. });
  195. expect(result.config.plugins.enabledPlugins[id]).toBe(scope !== "project");
  196. expect(result.config.plugins.enabledPlugins["other@fixture"]).toBe(true);
  197. expect(warn).toHaveBeenCalledExactlyOnceWith(
  198. expect.any(String),
  199. expect.objectContaining({ configPath: failedPath, errorCode: "EROFS" }),
  200. );
  201. expect(await readFile(failedPath, "utf8")).toBe(config(false));
  202. } finally {
  203. vi.mocked(fsPromises.rename).mockRestore();
  204. }
  205. } finally {
  206. await rm(root, { recursive: true, force: true });
  207. }
  208. },
  209. );
  210. it("warns once when the same file is used by user and project scopes", async () => {
  211. const root = await mkdtemp(join(tmpdir(), "zcode-visualize-shared-config-"));
  212. const userConfigPath = join(root, "config.json");
  213. const id = "visualize@zcode-plugins-official";
  214. const { loggerFactory, warn } = captureConfigLogger();
  215. try {
  216. await writeFile(
  217. userConfigPath,
  218. JSON.stringify({ plugins: { enabledPlugins: { [id]: true } } }),
  219. );
  220. vi.mocked(fsPromises.rename).mockRejectedValue(
  221. Object.assign(new Error("read only"), { code: "EROFS" }),
  222. );
  223. const result = await createConfigWithPluginMigrations({
  224. env: {},
  225. userConfigPath,
  226. projectConfigPath: userConfigPath,
  227. loggerFactory,
  228. });
  229. expect(result.config.plugins.enabledPlugins[id]).toBe(false);
  230. expect(warn).toHaveBeenCalledTimes(1);
  231. } finally {
  232. vi.mocked(fsPromises.rename).mockRestore();
  233. await rm(root, { recursive: true, force: true });
  234. }
  235. });
  236. it.each(["invalid", "unchanged", "migration"])(
  237. "reads config once and reports diagnostics once: %s",
  238. async (kind) => {
  239. const root = await mkdtemp(join(tmpdir(), "zcode-config-single-read-"));
  240. const userConfigPath = join(root, "user.json");
  241. const { loggerFactory, warn } = captureConfigLogger();
  242. try {
  243. await writeFile(
  244. userConfigPath,
  245. kind === "invalid"
  246. ? "{"
  247. : JSON.stringify({
  248. plugins: {
  249. ...(kind === "unchanged" ? { visualizeDefaultOffMigrated: true } : {}),
  250. enabledPlugins: { "visualize@zcode-plugins-official": true },
  251. },
  252. ...(kind === "migration"
  253. ? { mcp: { servers: { broken: { type: "stdio", args: [] } } } }
  254. : {}),
  255. }),
  256. );
  257. vi.mocked(loadFileConfig).mockClear();
  258. await createConfigWithPluginMigrations({ env: {}, userConfigPath, loggerFactory });
  259. expect(loadFileConfig).toHaveBeenCalledTimes(1);
  260. expect(warn).toHaveBeenCalledTimes(kind === "unchanged" ? 0 : 1);
  261. } finally {
  262. await rm(root, { recursive: true, force: true });
  263. }
  264. },
  265. );
  266. it.each(["zcode.json", ".zcode/config.json", "explicit-project.json"])(
  267. "restricts project runtime parameters while retaining extension settings in %s",
  268. async (fileName) => {
  269. const root = await mkdtemp(join(tmpdir(), "zcode-project-runtime-boundary-"));
  270. const userPath = join(root, ".zcode", "cli", "config.json");
  271. const projectPath = join(root, fileName);
  272. const skillPath = join(root, "skills", "demo", "SKILL.md");
  273. const commandPath = join(root, "commands", "demo.md");
  274. const userConfig = {
  275. network: { httpProxy: "http://user.example:8080", caCertFile: join(root, "user-ca.pem") },
  276. storage: { dir: join(root, "user-storage"), sessionDbPath: join(root, "user.sqlite") },
  277. permission: { mode: "plan", autoApproveHighRisk: false },
  278. plugins: {
  279. dirs: [join(root, "installed-plugin")],
  280. enabledPlugins: { "demo@fixture": false },
  281. },
  282. };
  283. const projectConfig = {
  284. network: {
  285. httpProxy: "http://project.example:8080",
  286. caCertFile: "./repo-ca.pem",
  287. noProxy: "*",
  288. timeout: 1,
  289. },
  290. storage: { dir: "./fake-user-storage", sessionDbPath: "./fake-session.sqlite" },
  291. permission: { mode: "yolo", autoApproveHighRisk: true },
  292. modelStream: { idleTimeoutMs: 1 },
  293. features: { mcp: false, subagent: false, memory: false, skill: false },
  294. memory: { use: false },
  295. logging: { level: "error", format: "text" },
  296. ui: { locale: "zh-CN", theme: "light" },
  297. toolConcurrency: { maxConcurrency: 1 },
  298. modelAnomalyGuard: { toolCallWarningThreshold: 1 },
  299. skills: { enabled: false, roots: ["./extra-skills"], [skillPath]: { enable: false } },
  300. command: { [commandPath]: { enable: false } },
  301. plugins: {
  302. enabled: false,
  303. dirs: ["./fake-plugin"],
  304. suppressedBuiltins: ["builtin@fixture"],
  305. extraKnownMarketplaces: {
  306. fake: { source: { source: "directory", path: "./fake-market" } },
  307. },
  308. enabledPlugins: { "demo@fixture": true },
  309. options: { "demo@fixture": { format: "compact" } },
  310. },
  311. mcp: { servers: { demo: { type: "stdio", command: "node", cwd: "./tools" } } },
  312. hooks: {
  313. events: {
  314. SessionStart: [{ hooks: [{ type: "command", command: "echo project-hook" }] }],
  315. },
  316. },
  317. };
  318. try {
  319. vi.stubEnv("HOME", root);
  320. vi.stubEnv("USERPROFILE", root);
  321. await mkdir(join(root, ".git"));
  322. await mkdir(join(root, ".zcode", "cli"), { recursive: true });
  323. await writeFile(userPath, JSON.stringify(userConfig));
  324. await writeFile(projectPath, JSON.stringify(projectConfig));
  325. const baseline = createConfig({ env: {}, userConfigPath: userPath });
  326. const result = createConfig({
  327. env: {},
  328. userConfigPath: userPath,
  329. workingDirectory: root,
  330. ...(fileName === "explicit-project.json" ? { projectConfigPath: projectPath } : {}),
  331. });
  332. for (const field of [
  333. "network",
  334. "storage",
  335. "permission",
  336. "modelStream",
  337. "features",
  338. "memory",
  339. "logging",
  340. "ui",
  341. "toolConcurrency",
  342. "modelAnomalyGuard",
  343. "skills",
  344. ] as const) {
  345. expect(result.config[field], field).toEqual(baseline.config[field]);
  346. }
  347. expect(result.config.plugins).toEqual({
  348. ...baseline.config.plugins,
  349. enabledPlugins: { "demo@fixture": true },
  350. options: {},
  351. });
  352. expect(result.config.mcp.servers.demo).toMatchObject({
  353. command: "node",
  354. cwd: join(root, "tools"),
  355. });
  356. expect(result.sources.mcp.serverSources.demo).toBe("project");
  357. expect(result.config.hooks).toEqual(baseline.config.hooks);
  358. expect(result.sources.project.workspaceHookSnapshot).toBeDefined();
  359. expect(result.config.skillOverrides[skillPath]).toEqual({ enable: false });
  360. expect(result.config.commandOverrides[commandPath]).toEqual({ enable: false });
  361. expect(result.sources.project.hasUiLocale).toBe(false);
  362. expect(result.sources.project.hasUiTheme).toBe(false);
  363. expect(resolveWorkspaceStorageDir({ env: {}, workingDirectory: root })).toBe(
  364. userConfig.storage.dir,
  365. );
  366. } finally {
  367. vi.unstubAllEnvs();
  368. await rm(root, { recursive: true, force: true });
  369. }
  370. },
  371. );
  372. it("ignores invalid project runtime fields before validating extension settings", async () => {
  373. const root = await mkdtemp(join(tmpdir(), "zcode-project-runtime-invalid-"));
  374. const projectPath = join(root, "zcode.json");
  375. const skillPath = join(root, "SKILL.md");
  376. try {
  377. await mkdir(join(root, ".git"));
  378. await writeFile(
  379. projectPath,
  380. JSON.stringify({
  381. network: { caCertFile: 123 },
  382. storage: null,
  383. permission: { mode: "invalid" },
  384. skills: { enabled: "invalid", roots: 123, [skillPath]: { enable: false } },
  385. plugins: { dirs: 123, enabled: "invalid", enabledPlugins: { "demo@fixture": true } },
  386. mcp: { servers: { demo: { type: "http", url: "https://example.com/mcp" } } },
  387. }),
  388. );
  389. const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  390. expect(result.sources.project.loaded).toBe(true);
  391. expect(result.sources.project.diagnostics).toEqual([]);
  392. expect(result.config.network.caCertFile).toBeUndefined();
  393. expect(result.config.mcp.servers.demo).toMatchObject({ url: "https://example.com/mcp" });
  394. expect(result.config.plugins.enabledPlugins["demo@fixture"]).toBe(true);
  395. expect(result.config.skillOverrides[skillPath]).toEqual({ enable: false });
  396. } finally {
  397. await rm(root, { recursive: true, force: true });
  398. }
  399. });
  400. it("migrates the legacy official CUA plugin id to the canonical id", async () => {
  401. const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-identity-"));
  402. const configPath = join(dir, "config.json");
  403. try {
  404. await writeFile(
  405. configPath,
  406. JSON.stringify({
  407. plugins: {
  408. enabledPlugins: {
  409. "zcode-cua@zcode-plugins-official": true,
  410. "computer-use@zcode-plugins-official": false,
  411. },
  412. suppressedBuiltins: [
  413. "zcode-cua@zcode-plugins-official",
  414. "computer-use@zcode-plugins-official",
  415. ],
  416. options: {
  417. "zcode-cua@zcode-plugins-official": { apiKey: "legacy-key" },
  418. "computer-use@zcode-plugins-official": { apiKey: "canonical-key" },
  419. },
  420. },
  421. }),
  422. );
  423. const loaded = loadFileConfig(configPath);
  424. expect(loaded.config.plugins?.enabledPlugins).toEqual({
  425. "computer-use@zcode-plugins-official": false,
  426. });
  427. expect(loaded.config.plugins?.suppressedBuiltins).toEqual([
  428. "computer-use@zcode-plugins-official",
  429. ]);
  430. expect(loaded.config.plugins?.options).toEqual({
  431. "computer-use@zcode-plugins-official": { apiKey: "canonical-key" },
  432. });
  433. } finally {
  434. await rm(dir, { force: true, recursive: true });
  435. }
  436. });
  437. it("persists the canonical CUA plugin id while loading legacy config", async () => {
  438. const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-writeback-"));
  439. const path = join(dir, "config.json");
  440. await writeFile(
  441. path,
  442. JSON.stringify({
  443. plugins: {
  444. enabledPlugins: { "zcode-cua@zcode-plugins-official": true },
  445. suppressedBuiltins: ["zcode-cua@zcode-plugins-official"],
  446. options: {
  447. "zcode-cua@zcode-plugins-official": { apiKey: "legacy-key" },
  448. },
  449. },
  450. }),
  451. );
  452. loadFileConfig(path);
  453. expect(JSON.parse(await readFile(path, "utf8"))).toEqual({
  454. plugins: {
  455. enabledPlugins: { "computer-use@zcode-plugins-official": true },
  456. suppressedBuiltins: ["computer-use@zcode-plugins-official"],
  457. options: {
  458. "computer-use@zcode-plugins-official": { apiKey: "legacy-key" },
  459. },
  460. },
  461. });
  462. await rm(dir, { recursive: true, force: true });
  463. });
  464. it("writes canonical CUA ids when removing legacy config entries", async () => {
  465. const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-write-migration-"));
  466. const configPath = join(dir, "config.json");
  467. try {
  468. await writeFile(
  469. configPath,
  470. JSON.stringify({
  471. plugins: {
  472. enabledPlugins: { "zcode-cua@zcode-plugins-official": true },
  473. suppressedBuiltins: ["zcode-cua@zcode-plugins-official"],
  474. },
  475. }),
  476. );
  477. expect(
  478. (
  479. await removeSuppressedBuiltinInFileConfig(
  480. configPath,
  481. "computer-use@zcode-plugins-official",
  482. )
  483. ).suppressed,
  484. ).toBe(false);
  485. expect(
  486. (await removePluginFromFileConfig(configPath, "computer-use@zcode-plugins-official"))
  487. .removedEnabled,
  488. ).toBe(true);
  489. expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
  490. plugins: { enabledPlugins: {}, suppressedBuiltins: [], options: {} },
  491. });
  492. } finally {
  493. await rm(dir, { force: true, recursive: true });
  494. }
  495. });
  496. it("clears only explicitly selected Plugin option keys", async () => {
  497. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-option-clear-"));
  498. const configPath = join(dir, "config.json");
  499. const pluginId = "secret-plugin@fixture";
  500. try {
  501. await writeFile(
  502. configPath,
  503. JSON.stringify({
  504. plugins: {
  505. enabledPlugins: { [pluginId]: true },
  506. options: {
  507. [pluginId]: {
  508. token: "secret",
  509. region: "us-east-1",
  510. },
  511. },
  512. },
  513. }),
  514. );
  515. await updatePluginOptionsInFileConfig(configPath, pluginId, { region: "eu-west-1" }, [
  516. "token",
  517. ]);
  518. expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
  519. plugins: {
  520. enabledPlugins: { [pluginId]: true },
  521. options: {
  522. [pluginId]: {
  523. region: "eu-west-1",
  524. },
  525. },
  526. },
  527. });
  528. } finally {
  529. await rm(dir, { force: true, recursive: true });
  530. }
  531. });
  532. it("merges Workspace Plugin enablement without trusting repository options", async () => {
  533. const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-plugins-"));
  534. const userPath = join(dir, "user.json");
  535. const workspacePath = join(dir, ".zcode", "config.json");
  536. try {
  537. await mkdir(join(dir, ".zcode"), { recursive: true });
  538. await writeFile(
  539. userPath,
  540. JSON.stringify({
  541. plugins: {
  542. dirs: [join(dir, "user-plugin")],
  543. enabledPlugins: {
  544. "workspace-plugin@fixture": true,
  545. "user-only@fixture": true,
  546. },
  547. options: {
  548. "workspace-plugin@fixture": {
  549. inherited: "user",
  550. overridden: "user",
  551. },
  552. },
  553. },
  554. }),
  555. );
  556. await writeFile(
  557. workspacePath,
  558. JSON.stringify({
  559. plugins: {
  560. dirs: ["./workspace-plugin", join(dir, "absolute-workspace-plugin")],
  561. enabledPlugins: {
  562. "workspace-plugin@fixture": false,
  563. },
  564. options: {
  565. "workspace-plugin@fixture": {
  566. overridden: "workspace",
  567. workspaceOnly: true,
  568. },
  569. },
  570. },
  571. }),
  572. );
  573. const result = createConfig({
  574. env: {},
  575. userConfigPath: userPath,
  576. projectConfigPath: workspacePath,
  577. workingDirectory: dir,
  578. });
  579. expect(result.config.plugins.enabledPlugins).toEqual({
  580. "workspace-plugin@fixture": false,
  581. "user-only@fixture": true,
  582. });
  583. expect(result.config.plugins.options).toEqual({
  584. "workspace-plugin@fixture": {
  585. inherited: "user",
  586. overridden: "user",
  587. },
  588. });
  589. expect(result.sources.project.paths).toEqual([workspacePath]);
  590. expect(result.sources.plugins.enabled).toEqual({
  591. "user-only@fixture": "user",
  592. "workspace-plugin@fixture": "workspace",
  593. });
  594. // 项目目录只作为待信任候选出现在 sources 里,可执行配置只有用户目录。
  595. expect(result.sources.plugins.dirs).toEqual({
  596. user: [join(dir, "user-plugin")],
  597. workspace: [join(dir, "workspace-plugin"), join(dir, "absolute-workspace-plugin")],
  598. });
  599. expect(result.config.plugins.dirs).toEqual([join(dir, "user-plugin")]);
  600. expect(result.sources.plugins.options).toEqual({
  601. "workspace-plugin@fixture": {
  602. inherited: "user",
  603. overridden: "user",
  604. },
  605. });
  606. } finally {
  607. await rm(dir, { force: true, recursive: true });
  608. }
  609. });
  610. it.each(["zcode.json", ".zcode/config.json", "explicit-project.json"])(
  611. "strips plugin options before validating project config %s",
  612. async (fileName) => {
  613. const root = await mkdtemp(join(tmpdir(), "zcode-project-plugin-options-"));
  614. const path = join(root, fileName);
  615. try {
  616. await mkdir(join(root, ".git"));
  617. await mkdir(join(root, ".zcode"));
  618. const original = JSON.stringify({
  619. plugins: {
  620. enabledPlugins: { "runner@fixture": true },
  621. options: { "runner@fixture": { pythonPath: "./repository-runner", invalid: {} } },
  622. },
  623. mcp: { servers: { kept: { type: "http", url: "https://mcp.example.com" } } },
  624. });
  625. await writeFile(path, original);
  626. const result = createConfig({
  627. env: {},
  628. skipUserConfig: true,
  629. workingDirectory: root,
  630. ...(fileName === "explicit-project.json" ? { projectConfigPath: path } : {}),
  631. });
  632. expect(result.sources.project.loaded).toBe(true);
  633. expect(result.config.plugins.options).toEqual({});
  634. expect(result.sources.plugins.options).toEqual({});
  635. expect(
  636. result.sources.plugins.optionLayers?.every(
  637. (layer) => Object.keys(layer.options).length === 0,
  638. ),
  639. ).toBe(true);
  640. expect(result.config.plugins.enabledPlugins["runner@fixture"]).toBe(true);
  641. expect(result.config.mcp.servers.kept).toBeDefined();
  642. expect(await readFile(path, "utf8")).toBe(original);
  643. } finally {
  644. await rm(root, { recursive: true, force: true });
  645. }
  646. },
  647. );
  648. it("merges skill and command toggles by path across user and project config", async () => {
  649. const dir = await mkdtemp(join(tmpdir(), "zcode-config-toggle-merge-"));
  650. const userPath = join(dir, "user.json");
  651. const workspacePath = join(dir, ".zcode", "config.json");
  652. const userSkill = join(dir, "user", "SKILL.md");
  653. const workspaceSkill = join(dir, "workspace", "SKILL.md");
  654. const userCommand = join(dir, "user", "command.md");
  655. const workspaceCommand = join(dir, "workspace", "command.md");
  656. try {
  657. await mkdir(join(dir, ".zcode"), { recursive: true });
  658. await writeFile(
  659. userPath,
  660. JSON.stringify({
  661. skills: { [userSkill]: { enable: false } },
  662. command: { [userCommand]: { enable: false } },
  663. }),
  664. );
  665. await writeFile(
  666. workspacePath,
  667. JSON.stringify({
  668. skills: { [workspaceSkill]: { enable: false } },
  669. command: { [workspaceCommand]: { enable: false } },
  670. }),
  671. );
  672. const result = createConfig({
  673. env: {},
  674. userConfigPath: userPath,
  675. projectConfigPath: workspacePath,
  676. workingDirectory: dir,
  677. });
  678. // 修复前项目层的开关整体替换了用户层的开关,用户停用的 skill 与命令重新出现。
  679. expect(result.config.skillOverrides).toEqual({
  680. [userSkill]: { enable: false },
  681. [workspaceSkill]: { enable: false },
  682. });
  683. expect(result.config.commandOverrides).toEqual({
  684. [userCommand]: { enable: false },
  685. [workspaceCommand]: { enable: false },
  686. });
  687. } finally {
  688. await rm(dir, { force: true, recursive: true });
  689. }
  690. });
  691. it.each(["zcode.json", ".zcode/config.json", "explicit-project.json"])(
  692. "keeps plugin directories from project config %s as untrusted candidates only",
  693. async (fileName) => {
  694. const dir = await mkdtemp(join(tmpdir(), "zcode-project-plugin-dirs-"));
  695. const projectConfigPath = join(dir, fileName);
  696. try {
  697. await mkdir(join(dir, ".git"));
  698. await mkdir(join(dir, ".zcode"));
  699. await writeFile(
  700. projectConfigPath,
  701. JSON.stringify({ plugins: { dirs: ["./plugin", join(dir, "absolute-plugin")] } }),
  702. );
  703. const result = createConfig({
  704. env: {},
  705. skipUserConfig: true,
  706. ...(fileName === "explicit-project.json"
  707. ? { projectConfigPath }
  708. : { workingDirectory: dir }),
  709. });
  710. expect(result.sources.project.loaded).toBe(true);
  711. // 可执行配置里永远没有项目插件目录;候选按配置文件所在项目目录解析相对路径。
  712. expect(result.config.plugins.dirs).toEqual([]);
  713. expect(result.sources.plugins.dirs.workspace).toEqual([
  714. join(dir, "plugin"),
  715. join(dir, "absolute-plugin"),
  716. ]);
  717. expect(JSON.parse(await readFile(projectConfigPath, "utf8")).plugins.dirs).toHaveLength(2);
  718. } finally {
  719. await rm(dir, { force: true, recursive: true });
  720. }
  721. },
  722. );
  723. it("ignores an invalid project plugins.dirs value without dropping other declarations", async () => {
  724. const dir = await mkdtemp(join(tmpdir(), "zcode-project-plugin-dirs-invalid-"));
  725. try {
  726. await mkdir(join(dir, ".git"));
  727. await mkdir(join(dir, ".zcode"));
  728. await writeFile(
  729. join(dir, ".zcode", "config.json"),
  730. JSON.stringify({
  731. plugins: { dirs: "./plugin", enabledPlugins: { "demo@inline": false } },
  732. mcp: { servers: { local: { type: "stdio", command: "node" } } },
  733. }),
  734. );
  735. const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: dir });
  736. expect(result.sources.plugins.dirs.workspace).toEqual([]);
  737. expect(result.config.plugins.enabledPlugins["demo@inline"]).toBe(false);
  738. expect(Object.keys(result.config.mcp.servers)).toContain("local");
  739. } finally {
  740. await rm(dir, { force: true, recursive: true });
  741. }
  742. });
  743. it("keeps Marketplace declarations in the User config layer", async () => {
  744. const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-marketplaces-"));
  745. const userPath = join(dir, "user.json");
  746. const workspacePath = join(dir, "workspace.json");
  747. try {
  748. await writeFile(
  749. userPath,
  750. JSON.stringify({
  751. plugins: {
  752. extraKnownMarketplaces: {
  753. "shared-market": {
  754. source: { source: "github", repo: "example/user-market" },
  755. },
  756. "user-market": {
  757. source: { source: "url", url: "https://example.test/user-market.json" },
  758. },
  759. },
  760. },
  761. }),
  762. );
  763. await writeFile(
  764. workspacePath,
  765. JSON.stringify({
  766. plugins: {
  767. extraKnownMarketplaces: {
  768. "shared-market": {
  769. source: { source: "directory", path: "./workspace-market" },
  770. },
  771. "workspace-market": {
  772. source: { source: "file", path: "./workspace-market.json" },
  773. },
  774. },
  775. },
  776. }),
  777. );
  778. const result = createConfig({
  779. env: {},
  780. userConfigPath: userPath,
  781. projectConfigPath: workspacePath,
  782. });
  783. expect(result.config.plugins.extraKnownMarketplaces).toEqual({
  784. "shared-market": {
  785. source: { source: "github", repo: "example/user-market" },
  786. },
  787. "user-market": {
  788. source: { source: "url", url: "https://example.test/user-market.json" },
  789. },
  790. });
  791. expect(result.sources.plugins.marketplaces).toEqual({
  792. "shared-market": "user",
  793. "user-market": "user",
  794. });
  795. } finally {
  796. await rm(dir, { force: true, recursive: true });
  797. }
  798. });
  799. it("parses the supported ZCODE environment surface", () => {
  800. const config = parseEnvConfig({
  801. ZCODE_STORAGE_DIR: "/tmp/zcode",
  802. ZCODE_HTTP_PROXY: "http://127.0.0.1:7890",
  803. ZCODE_NO_PROXY: "localhost,127.0.0.1",
  804. ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem",
  805. ZCODE_HTTP_TIMEOUT: "1234",
  806. ZCODE_LOCALE: "zh-CN",
  807. ZCODE_LOG_FORMAT: "json",
  808. });
  809. expect(config.model).toBeUndefined();
  810. expect(config.storage?.dir).toBe("/tmp/zcode");
  811. expect(config.network?.httpProxy).toBe("http://127.0.0.1:7890");
  812. expect(config.network?.noProxy).toBe("localhost,127.0.0.1");
  813. expect(config.network?.caCertFile).toBe("/tmp/zcode-ca.pem");
  814. expect(config.network?.timeout).toBe(1234);
  815. expect(config.ui).toBeUndefined();
  816. expect(config.logging?.format).toBe("json");
  817. expect(config.logging?.level).toBeUndefined();
  818. });
  819. it("loads the supported memory config fields", async () => {
  820. const dir = await mkdtemp(join(tmpdir(), "zcode-config-memory-"));
  821. const path = join(dir, "config.json");
  822. try {
  823. await writeFile(
  824. path,
  825. JSON.stringify({
  826. memory: {
  827. use: false,
  828. },
  829. }),
  830. );
  831. const loaded = loadFileConfig(path);
  832. const merged = createConfig({ env: {}, userConfigPath: path });
  833. expect(loaded.loaded).toBe(true);
  834. expect(loaded.config.memory).toEqual({
  835. use: false,
  836. });
  837. expect(merged.config.memory).toEqual({
  838. use: false,
  839. });
  840. } finally {
  841. await rm(dir, { force: true, recursive: true });
  842. }
  843. });
  844. it("parses session database path environment overrides", () => {
  845. expect(
  846. parseEnvConfig({
  847. ZCODE_SESSION_DB_PATH: "/tmp/zcode/db/db.sqlite",
  848. }).storage?.sessionDbPath,
  849. ).toBe("/tmp/zcode/db/db.sqlite");
  850. expect(
  851. parseEnvConfig({
  852. ZCODE_SESSION_DB: "/tmp/zcode/legacy.sqlite",
  853. }).storage?.sessionDbPath,
  854. ).toBe("/tmp/zcode/legacy.sqlite");
  855. });
  856. it("loads no-proxy rules from file config", async () => {
  857. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  858. const path = join(dir, "config.json");
  859. try {
  860. await writeFile(
  861. path,
  862. JSON.stringify({
  863. network: {
  864. httpProxy: "http://127.0.0.1:7890",
  865. noProxy: "localhost,127.0.0.1",
  866. caCertFile: "/tmp/zcode-ca.pem",
  867. },
  868. }),
  869. );
  870. const merged = createConfig({ env: {}, userConfigPath: path });
  871. expect(merged.config.network.httpProxy).toBe("http://127.0.0.1:7890");
  872. expect(merged.config.network.noProxy).toBe("localhost,127.0.0.1");
  873. expect(merged.config.network.caCertFile).toBe("/tmp/zcode-ca.pem");
  874. } finally {
  875. await rm(dir, { force: true, recursive: true });
  876. }
  877. });
  878. it("ignores undeclared ZCODE environment switches", () => {
  879. const config = parseEnvConfig({
  880. ZCODE_LOG_LEVEL: "debug",
  881. ZCODE_UNDECLARED_FLAG: "1",
  882. });
  883. expect(config).toEqual({});
  884. });
  885. it("loads yolo mode from file config", async () => {
  886. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  887. const path = join(dir, "config.json");
  888. try {
  889. await writeFile(path, JSON.stringify({ permission: { mode: "yolo" } }));
  890. const result = loadFileConfig(path);
  891. expect(result.loaded).toBe(true);
  892. expect(result.config.permission?.mode).toBe("yolo");
  893. } finally {
  894. await rm(dir, { force: true, recursive: true });
  895. }
  896. });
  897. it("loads edit mode from file config", async () => {
  898. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  899. const path = join(dir, "config.json");
  900. try {
  901. await writeFile(path, JSON.stringify({ permission: { mode: "edit" } }));
  902. const result = loadFileConfig(path);
  903. expect(result.loaded).toBe(true);
  904. expect(result.config.permission?.mode).toBe("edit");
  905. } finally {
  906. await rm(dir, { force: true, recursive: true });
  907. }
  908. });
  909. it("loads skill/command enable overrides from file config", async () => {
  910. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  911. const path = join(dir, "config.json");
  912. try {
  913. await writeFile(
  914. path,
  915. JSON.stringify({
  916. skill: { "/abs/skills/demo/SKILL.md": { enable: false } },
  917. command: { "/abs/commands/demo.md": { enable: false } },
  918. }),
  919. );
  920. const result = loadFileConfig(path);
  921. const merged = createConfig({ env: {}, userConfigPath: path });
  922. expect(result.loaded).toBe(true);
  923. // JSON 的 skill/command 字段映射到 runtime 的 skillOverrides/commandOverrides
  924. expect(result.config.skillOverrides?.["/abs/skills/demo/SKILL.md"]?.enable).toBe(false);
  925. expect(result.config.commandOverrides?.["/abs/commands/demo.md"]?.enable).toBe(false);
  926. expect(merged.config.skillOverrides["/abs/skills/demo/SKILL.md"]?.enable).toBe(false);
  927. expect(merged.config.commandOverrides["/abs/commands/demo.md"]?.enable).toBe(false);
  928. } finally {
  929. await rm(dir, { force: true, recursive: true });
  930. }
  931. });
  932. it("parses plugins.suppressedBuiltins as a string array", async () => {
  933. const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppressed-"));
  934. const path = join(dir, "config.json");
  935. await writeFile(
  936. path,
  937. JSON.stringify({ plugins: { suppressedBuiltins: ["skill-creator@zcode-plugins-official"] } }),
  938. );
  939. const loaded = loadFileConfig(path);
  940. expect(loaded.config.plugins.suppressedBuiltins).toEqual([
  941. "skill-creator@zcode-plugins-official",
  942. ]);
  943. });
  944. it("maps skills path enable entries to skill overrides", async () => {
  945. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  946. const path = join(dir, "config.json");
  947. try {
  948. await writeFile(
  949. path,
  950. JSON.stringify({
  951. skills: {
  952. enabled: true,
  953. roots: ["/abs/skills"],
  954. "/abs/skills/disabled/SKILL.md": { enable: false },
  955. "/abs/skills/enabled/SKILL.md": { enable: true },
  956. },
  957. }),
  958. );
  959. const result = loadFileConfig(path);
  960. const merged = createConfig({ env: {}, userConfigPath: path });
  961. expect(result.loaded).toBe(true);
  962. expect(result.config.skills).toEqual({
  963. enabled: true,
  964. roots: ["/abs/skills"],
  965. });
  966. expect(result.config.skillOverrides?.["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false);
  967. expect(result.config.skillOverrides?.["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true);
  968. expect(merged.config.skillOverrides["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false);
  969. expect(merged.config.skillOverrides["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true);
  970. } finally {
  971. await rm(dir, { force: true, recursive: true });
  972. }
  973. });
  974. it("loads top-level skills config from file config", async () => {
  975. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  976. const path = join(dir, "config.json");
  977. try {
  978. await writeFile(
  979. path,
  980. JSON.stringify({
  981. skills: {
  982. enabled: false,
  983. includeInstructions: false,
  984. metadataBudget: 1024,
  985. roots: ["/abs/skills"],
  986. },
  987. }),
  988. );
  989. const result = loadFileConfig(path);
  990. const merged = createConfig({ env: {}, userConfigPath: path });
  991. expect(result.loaded).toBe(true);
  992. expect(result.config.skills).toEqual({
  993. enabled: false,
  994. includeInstructions: false,
  995. metadataBudget: 1024,
  996. roots: ["/abs/skills"],
  997. });
  998. expect(merged.config.skills.enabled).toBe(false);
  999. expect(merged.config.skills.includeInstructions).toBe(false);
  1000. expect(merged.config.skills.metadataBudget).toBe(1024);
  1001. expect(merged.config.skills.roots).toEqual(["/abs/skills"]);
  1002. } finally {
  1003. await rm(dir, { force: true, recursive: true });
  1004. }
  1005. });
  1006. it("loads UI locale from file config", async () => {
  1007. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1008. const path = join(dir, "config.json");
  1009. try {
  1010. await writeFile(path, JSON.stringify({ ui: { locale: "zh-CN" } }));
  1011. const result = loadFileConfig(path);
  1012. const merged = createConfig({ env: {}, userConfigPath: path });
  1013. expect(result.loaded).toBe(true);
  1014. expect(result.config.ui?.locale).toBe("zh-CN");
  1015. expect(merged.config.ui.locale).toBe("zh-CN");
  1016. } finally {
  1017. await rm(dir, { force: true, recursive: true });
  1018. }
  1019. });
  1020. it("loads auto UI locale from file config", async () => {
  1021. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1022. const path = join(dir, "config.json");
  1023. try {
  1024. await writeFile(path, JSON.stringify({ ui: { locale: "auto" } }));
  1025. const result = loadFileConfig(path);
  1026. const merged = createConfig({ env: {}, userConfigPath: path });
  1027. expect(result.loaded).toBe(true);
  1028. expect(result.config.ui?.locale).toBe("auto");
  1029. expect(merged.config.ui.locale).toBe("auto");
  1030. } finally {
  1031. await rm(dir, { force: true, recursive: true });
  1032. }
  1033. });
  1034. it("loads UI theme from file config", async () => {
  1035. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1036. const path = join(dir, "config.json");
  1037. try {
  1038. await writeFile(path, JSON.stringify({ ui: { theme: "light" } }));
  1039. const result = loadFileConfig(path);
  1040. const merged = createConfig({ env: {}, userConfigPath: path });
  1041. expect(result.loaded).toBe(true);
  1042. expect(result.config.ui?.theme).toBe("light");
  1043. expect(merged.config.ui.theme).toBe("light");
  1044. } finally {
  1045. await rm(dir, { force: true, recursive: true });
  1046. }
  1047. });
  1048. it("rejects unsupported UI theme values from file config", async () => {
  1049. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1050. const path = join(dir, "config.json");
  1051. try {
  1052. await writeFile(path, JSON.stringify({ ui: { theme: "sepia" } }));
  1053. const result = loadFileConfig(path);
  1054. expect(result.loaded).toBe(false);
  1055. expect(result.config.ui).toBeUndefined();
  1056. } finally {
  1057. await rm(dir, { force: true, recursive: true });
  1058. }
  1059. });
  1060. it("patches UI locale while preserving unrelated config fields", async () => {
  1061. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1062. const path = join(dir, "config.json");
  1063. try {
  1064. await writeFile(
  1065. path,
  1066. JSON.stringify({
  1067. model: {
  1068. main: "openai/gpt-5.1",
  1069. },
  1070. permission: {
  1071. mode: "plan",
  1072. },
  1073. ui: {
  1074. density: "compact",
  1075. locale: "en-US",
  1076. },
  1077. }),
  1078. );
  1079. const result = await updateUiLocaleInFileConfig(path, "zh-CN");
  1080. const written = JSON.parse(await readFile(path, "utf-8"));
  1081. expect(result).toEqual({
  1082. locale: "zh-CN",
  1083. path,
  1084. });
  1085. expect(written).toMatchObject({
  1086. model: {
  1087. main: "openai/gpt-5.1",
  1088. },
  1089. permission: {
  1090. mode: "plan",
  1091. },
  1092. ui: {
  1093. density: "compact",
  1094. locale: "zh-CN",
  1095. },
  1096. });
  1097. } finally {
  1098. await rm(dir, { force: true, recursive: true });
  1099. }
  1100. });
  1101. it("creates config files when patching UI locale", async () => {
  1102. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1103. const path = join(dir, "nested", "config.json");
  1104. try {
  1105. await updateUiLocaleInFileConfig(path, "auto");
  1106. const written = JSON.parse(await readFile(path, "utf-8"));
  1107. expect(written).toEqual({
  1108. ui: {
  1109. locale: "auto",
  1110. },
  1111. });
  1112. } finally {
  1113. await rm(dir, { force: true, recursive: true });
  1114. }
  1115. });
  1116. it("rejects unsupported UI locale values from file config", async () => {
  1117. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1118. const path = join(dir, "config.json");
  1119. try {
  1120. await writeFile(path, JSON.stringify({ ui: { locale: "fr-FR" } }));
  1121. const result = loadFileConfig(path);
  1122. expect(result.loaded).toBe(false);
  1123. expect(result.config.ui).toBeUndefined();
  1124. } finally {
  1125. await rm(dir, { force: true, recursive: true });
  1126. }
  1127. });
  1128. it("loads MCP server config from file config", async () => {
  1129. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1130. const path = join(dir, "config.json");
  1131. try {
  1132. await writeFile(
  1133. path,
  1134. JSON.stringify({
  1135. features: {
  1136. mcp: true,
  1137. },
  1138. mcp: {
  1139. servers: {
  1140. local: {
  1141. type: "stdio",
  1142. command: "node",
  1143. args: ["server.js"],
  1144. cwd: ".",
  1145. env: {
  1146. EXAMPLE: "1",
  1147. },
  1148. },
  1149. remote: {
  1150. type: "http",
  1151. url: "https://example.com/mcp",
  1152. headers: {
  1153. Authorization: "Bearer token",
  1154. },
  1155. oauth: {
  1156. type: "client_credentials",
  1157. clientId: "zcode-client",
  1158. clientSecret: "secret",
  1159. scope: "mcp:tools",
  1160. },
  1161. timeoutMs: 30000,
  1162. },
  1163. events: {
  1164. type: "sse",
  1165. url: "https://example.com/sse",
  1166. oauth: {
  1167. type: "authorization_code",
  1168. clientName: "ZCode",
  1169. redirectPath: "/oauth/callback/mcp/figma",
  1170. scope: "mcp:connect",
  1171. },
  1172. enabled: false,
  1173. },
  1174. },
  1175. },
  1176. }),
  1177. );
  1178. const result = loadFileConfig(path);
  1179. expect(result.loaded).toBe(true);
  1180. expect(result.config.features?.mcp).toBe(true);
  1181. expect(result.config.mcp?.servers?.local).toMatchObject({
  1182. type: "stdio",
  1183. command: "node",
  1184. args: ["server.js"],
  1185. });
  1186. expect(result.config.mcp?.servers?.remote).toMatchObject({
  1187. type: "http",
  1188. url: "https://example.com/mcp",
  1189. oauth: {
  1190. type: "client_credentials",
  1191. clientId: "zcode-client",
  1192. clientSecret: "secret",
  1193. scope: "mcp:tools",
  1194. },
  1195. timeoutMs: 30000,
  1196. });
  1197. expect(result.config.mcp?.servers?.events).toMatchObject({
  1198. type: "sse",
  1199. oauth: {
  1200. type: "authorization_code",
  1201. clientName: "ZCode",
  1202. redirectPath: "/oauth/callback/mcp/figma",
  1203. scope: "mcp:connect",
  1204. },
  1205. enabled: false,
  1206. });
  1207. } finally {
  1208. await rm(dir, { force: true, recursive: true });
  1209. }
  1210. });
  1211. it("keeps an MCP server disabled when legacy enable:false coexists with enabled:true", async () => {
  1212. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1213. const path = join(dir, "config.json");
  1214. try {
  1215. await writeFile(
  1216. path,
  1217. JSON.stringify({
  1218. mcp: {
  1219. servers: {
  1220. // 桌面端「停用」写入 enable:false,而外部导入/手工编辑的同一条配置里
  1221. // 已经带着 enabled:true。禁用意图必须胜出。
  1222. playwright: {
  1223. type: "stdio",
  1224. command: "npx",
  1225. args: ["-y", "@playwright/mcp@latest"],
  1226. enable: false,
  1227. enabled: true,
  1228. },
  1229. },
  1230. },
  1231. }),
  1232. );
  1233. const result = loadFileConfig(path);
  1234. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false);
  1235. } finally {
  1236. await rm(dir, { force: true, recursive: true });
  1237. }
  1238. });
  1239. it("keeps an MCP server disabled when enabled:false coexists with legacy enable:true", async () => {
  1240. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1241. const path = join(dir, "config.json");
  1242. try {
  1243. await writeFile(
  1244. path,
  1245. JSON.stringify({
  1246. mcp: {
  1247. servers: {
  1248. playwright: {
  1249. type: "stdio",
  1250. command: "npx",
  1251. args: ["-y", "@playwright/mcp@latest"],
  1252. enable: true,
  1253. enabled: false,
  1254. },
  1255. },
  1256. },
  1257. }),
  1258. );
  1259. const result = loadFileConfig(path);
  1260. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false);
  1261. } finally {
  1262. await rm(dir, { force: true, recursive: true });
  1263. }
  1264. });
  1265. it("keeps an MCP server enabled when both enable and enabled are true", async () => {
  1266. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1267. const path = join(dir, "config.json");
  1268. try {
  1269. await writeFile(
  1270. path,
  1271. JSON.stringify({
  1272. mcp: {
  1273. servers: {
  1274. playwright: {
  1275. type: "stdio",
  1276. command: "npx",
  1277. args: ["-y", "@playwright/mcp@latest"],
  1278. enable: true,
  1279. enabled: true,
  1280. },
  1281. },
  1282. },
  1283. }),
  1284. );
  1285. const result = loadFileConfig(path);
  1286. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(true);
  1287. } finally {
  1288. await rm(dir, { force: true, recursive: true });
  1289. }
  1290. });
  1291. it("preserves fresh HTTP MCP config without writing implicit OAuth", async () => {
  1292. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1293. const path = join(dir, "config.json");
  1294. try {
  1295. await writeFile(
  1296. path,
  1297. JSON.stringify({
  1298. mcp: {
  1299. servers: {
  1300. notion: {
  1301. type: "http",
  1302. url: "https://mcp.notion.com/mcp",
  1303. timeoutMs: 30000,
  1304. },
  1305. },
  1306. },
  1307. }),
  1308. );
  1309. const result = loadFileConfig(path);
  1310. expect(result.loaded).toBe(true);
  1311. expect(result.config.mcp?.servers?.notion).toMatchObject({
  1312. type: "http",
  1313. url: "https://mcp.notion.com/mcp",
  1314. timeoutMs: 30000,
  1315. });
  1316. expect(result.config.mcp?.servers?.notion?.oauth).toBeUndefined();
  1317. } finally {
  1318. await rm(dir, { force: true, recursive: true });
  1319. }
  1320. });
  1321. it("skips invalid MCP OAuth config without dropping unrelated config", async () => {
  1322. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1323. const path = join(dir, "config.json");
  1324. try {
  1325. await writeFile(
  1326. path,
  1327. JSON.stringify({
  1328. mcp: {
  1329. servers: {
  1330. broken: {
  1331. type: "http",
  1332. url: "https://example.com/mcp",
  1333. oauth: {
  1334. type: "client_credentials",
  1335. clientId: "zcode-client",
  1336. },
  1337. },
  1338. },
  1339. },
  1340. plugins: {
  1341. enabled: true,
  1342. },
  1343. }),
  1344. );
  1345. const result = loadFileConfig(path);
  1346. expect(result.loaded).toBe(true);
  1347. expect(result.config.mcp?.servers).not.toHaveProperty("broken");
  1348. expect(result.config.plugins?.enabled).toBe(true);
  1349. expect(result.diagnostics).toEqual([
  1350. expect.objectContaining({
  1351. code: "config_mcp_server_invalid",
  1352. path: "mcp.servers.broken",
  1353. severity: "warning",
  1354. }),
  1355. ]);
  1356. } finally {
  1357. await rm(dir, { force: true, recursive: true });
  1358. }
  1359. });
  1360. it("normalizes app-managed MCP config aliases from file config", async () => {
  1361. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1362. const path = join(dir, "config.json");
  1363. try {
  1364. await writeFile(
  1365. path,
  1366. JSON.stringify({
  1367. mcp: {
  1368. servers: {
  1369. "figma-dev-mode-mcp-server": {
  1370. type: "stdio",
  1371. command: "npx",
  1372. args: ["-y", "figma-developer-mcp"],
  1373. enable: false,
  1374. },
  1375. "chrome-devtools": {
  1376. command: "npx",
  1377. args: ["-y", "chrome-devtools-mcp@latest"],
  1378. },
  1379. node_repl: {
  1380. command: "/opt/tools/node_repl",
  1381. args: [],
  1382. timeout: 30,
  1383. startup_timeout_sec: 120,
  1384. },
  1385. },
  1386. },
  1387. }),
  1388. );
  1389. const result = loadFileConfig(path);
  1390. expect(result.loaded).toBe(true);
  1391. expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).toMatchObject({
  1392. type: "stdio",
  1393. command: "npx",
  1394. enabled: false,
  1395. });
  1396. expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).not.toHaveProperty(
  1397. "enable",
  1398. );
  1399. expect(result.config.mcp?.servers?.["chrome-devtools"]).toMatchObject({
  1400. type: "stdio",
  1401. command: "npx",
  1402. args: ["-y", "chrome-devtools-mcp@latest"],
  1403. });
  1404. expect(result.config.mcp?.servers?.node_repl).toMatchObject({
  1405. type: "stdio",
  1406. command: "/opt/tools/node_repl",
  1407. });
  1408. expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("timeout");
  1409. expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("startup_timeout_sec");
  1410. } finally {
  1411. await rm(dir, { force: true, recursive: true });
  1412. }
  1413. });
  1414. it("normalizes legacy MCP http_headers to runtime headers", async () => {
  1415. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1416. const path = join(dir, "config.json");
  1417. try {
  1418. await writeFile(
  1419. path,
  1420. JSON.stringify({
  1421. mcp: {
  1422. servers: {
  1423. web_search_prime: {
  1424. type: "http",
  1425. url: "https://bigmodel.example.test/mcp",
  1426. http_headers: {
  1427. Authorization: "Bearer token",
  1428. },
  1429. },
  1430. },
  1431. },
  1432. }),
  1433. );
  1434. const result = loadFileConfig(path);
  1435. expect(result.loaded).toBe(true);
  1436. expect(result.config.mcp?.servers?.web_search_prime).toMatchObject({
  1437. type: "http",
  1438. headers: {
  1439. Authorization: "Bearer token",
  1440. },
  1441. });
  1442. expect(result.config.mcp?.servers?.web_search_prime).not.toHaveProperty("http_headers");
  1443. } finally {
  1444. await rm(dir, { force: true, recursive: true });
  1445. }
  1446. });
  1447. it("normalizes legacy MCP remote/environment fields without dropping plugins config", async () => {
  1448. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1449. const path = join(dir, "config.json");
  1450. try {
  1451. await writeFile(
  1452. path,
  1453. JSON.stringify({
  1454. mcp: {
  1455. servers: {
  1456. "GLM-Image-MCP": {
  1457. enabled: true,
  1458. environment: {
  1459. Z_AI_API_KEY: "test-key",
  1460. Z_AI_MODE: "ZHIPU",
  1461. },
  1462. command: "npx",
  1463. args: ["-y", "@z_ai/mcp-server"],
  1464. type: "stdio",
  1465. },
  1466. "GLM-WebReader-MCP": {
  1467. enabled: true,
  1468. headers: {
  1469. Authorization: "Bearer token",
  1470. },
  1471. type: "remote",
  1472. url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp",
  1473. },
  1474. },
  1475. },
  1476. plugins: {
  1477. enabledPlugins: {
  1478. "superpowers@zcode-plugins-official": true,
  1479. "skill-creator@zcode-plugins-official": false,
  1480. },
  1481. },
  1482. }),
  1483. );
  1484. const result = loadFileConfig(path);
  1485. const merged = createConfig({ env: {}, userConfigPath: path });
  1486. expect(result.loaded).toBe(true);
  1487. expect(result.diagnostics).toEqual([]);
  1488. expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).toMatchObject({
  1489. type: "stdio",
  1490. env: {
  1491. Z_AI_API_KEY: "test-key",
  1492. Z_AI_MODE: "ZHIPU",
  1493. },
  1494. });
  1495. expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).not.toHaveProperty("environment");
  1496. expect(result.config.mcp?.servers?.["GLM-WebReader-MCP"]).toMatchObject({
  1497. headers: {
  1498. Authorization: "Bearer token",
  1499. },
  1500. type: "http",
  1501. url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp",
  1502. });
  1503. expect(merged.config.plugins.enabledPlugins).toMatchObject({
  1504. "skill-creator@zcode-plugins-official": false,
  1505. "superpowers@zcode-plugins-official": true,
  1506. });
  1507. } finally {
  1508. await rm(dir, { force: true, recursive: true });
  1509. }
  1510. });
  1511. it("keeps non-MCP config when one MCP server is invalid", async () => {
  1512. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1513. const logDir = join(dir, "log");
  1514. const path = join(dir, "config.json");
  1515. try {
  1516. await writeFile(
  1517. path,
  1518. JSON.stringify({
  1519. mcp: {
  1520. servers: {
  1521. valid: {
  1522. type: "remote",
  1523. url: "https://example.com/mcp",
  1524. },
  1525. broken: {
  1526. type: "stdio",
  1527. args: ["server.js"],
  1528. },
  1529. },
  1530. },
  1531. plugins: {
  1532. enabledPlugins: {
  1533. "android-emulator@zcode-plugins-official": true,
  1534. },
  1535. },
  1536. }),
  1537. );
  1538. const result = loadFileConfig(path);
  1539. const merged = createConfig({
  1540. env: { ZCODE_LOG_DIR: logDir },
  1541. userConfigPath: path,
  1542. });
  1543. expect(result.loaded).toBe(true);
  1544. expect(result.config.mcp?.servers?.valid).toMatchObject({
  1545. type: "http",
  1546. url: "https://example.com/mcp",
  1547. });
  1548. expect(result.config.mcp?.servers).not.toHaveProperty("broken");
  1549. expect(
  1550. result.config.plugins?.enabledPlugins?.["android-emulator@zcode-plugins-official"],
  1551. ).toBe(true);
  1552. expect(result.diagnostics).toEqual([
  1553. expect.objectContaining({
  1554. code: "config_mcp_server_invalid",
  1555. path: "mcp.servers.broken",
  1556. severity: "warning",
  1557. }),
  1558. ]);
  1559. expect(merged.sources.user.diagnostics).toEqual(result.diagnostics);
  1560. expect(merged.config.plugins.enabledPlugins["android-emulator@zcode-plugins-official"]).toBe(
  1561. true,
  1562. );
  1563. await expect(readLogEntries(logDir)).resolves.toEqual([
  1564. expect.objectContaining({
  1565. event: "config.mcp_server.skipped",
  1566. level: "warn",
  1567. message: "MCP server config skipped",
  1568. module: "adapters.config",
  1569. context: expect.objectContaining({
  1570. configPath: path,
  1571. configScope: "user",
  1572. diagnosticCode: "config_mcp_server_invalid",
  1573. diagnosticPath: "mcp.servers.broken",
  1574. }),
  1575. }),
  1576. ]);
  1577. } finally {
  1578. await rm(dir, { force: true, recursive: true });
  1579. }
  1580. });
  1581. it("reports invalid discovered project config diagnostics", async () => {
  1582. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1583. const logDir = join(root, "log");
  1584. const projectConfigPath = join(root, "zcode.json");
  1585. try {
  1586. await mkdir(join(root, ".git"));
  1587. await writeFile(
  1588. projectConfigPath,
  1589. JSON.stringify({
  1590. hooks: {
  1591. enabled: "invalid",
  1592. },
  1593. }),
  1594. );
  1595. const result = createConfig({
  1596. env: { ZCODE_LOG_DIR: logDir },
  1597. skipUserConfig: true,
  1598. workingDirectory: root,
  1599. });
  1600. expect(result.sources.project.loaded).toBe(false);
  1601. expect(result.sources.project.diagnostics).toEqual([
  1602. expect.objectContaining({
  1603. code: "config_file_invalid",
  1604. message: expect.stringContaining("hooks.enabled: Invalid input: expected boolean"),
  1605. severity: "error",
  1606. }),
  1607. ]);
  1608. await expect(readLogEntries(logDir)).resolves.toEqual([
  1609. expect.objectContaining({
  1610. event: "config.file.invalid",
  1611. level: "warn",
  1612. message: "Config file failed to load",
  1613. module: "adapters.config",
  1614. context: expect.objectContaining({
  1615. configPath: projectConfigPath,
  1616. configScope: "project",
  1617. diagnosticCode: "config_file_invalid",
  1618. }),
  1619. }),
  1620. ]);
  1621. } finally {
  1622. await rm(root, { force: true, recursive: true });
  1623. }
  1624. });
  1625. it("discovers project MCP config from the worktree root", async () => {
  1626. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1627. const cwd = join(root, "packages", "app");
  1628. try {
  1629. await mkdir(join(root, ".git"));
  1630. await mkdir(cwd, { recursive: true });
  1631. await writeFile(
  1632. join(root, "zcode.json"),
  1633. JSON.stringify({
  1634. mcp: {
  1635. servers: {
  1636. project: {
  1637. type: "stdio",
  1638. command: "node",
  1639. args: ["server.js"],
  1640. cwd: "tools",
  1641. },
  1642. },
  1643. },
  1644. }),
  1645. );
  1646. const result = createConfig({
  1647. env: {},
  1648. skipUserConfig: true,
  1649. workingDirectory: cwd,
  1650. });
  1651. expect(result.sources.project.loaded).toBe(true);
  1652. expect(result.sources.project.paths).toEqual([join(root, "zcode.json")]);
  1653. expect(result.sources.project.mcpServerNames).toEqual(["project"]);
  1654. expect(result.config.mcp.servers.project).toMatchObject({
  1655. type: "stdio",
  1656. command: "node",
  1657. cwd: join(root, "tools"),
  1658. });
  1659. } finally {
  1660. await rm(root, { force: true, recursive: true });
  1661. }
  1662. });
  1663. it("merges project configs from root to cwd with nearest config winning", async () => {
  1664. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1665. const cwd = join(root, "packages", "app");
  1666. const cwdConfigDir = join(cwd, ".zcode");
  1667. try {
  1668. await mkdir(join(root, ".git"));
  1669. await mkdir(cwdConfigDir, { recursive: true });
  1670. await writeFile(
  1671. join(root, "zcode.json"),
  1672. JSON.stringify({
  1673. mcp: {
  1674. servers: {
  1675. project: {
  1676. type: "stdio",
  1677. command: "root-server",
  1678. },
  1679. },
  1680. },
  1681. }),
  1682. );
  1683. await writeFile(
  1684. join(cwdConfigDir, "config.json"),
  1685. JSON.stringify({
  1686. mcp: {
  1687. servers: {
  1688. project: {
  1689. type: "stdio",
  1690. command: "nearest-server",
  1691. },
  1692. },
  1693. },
  1694. }),
  1695. );
  1696. const result = createConfig({
  1697. env: {},
  1698. skipUserConfig: true,
  1699. workingDirectory: cwd,
  1700. });
  1701. expect(result.sources.project.paths).toEqual([
  1702. join(root, "zcode.json"),
  1703. join(cwdConfigDir, "config.json"),
  1704. ]);
  1705. expect(result.config.mcp.servers.project).toMatchObject({
  1706. type: "stdio",
  1707. command: "nearest-server",
  1708. cwd,
  1709. });
  1710. } finally {
  1711. await rm(root, { force: true, recursive: true });
  1712. }
  1713. });
  1714. it("lets user MCP servers override same-name project MCP servers", async () => {
  1715. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1716. const userConfigPath = join(root, "home", "config.json");
  1717. try {
  1718. await mkdir(join(root, ".git"));
  1719. await mkdir(join(root, "home"), { recursive: true });
  1720. await writeFile(
  1721. join(root, "zcode.json"),
  1722. JSON.stringify({
  1723. mcp: {
  1724. servers: {
  1725. projectOnly: {
  1726. type: "stdio",
  1727. command: "project-only-server",
  1728. },
  1729. shared: {
  1730. type: "stdio",
  1731. command: "project-server",
  1732. },
  1733. },
  1734. },
  1735. }),
  1736. );
  1737. await writeFile(
  1738. userConfigPath,
  1739. JSON.stringify({
  1740. mcp: {
  1741. servers: {
  1742. shared: {
  1743. type: "stdio",
  1744. command: "user-server",
  1745. },
  1746. userOnly: {
  1747. type: "stdio",
  1748. command: "user-only-server",
  1749. },
  1750. },
  1751. },
  1752. }),
  1753. );
  1754. const result = createConfig({
  1755. env: {},
  1756. userConfigPath,
  1757. workingDirectory: root,
  1758. });
  1759. expect(result.config.mcp.servers.shared).toMatchObject({
  1760. type: "stdio",
  1761. command: "user-server",
  1762. });
  1763. expect(result.config.mcp.servers.projectOnly).toMatchObject({
  1764. command: "project-only-server",
  1765. });
  1766. expect(result.config.mcp.servers.userOnly).toMatchObject({
  1767. command: "user-only-server",
  1768. });
  1769. expect(result.sources.user.mcpServerNames).toEqual(["shared", "userOnly"]);
  1770. expect(result.sources.project.mcpServerNames.toSorted()).toEqual(["projectOnly", "shared"]);
  1771. expect(result.sources.mcp.serverSources).toMatchObject({
  1772. projectOnly: "project",
  1773. shared: "user",
  1774. userOnly: "user",
  1775. });
  1776. } finally {
  1777. await rm(root, { force: true, recursive: true });
  1778. }
  1779. });
  1780. it("does not scan project config above the worktree root", async () => {
  1781. const parent = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1782. const root = join(parent, "repo");
  1783. const cwd = join(root, "packages", "app");
  1784. try {
  1785. await mkdir(join(root, ".git"), { recursive: true });
  1786. await mkdir(cwd, { recursive: true });
  1787. await writeFile(
  1788. join(parent, "zcode.json"),
  1789. JSON.stringify({
  1790. mcp: {
  1791. servers: {
  1792. parent: {
  1793. type: "stdio",
  1794. command: "parent-server",
  1795. },
  1796. },
  1797. },
  1798. }),
  1799. );
  1800. const result = createConfig({
  1801. env: {},
  1802. skipUserConfig: true,
  1803. workingDirectory: cwd,
  1804. });
  1805. expect(result.sources.project.loaded).toBe(false);
  1806. expect(result.config.mcp.servers.parent).toBeUndefined();
  1807. } finally {
  1808. await rm(parent, { force: true, recursive: true });
  1809. }
  1810. });
  1811. it("keeps CLI feature overrides above project MCP config", async () => {
  1812. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1813. try {
  1814. await mkdir(join(root, ".git"));
  1815. await writeFile(
  1816. join(root, "zcode.json"),
  1817. JSON.stringify({
  1818. features: {
  1819. mcp: true,
  1820. },
  1821. }),
  1822. );
  1823. const result = createConfig({
  1824. cliOverrides: {
  1825. features: {
  1826. mcp: false,
  1827. },
  1828. },
  1829. env: {},
  1830. skipUserConfig: true,
  1831. workingDirectory: root,
  1832. });
  1833. expect(result.config.features.mcp).toBe(false);
  1834. } finally {
  1835. await rm(root, { force: true, recursive: true });
  1836. }
  1837. });
  1838. it("loads process hook config from file config", async () => {
  1839. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1840. const path = join(dir, "config.json");
  1841. try {
  1842. await writeFile(
  1843. path,
  1844. JSON.stringify({
  1845. hooks: {
  1846. enabled: true,
  1847. timeoutMs: 5000,
  1848. maxOutputBytes: 8192,
  1849. events: {
  1850. PreToolUse: [
  1851. {
  1852. matcher: "Bash",
  1853. hooks: [
  1854. {
  1855. type: "process",
  1856. command: "node",
  1857. args: ["hooks/pre-tool.js"],
  1858. enabled: false,
  1859. customFlag: "keep",
  1860. },
  1861. ],
  1862. },
  1863. ],
  1864. },
  1865. },
  1866. }),
  1867. );
  1868. const result = loadFileConfig(path);
  1869. expect(result.loaded).toBe(true);
  1870. expect(result.config.hooks).toMatchObject({
  1871. enabled: true,
  1872. timeoutMs: 5000,
  1873. maxOutputBytes: 8192,
  1874. });
  1875. expect(result.config.hooks?.events?.PreToolUse?.[0]?.hooks[0]).toMatchObject({
  1876. type: "process",
  1877. command: "node",
  1878. args: ["hooks/pre-tool.js"],
  1879. enabled: false,
  1880. customFlag: "keep",
  1881. });
  1882. } finally {
  1883. await rm(dir, { force: true, recursive: true });
  1884. }
  1885. });
  1886. it("drops hooks from discovered project config files because project hooks are untrusted code", async () => {
  1887. const root = await mkdtemp(join(tmpdir(), "zcode-project-hooks-"));
  1888. try {
  1889. await mkdir(join(root, ".git"));
  1890. await mkdir(join(root, ".zcode"), { recursive: true });
  1891. await writeFile(
  1892. join(root, "zcode.json"),
  1893. JSON.stringify({
  1894. hooks: {
  1895. enabled: true,
  1896. events: {
  1897. SessionStart: [
  1898. {
  1899. matcher: "startup",
  1900. hooks: [{ type: "command", command: "echo root-project-hook" }],
  1901. },
  1902. ],
  1903. },
  1904. },
  1905. }),
  1906. );
  1907. await writeFile(
  1908. join(root, ".zcode", "config.json"),
  1909. JSON.stringify({
  1910. hooks: {
  1911. enabled: true,
  1912. events: {
  1913. SessionStart: [
  1914. {
  1915. matcher: "startup",
  1916. hooks: [{ type: "command", command: "echo project-hook" }],
  1917. },
  1918. ],
  1919. },
  1920. },
  1921. }),
  1922. );
  1923. const result = createConfig({
  1924. env: {},
  1925. skipUserConfig: true,
  1926. workingDirectory: root,
  1927. });
  1928. expect(result.sources.project.loaded).toBe(true);
  1929. expect(
  1930. result.sources.project.diagnostics.filter(
  1931. (diagnostic) => diagnostic.code === "config_project_hooks_pending_trust",
  1932. ),
  1933. ).toHaveLength(2);
  1934. for (const configPath of [join(root, "zcode.json"), join(root, ".zcode", "config.json")]) {
  1935. expect(result.sources.project.diagnostics).toContainEqual(
  1936. expect.objectContaining({
  1937. code: "config_project_hooks_pending_trust",
  1938. filePath: configPath,
  1939. message: "Project hooks are pending workspace trust and remain blocked",
  1940. path: "hooks",
  1941. severity: "warning",
  1942. }),
  1943. );
  1944. }
  1945. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  1946. expect(result.config.hooks.enabled).toBe(false);
  1947. } finally {
  1948. await rm(root, { force: true, recursive: true });
  1949. }
  1950. });
  1951. it("keeps user hooks while dropping untrusted project hooks", async () => {
  1952. const root = await mkdtemp(join(tmpdir(), "zcode-user-project-hooks-"));
  1953. const userConfigPath = join(root, "user-config.json");
  1954. try {
  1955. await mkdir(join(root, ".git"));
  1956. await mkdir(join(root, ".zcode"), { recursive: true });
  1957. await writeFile(
  1958. userConfigPath,
  1959. JSON.stringify({
  1960. hooks: {
  1961. enabled: true,
  1962. events: {
  1963. SessionStart: [
  1964. {
  1965. matcher: "startup",
  1966. hooks: [{ type: "command", command: "echo user-hook" }],
  1967. },
  1968. ],
  1969. },
  1970. },
  1971. }),
  1972. );
  1973. await writeFile(
  1974. join(root, ".zcode", "config.json"),
  1975. JSON.stringify({
  1976. hooks: {
  1977. enabled: true,
  1978. events: {
  1979. UserPromptSubmit: [
  1980. {
  1981. matcher: "*",
  1982. hooks: [{ type: "command", command: "echo project-hook" }],
  1983. },
  1984. ],
  1985. },
  1986. },
  1987. }),
  1988. );
  1989. const result = createConfig({
  1990. env: {},
  1991. userConfigPath,
  1992. workingDirectory: root,
  1993. });
  1994. expect(result.sources.user.loaded).toBe(true);
  1995. expect(result.sources.project.loaded).toBe(true);
  1996. expect(result.sources.project.diagnostics).toContainEqual(
  1997. expect.objectContaining({
  1998. code: "config_project_hooks_pending_trust",
  1999. path: "hooks",
  2000. severity: "warning",
  2001. }),
  2002. );
  2003. expect(result.config.hooks.enabled).toBe(true);
  2004. expect(result.config.hooks.events.SessionStart?.[0]?.hooks[0]).toMatchObject({
  2005. type: "command",
  2006. command: "echo user-hook",
  2007. source: { kind: "user", path: userConfigPath },
  2008. });
  2009. expect(result.config.hooks.events.UserPromptSubmit).toBeUndefined();
  2010. } finally {
  2011. await rm(root, { force: true, recursive: true });
  2012. }
  2013. });
  2014. it("loads model stream idle timeout config from file config", async () => {
  2015. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  2016. const path = join(dir, "config.json");
  2017. try {
  2018. await writeFile(
  2019. path,
  2020. JSON.stringify({
  2021. modelStream: {
  2022. idleTimeoutMs: 120000,
  2023. },
  2024. }),
  2025. );
  2026. const result = loadFileConfig(path);
  2027. expect(result.loaded).toBe(true);
  2028. expect(result.config.modelStream).toMatchObject({
  2029. idleTimeoutMs: 120000,
  2030. });
  2031. } finally {
  2032. await rm(dir, { force: true, recursive: true });
  2033. }
  2034. });
  2035. it("merges model stream idle timeout into runtime config", async () => {
  2036. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  2037. const path = join(dir, "config.json");
  2038. try {
  2039. await writeFile(
  2040. path,
  2041. JSON.stringify({
  2042. modelStream: {
  2043. idleTimeoutMs: 240000,
  2044. },
  2045. }),
  2046. );
  2047. const result = createConfig({ env: {}, userConfigPath: path });
  2048. expect(result.config.modelStream.idleTimeoutMs).toBe(240000);
  2049. } finally {
  2050. await rm(dir, { force: true, recursive: true });
  2051. }
  2052. });
  2053. it("loads model anomaly guard config from file config", async () => {
  2054. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  2055. const path = join(dir, "config.json");
  2056. try {
  2057. await writeFile(
  2058. path,
  2059. JSON.stringify({
  2060. modelAnomalyGuard: {
  2061. repeatedToolCallWarningThreshold: 4,
  2062. maxBudgetWarningsPerTurn: 2,
  2063. },
  2064. }),
  2065. );
  2066. const result = loadFileConfig(path);
  2067. expect(result.loaded).toBe(true);
  2068. expect(result.config.modelAnomalyGuard).toMatchObject({
  2069. repeatedToolCallWarningThreshold: 4,
  2070. maxBudgetWarningsPerTurn: 2,
  2071. });
  2072. } finally {
  2073. await rm(dir, { force: true, recursive: true });
  2074. }
  2075. });
  2076. it("rejects unknown hook events from file config", async () => {
  2077. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  2078. const path = join(dir, "config.json");
  2079. try {
  2080. await writeFile(
  2081. path,
  2082. JSON.stringify({
  2083. hooks: {
  2084. enabled: true,
  2085. events: {
  2086. BeforeEverything: [
  2087. {
  2088. hooks: [
  2089. {
  2090. type: "process",
  2091. command: "node",
  2092. },
  2093. ],
  2094. },
  2095. ],
  2096. },
  2097. },
  2098. }),
  2099. );
  2100. const result = loadFileConfig(path);
  2101. expect(result.loaded).toBe(false);
  2102. expect(result.config).toEqual({});
  2103. } finally {
  2104. await rm(dir, { force: true, recursive: true });
  2105. }
  2106. });
  2107. // Provider/Model 配置已归 Registry 管理;通用配置忽略退场字段,不得重新推导模型选择。
  2108. it.each([
  2109. { model: { provider: "example", model: "example-model", apiKey: "fixture" } },
  2110. { model: { main: "example/main", lite: "example/lite" } },
  2111. { model: "example/main", modelSmall: "example/small", smallModel: "example/small" },
  2112. {
  2113. provider: {
  2114. example: {
  2115. kind: "unsupported",
  2116. npm: "fixture",
  2117. models: { tiny: { limit: { context: "invalid" } } },
  2118. },
  2119. },
  2120. },
  2121. { modelCatalog: { overrides: { "example/model": { supportsReasoning: true } } } },
  2122. ])(
  2123. "ignores retired provider config while preserving active configuration: %j",
  2124. async (legacy) => {
  2125. const dir = await mkdtemp(join(tmpdir(), "zcode-config-retired-model-"));
  2126. try {
  2127. const path = join(dir, "config.json");
  2128. await writeFile(path, JSON.stringify({ ...legacy, features: { memory: false } }));
  2129. const result = loadFileConfig(path);
  2130. expect(result.loaded).toBe(true);
  2131. expect(result.config).toMatchObject({ features: { memory: false } });
  2132. for (const key of ["model", "provider", "modelCatalog", "modelSmall", "smallModel"])
  2133. expect(result.config).not.toHaveProperty(key);
  2134. } finally {
  2135. await rm(dir, { recursive: true, force: true });
  2136. }
  2137. },
  2138. );
  2139. it("rejects invalid active configuration", async () => {
  2140. const dir = await mkdtemp(join(tmpdir(), "zcode-config-invalid-"));
  2141. try {
  2142. const path = join(dir, "config.json");
  2143. await writeFile(path, JSON.stringify({ network: { timeout: "invalid" } }));
  2144. const result = loadFileConfig(path);
  2145. expect(result.loaded).toBe(false);
  2146. expect(result.config).toEqual({});
  2147. } finally {
  2148. await rm(dir, { recursive: true, force: true });
  2149. }
  2150. });
  2151. it("removes a plugin's enabled flag and options on uninstall while preserving others", async () => {
  2152. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-"));
  2153. const configPath = join(dir, "config.json");
  2154. try {
  2155. await writeFile(
  2156. configPath,
  2157. JSON.stringify({
  2158. plugins: {
  2159. enabledPlugins: {
  2160. "hello@market": true,
  2161. "keep@market": true,
  2162. },
  2163. options: {
  2164. "hello@market": { default_device: "iPhone 16" },
  2165. "keep@market": { foo: "bar" },
  2166. },
  2167. },
  2168. }),
  2169. );
  2170. const result = await removePluginFromFileConfig(configPath, "hello@market");
  2171. expect(result.removedEnabled).toBe(true);
  2172. expect(result.removedOptions).toBe(true);
  2173. const parsed = JSON.parse(await readFile(configPath, "utf8")) as {
  2174. plugins: {
  2175. enabledPlugins: Record<string, boolean>;
  2176. options: Record<string, unknown>;
  2177. };
  2178. };
  2179. expect(parsed.plugins.enabledPlugins).toEqual({ "keep@market": true });
  2180. expect(parsed.plugins.options).toEqual({ "keep@market": { foo: "bar" } });
  2181. } finally {
  2182. await rm(dir, { force: true, recursive: true });
  2183. }
  2184. });
  2185. it("is a no-op when removing a plugin that has no config footprint", async () => {
  2186. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-missing-"));
  2187. const configPath = join(dir, "config.json");
  2188. try {
  2189. await writeFile(
  2190. configPath,
  2191. JSON.stringify({ plugins: { enabledPlugins: { "keep@market": true } } }),
  2192. );
  2193. const before = await readFile(configPath, "utf8");
  2194. const result = await removePluginFromFileConfig(configPath, "missing@market");
  2195. expect(result.removedEnabled).toBe(false);
  2196. expect(result.removedOptions).toBe(false);
  2197. // 未命中任何键时不应改写文件内容。
  2198. expect(await readFile(configPath, "utf8")).toBe(before);
  2199. } finally {
  2200. await rm(dir, { force: true, recursive: true });
  2201. }
  2202. });
  2203. it("adds and removes a suppressed builtin id atomically", async () => {
  2204. const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppress-patch-"));
  2205. const path = join(dir, "config.json");
  2206. const id = "skill-creator@zcode-plugins-official";
  2207. const added = await addSuppressedBuiltinInFileConfig(path, id);
  2208. expect(added.suppressed).toBe(true);
  2209. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]);
  2210. // idempotent add
  2211. await addSuppressedBuiltinInFileConfig(path, id);
  2212. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]);
  2213. const removed = await removeSuppressedBuiltinInFileConfig(path, id);
  2214. expect(removed.suppressed).toBe(false);
  2215. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([]);
  2216. });
  2217. });
  2218. async function readLogEntries(logDir: string): Promise<Array<Record<string, unknown>>> {
  2219. const files = await readdir(logDir);
  2220. expect(files).toHaveLength(1);
  2221. const content = await readFile(join(logDir, files[0]!), "utf8");
  2222. return content.trim().split("\n").map(JSON.parse) as Array<Record<string, unknown>>;
  2223. }