config.test.ts 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  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: { "demo@fixture": { format: "compact" } },
  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("deep merges Workspace Plugin enablement and options over User config", 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: "workspace",
  587. workspaceOnly: true,
  588. },
  589. });
  590. expect(result.sources.project.paths).toEqual([workspacePath]);
  591. expect(result.sources.plugins.enabled).toEqual({
  592. "user-only@fixture": "user",
  593. "workspace-plugin@fixture": "workspace",
  594. });
  595. expect(result.sources.plugins.dirs).toEqual({
  596. user: [join(dir, "user-plugin")],
  597. workspace: [],
  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: "workspace",
  604. workspaceOnly: "workspace",
  605. },
  606. });
  607. } finally {
  608. await rm(dir, { force: true, recursive: true });
  609. }
  610. });
  611. it.each(["zcode.json", ".zcode/config.json", "explicit-project.json"])(
  612. "ignores plugin directories from project config %s",
  613. async (fileName) => {
  614. const dir = await mkdtemp(join(tmpdir(), "zcode-project-plugin-dirs-"));
  615. const projectConfigPath = join(dir, fileName);
  616. try {
  617. await mkdir(join(dir, ".git"));
  618. await mkdir(join(dir, ".zcode"));
  619. await writeFile(
  620. projectConfigPath,
  621. JSON.stringify({ plugins: { dirs: ["./plugin", join(dir, "absolute-plugin")] } }),
  622. );
  623. const result = createConfig({
  624. env: {},
  625. skipUserConfig: true,
  626. ...(fileName === "explicit-project.json"
  627. ? { projectConfigPath }
  628. : { workingDirectory: dir }),
  629. });
  630. expect(result.sources.project.loaded).toBe(true);
  631. expect(result.config.plugins.dirs).toEqual([]);
  632. expect(result.sources.plugins.dirs.workspace).toEqual([]);
  633. expect(JSON.parse(await readFile(projectConfigPath, "utf8")).plugins.dirs).toHaveLength(2);
  634. } finally {
  635. await rm(dir, { force: true, recursive: true });
  636. }
  637. },
  638. );
  639. it("keeps Marketplace declarations in the User config layer", async () => {
  640. const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-marketplaces-"));
  641. const userPath = join(dir, "user.json");
  642. const workspacePath = join(dir, "workspace.json");
  643. try {
  644. await writeFile(
  645. userPath,
  646. JSON.stringify({
  647. plugins: {
  648. extraKnownMarketplaces: {
  649. "shared-market": {
  650. source: { source: "github", repo: "example/user-market" },
  651. },
  652. "user-market": {
  653. source: { source: "url", url: "https://example.test/user-market.json" },
  654. },
  655. },
  656. },
  657. }),
  658. );
  659. await writeFile(
  660. workspacePath,
  661. JSON.stringify({
  662. plugins: {
  663. extraKnownMarketplaces: {
  664. "shared-market": {
  665. source: { source: "directory", path: "./workspace-market" },
  666. },
  667. "workspace-market": {
  668. source: { source: "file", path: "./workspace-market.json" },
  669. },
  670. },
  671. },
  672. }),
  673. );
  674. const result = createConfig({
  675. env: {},
  676. userConfigPath: userPath,
  677. projectConfigPath: workspacePath,
  678. });
  679. expect(result.config.plugins.extraKnownMarketplaces).toEqual({
  680. "shared-market": {
  681. source: { source: "github", repo: "example/user-market" },
  682. },
  683. "user-market": {
  684. source: { source: "url", url: "https://example.test/user-market.json" },
  685. },
  686. });
  687. expect(result.sources.plugins.marketplaces).toEqual({
  688. "shared-market": "user",
  689. "user-market": "user",
  690. });
  691. } finally {
  692. await rm(dir, { force: true, recursive: true });
  693. }
  694. });
  695. it("parses the supported ZCODE environment surface", () => {
  696. const config = parseEnvConfig({
  697. ZCODE_STORAGE_DIR: "/tmp/zcode",
  698. ZCODE_HTTP_PROXY: "http://127.0.0.1:7890",
  699. ZCODE_NO_PROXY: "localhost,127.0.0.1",
  700. ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem",
  701. ZCODE_HTTP_TIMEOUT: "1234",
  702. ZCODE_LOCALE: "zh-CN",
  703. ZCODE_LOG_FORMAT: "json",
  704. });
  705. expect(config.model).toBeUndefined();
  706. expect(config.storage?.dir).toBe("/tmp/zcode");
  707. expect(config.network?.httpProxy).toBe("http://127.0.0.1:7890");
  708. expect(config.network?.noProxy).toBe("localhost,127.0.0.1");
  709. expect(config.network?.caCertFile).toBe("/tmp/zcode-ca.pem");
  710. expect(config.network?.timeout).toBe(1234);
  711. expect(config.ui).toBeUndefined();
  712. expect(config.logging?.format).toBe("json");
  713. expect(config.logging?.level).toBeUndefined();
  714. });
  715. it("loads the supported memory config fields", async () => {
  716. const dir = await mkdtemp(join(tmpdir(), "zcode-config-memory-"));
  717. const path = join(dir, "config.json");
  718. try {
  719. await writeFile(
  720. path,
  721. JSON.stringify({
  722. memory: {
  723. use: false,
  724. },
  725. }),
  726. );
  727. const loaded = loadFileConfig(path);
  728. const merged = createConfig({ env: {}, userConfigPath: path });
  729. expect(loaded.loaded).toBe(true);
  730. expect(loaded.config.memory).toEqual({
  731. use: false,
  732. });
  733. expect(merged.config.memory).toEqual({
  734. use: false,
  735. });
  736. } finally {
  737. await rm(dir, { force: true, recursive: true });
  738. }
  739. });
  740. it("parses session database path environment overrides", () => {
  741. expect(
  742. parseEnvConfig({
  743. ZCODE_SESSION_DB_PATH: "/tmp/zcode/db/db.sqlite",
  744. }).storage?.sessionDbPath,
  745. ).toBe("/tmp/zcode/db/db.sqlite");
  746. expect(
  747. parseEnvConfig({
  748. ZCODE_SESSION_DB: "/tmp/zcode/legacy.sqlite",
  749. }).storage?.sessionDbPath,
  750. ).toBe("/tmp/zcode/legacy.sqlite");
  751. });
  752. it("loads no-proxy rules from file config", async () => {
  753. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  754. const path = join(dir, "config.json");
  755. try {
  756. await writeFile(
  757. path,
  758. JSON.stringify({
  759. network: {
  760. httpProxy: "http://127.0.0.1:7890",
  761. noProxy: "localhost,127.0.0.1",
  762. caCertFile: "/tmp/zcode-ca.pem",
  763. },
  764. }),
  765. );
  766. const merged = createConfig({ env: {}, userConfigPath: path });
  767. expect(merged.config.network.httpProxy).toBe("http://127.0.0.1:7890");
  768. expect(merged.config.network.noProxy).toBe("localhost,127.0.0.1");
  769. expect(merged.config.network.caCertFile).toBe("/tmp/zcode-ca.pem");
  770. } finally {
  771. await rm(dir, { force: true, recursive: true });
  772. }
  773. });
  774. it("ignores undeclared ZCODE environment switches", () => {
  775. const config = parseEnvConfig({
  776. ZCODE_LOG_LEVEL: "debug",
  777. ZCODE_UNDECLARED_FLAG: "1",
  778. });
  779. expect(config).toEqual({});
  780. });
  781. it("loads yolo mode from file config", async () => {
  782. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  783. const path = join(dir, "config.json");
  784. try {
  785. await writeFile(path, JSON.stringify({ permission: { mode: "yolo" } }));
  786. const result = loadFileConfig(path);
  787. expect(result.loaded).toBe(true);
  788. expect(result.config.permission?.mode).toBe("yolo");
  789. } finally {
  790. await rm(dir, { force: true, recursive: true });
  791. }
  792. });
  793. it("loads edit mode from file config", async () => {
  794. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  795. const path = join(dir, "config.json");
  796. try {
  797. await writeFile(path, JSON.stringify({ permission: { mode: "edit" } }));
  798. const result = loadFileConfig(path);
  799. expect(result.loaded).toBe(true);
  800. expect(result.config.permission?.mode).toBe("edit");
  801. } finally {
  802. await rm(dir, { force: true, recursive: true });
  803. }
  804. });
  805. it("loads skill/command enable overrides from file config", async () => {
  806. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  807. const path = join(dir, "config.json");
  808. try {
  809. await writeFile(
  810. path,
  811. JSON.stringify({
  812. skill: { "/abs/skills/demo/SKILL.md": { enable: false } },
  813. command: { "/abs/commands/demo.md": { enable: false } },
  814. }),
  815. );
  816. const result = loadFileConfig(path);
  817. const merged = createConfig({ env: {}, userConfigPath: path });
  818. expect(result.loaded).toBe(true);
  819. // JSON 的 skill/command 字段映射到 runtime 的 skillOverrides/commandOverrides
  820. expect(result.config.skillOverrides?.["/abs/skills/demo/SKILL.md"]?.enable).toBe(false);
  821. expect(result.config.commandOverrides?.["/abs/commands/demo.md"]?.enable).toBe(false);
  822. expect(merged.config.skillOverrides["/abs/skills/demo/SKILL.md"]?.enable).toBe(false);
  823. expect(merged.config.commandOverrides["/abs/commands/demo.md"]?.enable).toBe(false);
  824. } finally {
  825. await rm(dir, { force: true, recursive: true });
  826. }
  827. });
  828. it("parses plugins.suppressedBuiltins as a string array", async () => {
  829. const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppressed-"));
  830. const path = join(dir, "config.json");
  831. await writeFile(
  832. path,
  833. JSON.stringify({ plugins: { suppressedBuiltins: ["skill-creator@zcode-plugins-official"] } }),
  834. );
  835. const loaded = loadFileConfig(path);
  836. expect(loaded.config.plugins.suppressedBuiltins).toEqual([
  837. "skill-creator@zcode-plugins-official",
  838. ]);
  839. });
  840. it("maps skills path enable entries to skill overrides", async () => {
  841. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  842. const path = join(dir, "config.json");
  843. try {
  844. await writeFile(
  845. path,
  846. JSON.stringify({
  847. skills: {
  848. enabled: true,
  849. roots: ["/abs/skills"],
  850. "/abs/skills/disabled/SKILL.md": { enable: false },
  851. "/abs/skills/enabled/SKILL.md": { enable: true },
  852. },
  853. }),
  854. );
  855. const result = loadFileConfig(path);
  856. const merged = createConfig({ env: {}, userConfigPath: path });
  857. expect(result.loaded).toBe(true);
  858. expect(result.config.skills).toEqual({
  859. enabled: true,
  860. roots: ["/abs/skills"],
  861. });
  862. expect(result.config.skillOverrides?.["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false);
  863. expect(result.config.skillOverrides?.["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true);
  864. expect(merged.config.skillOverrides["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false);
  865. expect(merged.config.skillOverrides["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true);
  866. } finally {
  867. await rm(dir, { force: true, recursive: true });
  868. }
  869. });
  870. it("loads top-level skills config from file config", async () => {
  871. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  872. const path = join(dir, "config.json");
  873. try {
  874. await writeFile(
  875. path,
  876. JSON.stringify({
  877. skills: {
  878. enabled: false,
  879. includeInstructions: false,
  880. metadataBudget: 1024,
  881. roots: ["/abs/skills"],
  882. },
  883. }),
  884. );
  885. const result = loadFileConfig(path);
  886. const merged = createConfig({ env: {}, userConfigPath: path });
  887. expect(result.loaded).toBe(true);
  888. expect(result.config.skills).toEqual({
  889. enabled: false,
  890. includeInstructions: false,
  891. metadataBudget: 1024,
  892. roots: ["/abs/skills"],
  893. });
  894. expect(merged.config.skills.enabled).toBe(false);
  895. expect(merged.config.skills.includeInstructions).toBe(false);
  896. expect(merged.config.skills.metadataBudget).toBe(1024);
  897. expect(merged.config.skills.roots).toEqual(["/abs/skills"]);
  898. } finally {
  899. await rm(dir, { force: true, recursive: true });
  900. }
  901. });
  902. it("loads UI locale from file config", async () => {
  903. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  904. const path = join(dir, "config.json");
  905. try {
  906. await writeFile(path, JSON.stringify({ ui: { locale: "zh-CN" } }));
  907. const result = loadFileConfig(path);
  908. const merged = createConfig({ env: {}, userConfigPath: path });
  909. expect(result.loaded).toBe(true);
  910. expect(result.config.ui?.locale).toBe("zh-CN");
  911. expect(merged.config.ui.locale).toBe("zh-CN");
  912. } finally {
  913. await rm(dir, { force: true, recursive: true });
  914. }
  915. });
  916. it("loads auto UI locale from file config", async () => {
  917. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  918. const path = join(dir, "config.json");
  919. try {
  920. await writeFile(path, JSON.stringify({ ui: { locale: "auto" } }));
  921. const result = loadFileConfig(path);
  922. const merged = createConfig({ env: {}, userConfigPath: path });
  923. expect(result.loaded).toBe(true);
  924. expect(result.config.ui?.locale).toBe("auto");
  925. expect(merged.config.ui.locale).toBe("auto");
  926. } finally {
  927. await rm(dir, { force: true, recursive: true });
  928. }
  929. });
  930. it("loads UI theme from file config", async () => {
  931. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  932. const path = join(dir, "config.json");
  933. try {
  934. await writeFile(path, JSON.stringify({ ui: { theme: "light" } }));
  935. const result = loadFileConfig(path);
  936. const merged = createConfig({ env: {}, userConfigPath: path });
  937. expect(result.loaded).toBe(true);
  938. expect(result.config.ui?.theme).toBe("light");
  939. expect(merged.config.ui.theme).toBe("light");
  940. } finally {
  941. await rm(dir, { force: true, recursive: true });
  942. }
  943. });
  944. it("rejects unsupported UI theme values from file config", async () => {
  945. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  946. const path = join(dir, "config.json");
  947. try {
  948. await writeFile(path, JSON.stringify({ ui: { theme: "sepia" } }));
  949. const result = loadFileConfig(path);
  950. expect(result.loaded).toBe(false);
  951. expect(result.config.ui).toBeUndefined();
  952. } finally {
  953. await rm(dir, { force: true, recursive: true });
  954. }
  955. });
  956. it("patches UI locale while preserving unrelated config fields", async () => {
  957. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  958. const path = join(dir, "config.json");
  959. try {
  960. await writeFile(
  961. path,
  962. JSON.stringify({
  963. model: {
  964. main: "openai/gpt-5.1",
  965. },
  966. permission: {
  967. mode: "plan",
  968. },
  969. ui: {
  970. density: "compact",
  971. locale: "en-US",
  972. },
  973. }),
  974. );
  975. const result = await updateUiLocaleInFileConfig(path, "zh-CN");
  976. const written = JSON.parse(await readFile(path, "utf-8"));
  977. expect(result).toEqual({
  978. locale: "zh-CN",
  979. path,
  980. });
  981. expect(written).toMatchObject({
  982. model: {
  983. main: "openai/gpt-5.1",
  984. },
  985. permission: {
  986. mode: "plan",
  987. },
  988. ui: {
  989. density: "compact",
  990. locale: "zh-CN",
  991. },
  992. });
  993. } finally {
  994. await rm(dir, { force: true, recursive: true });
  995. }
  996. });
  997. it("creates config files when patching UI locale", async () => {
  998. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  999. const path = join(dir, "nested", "config.json");
  1000. try {
  1001. await updateUiLocaleInFileConfig(path, "auto");
  1002. const written = JSON.parse(await readFile(path, "utf-8"));
  1003. expect(written).toEqual({
  1004. ui: {
  1005. locale: "auto",
  1006. },
  1007. });
  1008. } finally {
  1009. await rm(dir, { force: true, recursive: true });
  1010. }
  1011. });
  1012. it("rejects unsupported UI locale values from file config", async () => {
  1013. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1014. const path = join(dir, "config.json");
  1015. try {
  1016. await writeFile(path, JSON.stringify({ ui: { locale: "fr-FR" } }));
  1017. const result = loadFileConfig(path);
  1018. expect(result.loaded).toBe(false);
  1019. expect(result.config.ui).toBeUndefined();
  1020. } finally {
  1021. await rm(dir, { force: true, recursive: true });
  1022. }
  1023. });
  1024. it("loads MCP server config from file config", async () => {
  1025. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1026. const path = join(dir, "config.json");
  1027. try {
  1028. await writeFile(
  1029. path,
  1030. JSON.stringify({
  1031. features: {
  1032. mcp: true,
  1033. },
  1034. mcp: {
  1035. servers: {
  1036. local: {
  1037. type: "stdio",
  1038. command: "node",
  1039. args: ["server.js"],
  1040. cwd: ".",
  1041. env: {
  1042. EXAMPLE: "1",
  1043. },
  1044. },
  1045. remote: {
  1046. type: "http",
  1047. url: "https://example.com/mcp",
  1048. headers: {
  1049. Authorization: "Bearer token",
  1050. },
  1051. oauth: {
  1052. type: "client_credentials",
  1053. clientId: "zcode-client",
  1054. clientSecret: "secret",
  1055. scope: "mcp:tools",
  1056. },
  1057. timeoutMs: 30000,
  1058. },
  1059. events: {
  1060. type: "sse",
  1061. url: "https://example.com/sse",
  1062. oauth: {
  1063. type: "authorization_code",
  1064. clientName: "ZCode",
  1065. redirectPath: "/oauth/callback/mcp/figma",
  1066. scope: "mcp:connect",
  1067. },
  1068. enabled: false,
  1069. },
  1070. },
  1071. },
  1072. }),
  1073. );
  1074. const result = loadFileConfig(path);
  1075. expect(result.loaded).toBe(true);
  1076. expect(result.config.features?.mcp).toBe(true);
  1077. expect(result.config.mcp?.servers?.local).toMatchObject({
  1078. type: "stdio",
  1079. command: "node",
  1080. args: ["server.js"],
  1081. });
  1082. expect(result.config.mcp?.servers?.remote).toMatchObject({
  1083. type: "http",
  1084. url: "https://example.com/mcp",
  1085. oauth: {
  1086. type: "client_credentials",
  1087. clientId: "zcode-client",
  1088. clientSecret: "secret",
  1089. scope: "mcp:tools",
  1090. },
  1091. timeoutMs: 30000,
  1092. });
  1093. expect(result.config.mcp?.servers?.events).toMatchObject({
  1094. type: "sse",
  1095. oauth: {
  1096. type: "authorization_code",
  1097. clientName: "ZCode",
  1098. redirectPath: "/oauth/callback/mcp/figma",
  1099. scope: "mcp:connect",
  1100. },
  1101. enabled: false,
  1102. });
  1103. } finally {
  1104. await rm(dir, { force: true, recursive: true });
  1105. }
  1106. });
  1107. it("keeps an MCP server disabled when legacy enable:false coexists with enabled:true", async () => {
  1108. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1109. const path = join(dir, "config.json");
  1110. try {
  1111. await writeFile(
  1112. path,
  1113. JSON.stringify({
  1114. mcp: {
  1115. servers: {
  1116. // 桌面端「停用」写入 enable:false,而外部导入/手工编辑的同一条配置里
  1117. // 已经带着 enabled:true。禁用意图必须胜出。
  1118. playwright: {
  1119. type: "stdio",
  1120. command: "npx",
  1121. args: ["-y", "@playwright/mcp@latest"],
  1122. enable: false,
  1123. enabled: true,
  1124. },
  1125. },
  1126. },
  1127. }),
  1128. );
  1129. const result = loadFileConfig(path);
  1130. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false);
  1131. } finally {
  1132. await rm(dir, { force: true, recursive: true });
  1133. }
  1134. });
  1135. it("keeps an MCP server disabled when enabled:false coexists with legacy enable:true", async () => {
  1136. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1137. const path = join(dir, "config.json");
  1138. try {
  1139. await writeFile(
  1140. path,
  1141. JSON.stringify({
  1142. mcp: {
  1143. servers: {
  1144. playwright: {
  1145. type: "stdio",
  1146. command: "npx",
  1147. args: ["-y", "@playwright/mcp@latest"],
  1148. enable: true,
  1149. enabled: false,
  1150. },
  1151. },
  1152. },
  1153. }),
  1154. );
  1155. const result = loadFileConfig(path);
  1156. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false);
  1157. } finally {
  1158. await rm(dir, { force: true, recursive: true });
  1159. }
  1160. });
  1161. it("keeps an MCP server enabled when both enable and enabled are true", async () => {
  1162. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1163. const path = join(dir, "config.json");
  1164. try {
  1165. await writeFile(
  1166. path,
  1167. JSON.stringify({
  1168. mcp: {
  1169. servers: {
  1170. playwright: {
  1171. type: "stdio",
  1172. command: "npx",
  1173. args: ["-y", "@playwright/mcp@latest"],
  1174. enable: true,
  1175. enabled: true,
  1176. },
  1177. },
  1178. },
  1179. }),
  1180. );
  1181. const result = loadFileConfig(path);
  1182. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(true);
  1183. } finally {
  1184. await rm(dir, { force: true, recursive: true });
  1185. }
  1186. });
  1187. it("preserves fresh HTTP MCP config without writing implicit OAuth", async () => {
  1188. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1189. const path = join(dir, "config.json");
  1190. try {
  1191. await writeFile(
  1192. path,
  1193. JSON.stringify({
  1194. mcp: {
  1195. servers: {
  1196. notion: {
  1197. type: "http",
  1198. url: "https://mcp.notion.com/mcp",
  1199. timeoutMs: 30000,
  1200. },
  1201. },
  1202. },
  1203. }),
  1204. );
  1205. const result = loadFileConfig(path);
  1206. expect(result.loaded).toBe(true);
  1207. expect(result.config.mcp?.servers?.notion).toMatchObject({
  1208. type: "http",
  1209. url: "https://mcp.notion.com/mcp",
  1210. timeoutMs: 30000,
  1211. });
  1212. expect(result.config.mcp?.servers?.notion?.oauth).toBeUndefined();
  1213. } finally {
  1214. await rm(dir, { force: true, recursive: true });
  1215. }
  1216. });
  1217. it("skips invalid MCP OAuth config without dropping unrelated config", async () => {
  1218. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1219. const path = join(dir, "config.json");
  1220. try {
  1221. await writeFile(
  1222. path,
  1223. JSON.stringify({
  1224. mcp: {
  1225. servers: {
  1226. broken: {
  1227. type: "http",
  1228. url: "https://example.com/mcp",
  1229. oauth: {
  1230. type: "client_credentials",
  1231. clientId: "zcode-client",
  1232. },
  1233. },
  1234. },
  1235. },
  1236. plugins: {
  1237. enabled: true,
  1238. },
  1239. }),
  1240. );
  1241. const result = loadFileConfig(path);
  1242. expect(result.loaded).toBe(true);
  1243. expect(result.config.mcp?.servers).not.toHaveProperty("broken");
  1244. expect(result.config.plugins?.enabled).toBe(true);
  1245. expect(result.diagnostics).toEqual([
  1246. expect.objectContaining({
  1247. code: "config_mcp_server_invalid",
  1248. path: "mcp.servers.broken",
  1249. severity: "warning",
  1250. }),
  1251. ]);
  1252. } finally {
  1253. await rm(dir, { force: true, recursive: true });
  1254. }
  1255. });
  1256. it("normalizes app-managed MCP config aliases from file config", async () => {
  1257. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1258. const path = join(dir, "config.json");
  1259. try {
  1260. await writeFile(
  1261. path,
  1262. JSON.stringify({
  1263. mcp: {
  1264. servers: {
  1265. "figma-dev-mode-mcp-server": {
  1266. type: "stdio",
  1267. command: "npx",
  1268. args: ["-y", "figma-developer-mcp"],
  1269. enable: false,
  1270. },
  1271. "chrome-devtools": {
  1272. command: "npx",
  1273. args: ["-y", "chrome-devtools-mcp@latest"],
  1274. },
  1275. node_repl: {
  1276. command: "/opt/tools/node_repl",
  1277. args: [],
  1278. timeout: 30,
  1279. startup_timeout_sec: 120,
  1280. },
  1281. },
  1282. },
  1283. }),
  1284. );
  1285. const result = loadFileConfig(path);
  1286. expect(result.loaded).toBe(true);
  1287. expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).toMatchObject({
  1288. type: "stdio",
  1289. command: "npx",
  1290. enabled: false,
  1291. });
  1292. expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).not.toHaveProperty(
  1293. "enable",
  1294. );
  1295. expect(result.config.mcp?.servers?.["chrome-devtools"]).toMatchObject({
  1296. type: "stdio",
  1297. command: "npx",
  1298. args: ["-y", "chrome-devtools-mcp@latest"],
  1299. });
  1300. expect(result.config.mcp?.servers?.node_repl).toMatchObject({
  1301. type: "stdio",
  1302. command: "/opt/tools/node_repl",
  1303. });
  1304. expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("timeout");
  1305. expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("startup_timeout_sec");
  1306. } finally {
  1307. await rm(dir, { force: true, recursive: true });
  1308. }
  1309. });
  1310. it("normalizes legacy MCP http_headers to runtime headers", async () => {
  1311. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1312. const path = join(dir, "config.json");
  1313. try {
  1314. await writeFile(
  1315. path,
  1316. JSON.stringify({
  1317. mcp: {
  1318. servers: {
  1319. web_search_prime: {
  1320. type: "http",
  1321. url: "https://bigmodel.example.test/mcp",
  1322. http_headers: {
  1323. Authorization: "Bearer token",
  1324. },
  1325. },
  1326. },
  1327. },
  1328. }),
  1329. );
  1330. const result = loadFileConfig(path);
  1331. expect(result.loaded).toBe(true);
  1332. expect(result.config.mcp?.servers?.web_search_prime).toMatchObject({
  1333. type: "http",
  1334. headers: {
  1335. Authorization: "Bearer token",
  1336. },
  1337. });
  1338. expect(result.config.mcp?.servers?.web_search_prime).not.toHaveProperty("http_headers");
  1339. } finally {
  1340. await rm(dir, { force: true, recursive: true });
  1341. }
  1342. });
  1343. it("normalizes legacy MCP remote/environment fields without dropping plugins config", async () => {
  1344. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1345. const path = join(dir, "config.json");
  1346. try {
  1347. await writeFile(
  1348. path,
  1349. JSON.stringify({
  1350. mcp: {
  1351. servers: {
  1352. "GLM-Image-MCP": {
  1353. enabled: true,
  1354. environment: {
  1355. Z_AI_API_KEY: "test-key",
  1356. Z_AI_MODE: "ZHIPU",
  1357. },
  1358. command: "npx",
  1359. args: ["-y", "@z_ai/mcp-server"],
  1360. type: "stdio",
  1361. },
  1362. "GLM-WebReader-MCP": {
  1363. enabled: true,
  1364. headers: {
  1365. Authorization: "Bearer token",
  1366. },
  1367. type: "remote",
  1368. url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp",
  1369. },
  1370. },
  1371. },
  1372. plugins: {
  1373. enabledPlugins: {
  1374. "superpowers@zcode-plugins-official": true,
  1375. "skill-creator@zcode-plugins-official": false,
  1376. },
  1377. },
  1378. }),
  1379. );
  1380. const result = loadFileConfig(path);
  1381. const merged = createConfig({ env: {}, userConfigPath: path });
  1382. expect(result.loaded).toBe(true);
  1383. expect(result.diagnostics).toEqual([]);
  1384. expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).toMatchObject({
  1385. type: "stdio",
  1386. env: {
  1387. Z_AI_API_KEY: "test-key",
  1388. Z_AI_MODE: "ZHIPU",
  1389. },
  1390. });
  1391. expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).not.toHaveProperty("environment");
  1392. expect(result.config.mcp?.servers?.["GLM-WebReader-MCP"]).toMatchObject({
  1393. headers: {
  1394. Authorization: "Bearer token",
  1395. },
  1396. type: "http",
  1397. url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp",
  1398. });
  1399. expect(merged.config.plugins.enabledPlugins).toMatchObject({
  1400. "skill-creator@zcode-plugins-official": false,
  1401. "superpowers@zcode-plugins-official": true,
  1402. });
  1403. } finally {
  1404. await rm(dir, { force: true, recursive: true });
  1405. }
  1406. });
  1407. it("keeps non-MCP config when one MCP server is invalid", async () => {
  1408. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1409. const logDir = join(dir, "log");
  1410. const path = join(dir, "config.json");
  1411. try {
  1412. await writeFile(
  1413. path,
  1414. JSON.stringify({
  1415. mcp: {
  1416. servers: {
  1417. valid: {
  1418. type: "remote",
  1419. url: "https://example.com/mcp",
  1420. },
  1421. broken: {
  1422. type: "stdio",
  1423. args: ["server.js"],
  1424. },
  1425. },
  1426. },
  1427. plugins: {
  1428. enabledPlugins: {
  1429. "android-emulator@zcode-plugins-official": true,
  1430. },
  1431. },
  1432. }),
  1433. );
  1434. const result = loadFileConfig(path);
  1435. const merged = createConfig({
  1436. env: { ZCODE_LOG_DIR: logDir },
  1437. userConfigPath: path,
  1438. });
  1439. expect(result.loaded).toBe(true);
  1440. expect(result.config.mcp?.servers?.valid).toMatchObject({
  1441. type: "http",
  1442. url: "https://example.com/mcp",
  1443. });
  1444. expect(result.config.mcp?.servers).not.toHaveProperty("broken");
  1445. expect(
  1446. result.config.plugins?.enabledPlugins?.["android-emulator@zcode-plugins-official"],
  1447. ).toBe(true);
  1448. expect(result.diagnostics).toEqual([
  1449. expect.objectContaining({
  1450. code: "config_mcp_server_invalid",
  1451. path: "mcp.servers.broken",
  1452. severity: "warning",
  1453. }),
  1454. ]);
  1455. expect(merged.sources.user.diagnostics).toEqual(result.diagnostics);
  1456. expect(merged.config.plugins.enabledPlugins["android-emulator@zcode-plugins-official"]).toBe(
  1457. true,
  1458. );
  1459. await expect(readLogEntries(logDir)).resolves.toEqual([
  1460. expect.objectContaining({
  1461. event: "config.mcp_server.skipped",
  1462. level: "warn",
  1463. message: "MCP server config skipped",
  1464. module: "adapters.config",
  1465. context: expect.objectContaining({
  1466. configPath: path,
  1467. configScope: "user",
  1468. diagnosticCode: "config_mcp_server_invalid",
  1469. diagnosticPath: "mcp.servers.broken",
  1470. }),
  1471. }),
  1472. ]);
  1473. } finally {
  1474. await rm(dir, { force: true, recursive: true });
  1475. }
  1476. });
  1477. it("reports invalid discovered project config diagnostics", async () => {
  1478. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1479. const logDir = join(root, "log");
  1480. const projectConfigPath = join(root, "zcode.json");
  1481. try {
  1482. await mkdir(join(root, ".git"));
  1483. await writeFile(
  1484. projectConfigPath,
  1485. JSON.stringify({
  1486. hooks: {
  1487. enabled: "invalid",
  1488. },
  1489. }),
  1490. );
  1491. const result = createConfig({
  1492. env: { ZCODE_LOG_DIR: logDir },
  1493. skipUserConfig: true,
  1494. workingDirectory: root,
  1495. });
  1496. expect(result.sources.project.loaded).toBe(false);
  1497. expect(result.sources.project.diagnostics).toEqual([
  1498. expect.objectContaining({
  1499. code: "config_file_invalid",
  1500. message: expect.stringContaining("hooks.enabled: Invalid input: expected boolean"),
  1501. severity: "error",
  1502. }),
  1503. ]);
  1504. await expect(readLogEntries(logDir)).resolves.toEqual([
  1505. expect.objectContaining({
  1506. event: "config.file.invalid",
  1507. level: "warn",
  1508. message: "Config file failed to load",
  1509. module: "adapters.config",
  1510. context: expect.objectContaining({
  1511. configPath: projectConfigPath,
  1512. configScope: "project",
  1513. diagnosticCode: "config_file_invalid",
  1514. }),
  1515. }),
  1516. ]);
  1517. } finally {
  1518. await rm(root, { force: true, recursive: true });
  1519. }
  1520. });
  1521. it("discovers project MCP config from the worktree root", async () => {
  1522. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1523. const cwd = join(root, "packages", "app");
  1524. try {
  1525. await mkdir(join(root, ".git"));
  1526. await mkdir(cwd, { recursive: true });
  1527. await writeFile(
  1528. join(root, "zcode.json"),
  1529. JSON.stringify({
  1530. mcp: {
  1531. servers: {
  1532. project: {
  1533. type: "stdio",
  1534. command: "node",
  1535. args: ["server.js"],
  1536. cwd: "tools",
  1537. },
  1538. },
  1539. },
  1540. }),
  1541. );
  1542. const result = createConfig({
  1543. env: {},
  1544. skipUserConfig: true,
  1545. workingDirectory: cwd,
  1546. });
  1547. expect(result.sources.project.loaded).toBe(true);
  1548. expect(result.sources.project.paths).toEqual([join(root, "zcode.json")]);
  1549. expect(result.sources.project.mcpServerNames).toEqual(["project"]);
  1550. expect(result.config.mcp.servers.project).toMatchObject({
  1551. type: "stdio",
  1552. command: "node",
  1553. cwd: join(root, "tools"),
  1554. });
  1555. } finally {
  1556. await rm(root, { force: true, recursive: true });
  1557. }
  1558. });
  1559. it("merges project configs from root to cwd with nearest config winning", async () => {
  1560. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1561. const cwd = join(root, "packages", "app");
  1562. const cwdConfigDir = join(cwd, ".zcode");
  1563. try {
  1564. await mkdir(join(root, ".git"));
  1565. await mkdir(cwdConfigDir, { recursive: true });
  1566. await writeFile(
  1567. join(root, "zcode.json"),
  1568. JSON.stringify({
  1569. mcp: {
  1570. servers: {
  1571. project: {
  1572. type: "stdio",
  1573. command: "root-server",
  1574. },
  1575. },
  1576. },
  1577. }),
  1578. );
  1579. await writeFile(
  1580. join(cwdConfigDir, "config.json"),
  1581. JSON.stringify({
  1582. mcp: {
  1583. servers: {
  1584. project: {
  1585. type: "stdio",
  1586. command: "nearest-server",
  1587. },
  1588. },
  1589. },
  1590. }),
  1591. );
  1592. const result = createConfig({
  1593. env: {},
  1594. skipUserConfig: true,
  1595. workingDirectory: cwd,
  1596. });
  1597. expect(result.sources.project.paths).toEqual([
  1598. join(root, "zcode.json"),
  1599. join(cwdConfigDir, "config.json"),
  1600. ]);
  1601. expect(result.config.mcp.servers.project).toMatchObject({
  1602. type: "stdio",
  1603. command: "nearest-server",
  1604. cwd,
  1605. });
  1606. } finally {
  1607. await rm(root, { force: true, recursive: true });
  1608. }
  1609. });
  1610. it("lets user MCP servers override same-name project MCP servers", async () => {
  1611. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1612. const userConfigPath = join(root, "home", "config.json");
  1613. try {
  1614. await mkdir(join(root, ".git"));
  1615. await mkdir(join(root, "home"), { recursive: true });
  1616. await writeFile(
  1617. join(root, "zcode.json"),
  1618. JSON.stringify({
  1619. mcp: {
  1620. servers: {
  1621. projectOnly: {
  1622. type: "stdio",
  1623. command: "project-only-server",
  1624. },
  1625. shared: {
  1626. type: "stdio",
  1627. command: "project-server",
  1628. },
  1629. },
  1630. },
  1631. }),
  1632. );
  1633. await writeFile(
  1634. userConfigPath,
  1635. JSON.stringify({
  1636. mcp: {
  1637. servers: {
  1638. shared: {
  1639. type: "stdio",
  1640. command: "user-server",
  1641. },
  1642. userOnly: {
  1643. type: "stdio",
  1644. command: "user-only-server",
  1645. },
  1646. },
  1647. },
  1648. }),
  1649. );
  1650. const result = createConfig({
  1651. env: {},
  1652. userConfigPath,
  1653. workingDirectory: root,
  1654. });
  1655. expect(result.config.mcp.servers.shared).toMatchObject({
  1656. type: "stdio",
  1657. command: "user-server",
  1658. });
  1659. expect(result.config.mcp.servers.projectOnly).toMatchObject({
  1660. command: "project-only-server",
  1661. });
  1662. expect(result.config.mcp.servers.userOnly).toMatchObject({
  1663. command: "user-only-server",
  1664. });
  1665. expect(result.sources.user.mcpServerNames).toEqual(["shared", "userOnly"]);
  1666. expect(result.sources.project.mcpServerNames.toSorted()).toEqual(["projectOnly", "shared"]);
  1667. expect(result.sources.mcp.serverSources).toMatchObject({
  1668. projectOnly: "project",
  1669. shared: "user",
  1670. userOnly: "user",
  1671. });
  1672. } finally {
  1673. await rm(root, { force: true, recursive: true });
  1674. }
  1675. });
  1676. it("does not scan project config above the worktree root", async () => {
  1677. const parent = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1678. const root = join(parent, "repo");
  1679. const cwd = join(root, "packages", "app");
  1680. try {
  1681. await mkdir(join(root, ".git"), { recursive: true });
  1682. await mkdir(cwd, { recursive: true });
  1683. await writeFile(
  1684. join(parent, "zcode.json"),
  1685. JSON.stringify({
  1686. mcp: {
  1687. servers: {
  1688. parent: {
  1689. type: "stdio",
  1690. command: "parent-server",
  1691. },
  1692. },
  1693. },
  1694. }),
  1695. );
  1696. const result = createConfig({
  1697. env: {},
  1698. skipUserConfig: true,
  1699. workingDirectory: cwd,
  1700. });
  1701. expect(result.sources.project.loaded).toBe(false);
  1702. expect(result.config.mcp.servers.parent).toBeUndefined();
  1703. } finally {
  1704. await rm(parent, { force: true, recursive: true });
  1705. }
  1706. });
  1707. it("keeps CLI feature overrides above project MCP config", async () => {
  1708. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1709. try {
  1710. await mkdir(join(root, ".git"));
  1711. await writeFile(
  1712. join(root, "zcode.json"),
  1713. JSON.stringify({
  1714. features: {
  1715. mcp: true,
  1716. },
  1717. }),
  1718. );
  1719. const result = createConfig({
  1720. cliOverrides: {
  1721. features: {
  1722. mcp: false,
  1723. },
  1724. },
  1725. env: {},
  1726. skipUserConfig: true,
  1727. workingDirectory: root,
  1728. });
  1729. expect(result.config.features.mcp).toBe(false);
  1730. } finally {
  1731. await rm(root, { force: true, recursive: true });
  1732. }
  1733. });
  1734. it("loads process hook config from file config", async () => {
  1735. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1736. const path = join(dir, "config.json");
  1737. try {
  1738. await writeFile(
  1739. path,
  1740. JSON.stringify({
  1741. hooks: {
  1742. enabled: true,
  1743. timeoutMs: 5000,
  1744. maxOutputBytes: 8192,
  1745. events: {
  1746. PreToolUse: [
  1747. {
  1748. matcher: "Bash",
  1749. hooks: [
  1750. {
  1751. type: "process",
  1752. command: "node",
  1753. args: ["hooks/pre-tool.js"],
  1754. enabled: false,
  1755. customFlag: "keep",
  1756. },
  1757. ],
  1758. },
  1759. ],
  1760. },
  1761. },
  1762. }),
  1763. );
  1764. const result = loadFileConfig(path);
  1765. expect(result.loaded).toBe(true);
  1766. expect(result.config.hooks).toMatchObject({
  1767. enabled: true,
  1768. timeoutMs: 5000,
  1769. maxOutputBytes: 8192,
  1770. });
  1771. expect(result.config.hooks?.events?.PreToolUse?.[0]?.hooks[0]).toMatchObject({
  1772. type: "process",
  1773. command: "node",
  1774. args: ["hooks/pre-tool.js"],
  1775. enabled: false,
  1776. customFlag: "keep",
  1777. });
  1778. } finally {
  1779. await rm(dir, { force: true, recursive: true });
  1780. }
  1781. });
  1782. it("drops hooks from discovered project config files because project hooks are untrusted code", async () => {
  1783. const root = await mkdtemp(join(tmpdir(), "zcode-project-hooks-"));
  1784. try {
  1785. await mkdir(join(root, ".git"));
  1786. await mkdir(join(root, ".zcode"), { recursive: true });
  1787. await writeFile(
  1788. join(root, "zcode.json"),
  1789. JSON.stringify({
  1790. hooks: {
  1791. enabled: true,
  1792. events: {
  1793. SessionStart: [
  1794. {
  1795. matcher: "startup",
  1796. hooks: [{ type: "command", command: "echo root-project-hook" }],
  1797. },
  1798. ],
  1799. },
  1800. },
  1801. }),
  1802. );
  1803. await writeFile(
  1804. join(root, ".zcode", "config.json"),
  1805. JSON.stringify({
  1806. hooks: {
  1807. enabled: true,
  1808. events: {
  1809. SessionStart: [
  1810. {
  1811. matcher: "startup",
  1812. hooks: [{ type: "command", command: "echo project-hook" }],
  1813. },
  1814. ],
  1815. },
  1816. },
  1817. }),
  1818. );
  1819. const result = createConfig({
  1820. env: {},
  1821. skipUserConfig: true,
  1822. workingDirectory: root,
  1823. });
  1824. expect(result.sources.project.loaded).toBe(true);
  1825. expect(
  1826. result.sources.project.diagnostics.filter(
  1827. (diagnostic) => diagnostic.code === "config_project_hooks_pending_trust",
  1828. ),
  1829. ).toHaveLength(2);
  1830. for (const configPath of [join(root, "zcode.json"), join(root, ".zcode", "config.json")]) {
  1831. expect(result.sources.project.diagnostics).toContainEqual(
  1832. expect.objectContaining({
  1833. code: "config_project_hooks_pending_trust",
  1834. filePath: configPath,
  1835. message: "Project hooks are pending workspace trust and remain blocked",
  1836. path: "hooks",
  1837. severity: "warning",
  1838. }),
  1839. );
  1840. }
  1841. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  1842. expect(result.config.hooks.enabled).toBe(false);
  1843. } finally {
  1844. await rm(root, { force: true, recursive: true });
  1845. }
  1846. });
  1847. it("keeps user hooks while dropping untrusted project hooks", async () => {
  1848. const root = await mkdtemp(join(tmpdir(), "zcode-user-project-hooks-"));
  1849. const userConfigPath = join(root, "user-config.json");
  1850. try {
  1851. await mkdir(join(root, ".git"));
  1852. await mkdir(join(root, ".zcode"), { recursive: true });
  1853. await writeFile(
  1854. userConfigPath,
  1855. JSON.stringify({
  1856. hooks: {
  1857. enabled: true,
  1858. events: {
  1859. SessionStart: [
  1860. {
  1861. matcher: "startup",
  1862. hooks: [{ type: "command", command: "echo user-hook" }],
  1863. },
  1864. ],
  1865. },
  1866. },
  1867. }),
  1868. );
  1869. await writeFile(
  1870. join(root, ".zcode", "config.json"),
  1871. JSON.stringify({
  1872. hooks: {
  1873. enabled: true,
  1874. events: {
  1875. UserPromptSubmit: [
  1876. {
  1877. matcher: "*",
  1878. hooks: [{ type: "command", command: "echo project-hook" }],
  1879. },
  1880. ],
  1881. },
  1882. },
  1883. }),
  1884. );
  1885. const result = createConfig({
  1886. env: {},
  1887. userConfigPath,
  1888. workingDirectory: root,
  1889. });
  1890. expect(result.sources.user.loaded).toBe(true);
  1891. expect(result.sources.project.loaded).toBe(true);
  1892. expect(result.sources.project.diagnostics).toContainEqual(
  1893. expect.objectContaining({
  1894. code: "config_project_hooks_pending_trust",
  1895. path: "hooks",
  1896. severity: "warning",
  1897. }),
  1898. );
  1899. expect(result.config.hooks.enabled).toBe(true);
  1900. expect(result.config.hooks.events.SessionStart?.[0]?.hooks[0]).toMatchObject({
  1901. type: "command",
  1902. command: "echo user-hook",
  1903. source: { kind: "user", path: userConfigPath },
  1904. });
  1905. expect(result.config.hooks.events.UserPromptSubmit).toBeUndefined();
  1906. } finally {
  1907. await rm(root, { force: true, recursive: true });
  1908. }
  1909. });
  1910. it("loads model stream idle timeout config from file config", async () => {
  1911. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1912. const path = join(dir, "config.json");
  1913. try {
  1914. await writeFile(
  1915. path,
  1916. JSON.stringify({
  1917. modelStream: {
  1918. idleTimeoutMs: 120000,
  1919. },
  1920. }),
  1921. );
  1922. const result = loadFileConfig(path);
  1923. expect(result.loaded).toBe(true);
  1924. expect(result.config.modelStream).toMatchObject({
  1925. idleTimeoutMs: 120000,
  1926. });
  1927. } finally {
  1928. await rm(dir, { force: true, recursive: true });
  1929. }
  1930. });
  1931. it("merges model stream idle timeout into runtime config", async () => {
  1932. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1933. const path = join(dir, "config.json");
  1934. try {
  1935. await writeFile(
  1936. path,
  1937. JSON.stringify({
  1938. modelStream: {
  1939. idleTimeoutMs: 240000,
  1940. },
  1941. }),
  1942. );
  1943. const result = createConfig({ env: {}, userConfigPath: path });
  1944. expect(result.config.modelStream.idleTimeoutMs).toBe(240000);
  1945. } finally {
  1946. await rm(dir, { force: true, recursive: true });
  1947. }
  1948. });
  1949. it("loads model anomaly guard config from file config", async () => {
  1950. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1951. const path = join(dir, "config.json");
  1952. try {
  1953. await writeFile(
  1954. path,
  1955. JSON.stringify({
  1956. modelAnomalyGuard: {
  1957. repeatedToolCallWarningThreshold: 4,
  1958. maxBudgetWarningsPerTurn: 2,
  1959. },
  1960. }),
  1961. );
  1962. const result = loadFileConfig(path);
  1963. expect(result.loaded).toBe(true);
  1964. expect(result.config.modelAnomalyGuard).toMatchObject({
  1965. repeatedToolCallWarningThreshold: 4,
  1966. maxBudgetWarningsPerTurn: 2,
  1967. });
  1968. } finally {
  1969. await rm(dir, { force: true, recursive: true });
  1970. }
  1971. });
  1972. it("rejects unknown hook events from file config", async () => {
  1973. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1974. const path = join(dir, "config.json");
  1975. try {
  1976. await writeFile(
  1977. path,
  1978. JSON.stringify({
  1979. hooks: {
  1980. enabled: true,
  1981. events: {
  1982. BeforeEverything: [
  1983. {
  1984. hooks: [
  1985. {
  1986. type: "process",
  1987. command: "node",
  1988. },
  1989. ],
  1990. },
  1991. ],
  1992. },
  1993. },
  1994. }),
  1995. );
  1996. const result = loadFileConfig(path);
  1997. expect(result.loaded).toBe(false);
  1998. expect(result.config).toEqual({});
  1999. } finally {
  2000. await rm(dir, { force: true, recursive: true });
  2001. }
  2002. });
  2003. // Provider/Model 配置已归 Registry 管理;通用配置忽略退场字段,不得重新推导模型选择。
  2004. it.each([
  2005. { model: { provider: "example", model: "example-model", apiKey: "fixture" } },
  2006. { model: { main: "example/main", lite: "example/lite" } },
  2007. { model: "example/main", modelSmall: "example/small", smallModel: "example/small" },
  2008. {
  2009. provider: {
  2010. example: {
  2011. kind: "unsupported",
  2012. npm: "fixture",
  2013. models: { tiny: { limit: { context: "invalid" } } },
  2014. },
  2015. },
  2016. },
  2017. { modelCatalog: { overrides: { "example/model": { supportsReasoning: true } } } },
  2018. ])(
  2019. "ignores retired provider config while preserving active configuration: %j",
  2020. async (legacy) => {
  2021. const dir = await mkdtemp(join(tmpdir(), "zcode-config-retired-model-"));
  2022. try {
  2023. const path = join(dir, "config.json");
  2024. await writeFile(path, JSON.stringify({ ...legacy, features: { memory: false } }));
  2025. const result = loadFileConfig(path);
  2026. expect(result.loaded).toBe(true);
  2027. expect(result.config).toMatchObject({ features: { memory: false } });
  2028. for (const key of ["model", "provider", "modelCatalog", "modelSmall", "smallModel"])
  2029. expect(result.config).not.toHaveProperty(key);
  2030. } finally {
  2031. await rm(dir, { recursive: true, force: true });
  2032. }
  2033. },
  2034. );
  2035. it("rejects invalid active configuration", async () => {
  2036. const dir = await mkdtemp(join(tmpdir(), "zcode-config-invalid-"));
  2037. try {
  2038. const path = join(dir, "config.json");
  2039. await writeFile(path, JSON.stringify({ network: { timeout: "invalid" } }));
  2040. const result = loadFileConfig(path);
  2041. expect(result.loaded).toBe(false);
  2042. expect(result.config).toEqual({});
  2043. } finally {
  2044. await rm(dir, { recursive: true, force: true });
  2045. }
  2046. });
  2047. it("removes a plugin's enabled flag and options on uninstall while preserving others", async () => {
  2048. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-"));
  2049. const configPath = join(dir, "config.json");
  2050. try {
  2051. await writeFile(
  2052. configPath,
  2053. JSON.stringify({
  2054. plugins: {
  2055. enabledPlugins: {
  2056. "hello@market": true,
  2057. "keep@market": true,
  2058. },
  2059. options: {
  2060. "hello@market": { default_device: "iPhone 16" },
  2061. "keep@market": { foo: "bar" },
  2062. },
  2063. },
  2064. }),
  2065. );
  2066. const result = await removePluginFromFileConfig(configPath, "hello@market");
  2067. expect(result.removedEnabled).toBe(true);
  2068. expect(result.removedOptions).toBe(true);
  2069. const parsed = JSON.parse(await readFile(configPath, "utf8")) as {
  2070. plugins: {
  2071. enabledPlugins: Record<string, boolean>;
  2072. options: Record<string, unknown>;
  2073. };
  2074. };
  2075. expect(parsed.plugins.enabledPlugins).toEqual({ "keep@market": true });
  2076. expect(parsed.plugins.options).toEqual({ "keep@market": { foo: "bar" } });
  2077. } finally {
  2078. await rm(dir, { force: true, recursive: true });
  2079. }
  2080. });
  2081. it("is a no-op when removing a plugin that has no config footprint", async () => {
  2082. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-missing-"));
  2083. const configPath = join(dir, "config.json");
  2084. try {
  2085. await writeFile(
  2086. configPath,
  2087. JSON.stringify({ plugins: { enabledPlugins: { "keep@market": true } } }),
  2088. );
  2089. const before = await readFile(configPath, "utf8");
  2090. const result = await removePluginFromFileConfig(configPath, "missing@market");
  2091. expect(result.removedEnabled).toBe(false);
  2092. expect(result.removedOptions).toBe(false);
  2093. // 未命中任何键时不应改写文件内容。
  2094. expect(await readFile(configPath, "utf8")).toBe(before);
  2095. } finally {
  2096. await rm(dir, { force: true, recursive: true });
  2097. }
  2098. });
  2099. it("adds and removes a suppressed builtin id atomically", async () => {
  2100. const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppress-patch-"));
  2101. const path = join(dir, "config.json");
  2102. const id = "skill-creator@zcode-plugins-official";
  2103. const added = await addSuppressedBuiltinInFileConfig(path, id);
  2104. expect(added.suppressed).toBe(true);
  2105. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]);
  2106. // idempotent add
  2107. await addSuppressedBuiltinInFileConfig(path, id);
  2108. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]);
  2109. const removed = await removeSuppressedBuiltinInFileConfig(path, id);
  2110. expect(removed.suppressed).toBe(false);
  2111. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([]);
  2112. });
  2113. });
  2114. async function readLogEntries(logDir: string): Promise<Array<Record<string, unknown>>> {
  2115. const files = await readdir(logDir);
  2116. expect(files).toHaveLength(1);
  2117. const content = await readFile(join(logDir, files[0]!), "utf8");
  2118. return content.trim().split("\n").map(JSON.parse) as Array<Record<string, unknown>>;
  2119. }