devworkspace 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +105 -26
  3. package/dist/cli/args.d.ts +10 -0
  4. package/dist/cli/args.js +3 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/help.js +15 -5
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli/render.d.ts +2 -1
  9. package/dist/cli/render.js +71 -4
  10. package/dist/cli/render.js.map +1 -1
  11. package/dist/cli/run.js +54 -36
  12. package/dist/cli/run.js.map +1 -1
  13. package/dist/core/artifacts.d.ts +32 -0
  14. package/dist/core/artifacts.js +46 -0
  15. package/dist/core/artifacts.js.map +1 -0
  16. package/dist/core/version.js +3 -0
  17. package/dist/core/version.js.map +1 -1
  18. package/dist/core/workspace.js +1 -0
  19. package/dist/core/workspace.js.map +1 -1
  20. package/dist/integrations/adapters/graphify.js +2 -1
  21. package/dist/integrations/adapters/graphify.js.map +1 -1
  22. package/dist/integrations/adapters/pluginSkill.js +15 -1
  23. package/dist/integrations/adapters/pluginSkill.js.map +1 -1
  24. package/dist/mcp/setup.d.ts +98 -5
  25. package/dist/mcp/setup.js +332 -82
  26. package/dist/mcp/setup.js.map +1 -1
  27. package/dist/mcp/tools.d.ts +6 -0
  28. package/dist/mcp/tools.js +67 -13
  29. package/dist/mcp/tools.js.map +1 -1
  30. package/dist/mcp/verify.d.ts +41 -0
  31. package/dist/mcp/verify.js +264 -0
  32. package/dist/mcp/verify.js.map +1 -0
  33. package/dist/services/doctor.js +64 -1
  34. package/dist/services/doctor.js.map +1 -1
  35. package/dist/services/graph.d.ts +92 -4
  36. package/dist/services/graph.js +552 -191
  37. package/dist/services/graph.js.map +1 -1
  38. package/dist/services/setup.js +3 -0
  39. package/dist/services/setup.js.map +1 -1
  40. package/dist/services/taskContext.d.ts +20 -2
  41. package/dist/services/taskContext.js +29 -15
  42. package/dist/services/taskContext.js.map +1 -1
  43. package/dist/utils/proc.js +19 -3
  44. package/dist/utils/proc.js.map +1 -1
  45. package/docs/agents.md +2 -2
  46. package/docs/claude.md +13 -0
  47. package/docs/getting-started.md +40 -1
  48. package/docs/integrations.md +16 -1
  49. package/docs/mcp.md +46 -10
  50. package/docs/troubleshooting.md +5 -0
  51. package/package.json +1 -1
package/dist/mcp/setup.js CHANGED
@@ -1,13 +1,17 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import os from 'node:os';
1
3
  import path from 'node:path';
2
4
  import { requireWorkspace, loadProject } from '../core/workspace.js';
3
5
  import { DevWorkspaceError } from '../errors/index.js';
4
- import { atomicWriteFile } from '../utils/fs.js';
6
+ import { atomicWriteFile, pathExists } from '../utils/fs.js';
5
7
  import { assertNoSymlinkEscape, resolveInside } from '../utils/paths.js';
6
8
  import { withLock } from '../utils/lock.js';
7
9
  import { detectEol, withEol, readIfExists } from '../agents/shared.js';
8
10
  import { which } from '../utils/proc.js';
9
- import { detectCliProvenance } from '../core/version.js';
10
- export const SUPPORTED_MCP_AGENTS = ['claude-code', 'claude', 'codex', 'antigravity', 'all'];
11
+ import { detectCliProvenance, packageVersion } from '../core/version.js';
12
+ import { createRunner } from '../integrations/exec.js';
13
+ import { observeClaudeCode, verifyMcpServer } from './verify.js';
14
+ export const SUPPORTED_MCP_AGENTS = ['claude-code', 'claude', 'codex', 'antigravity', 'all', 'auto'];
11
15
  export function isSupportedMcpAgent(id) {
12
16
  const norm = id.toLowerCase();
13
17
  return SUPPORTED_MCP_AGENTS.includes(norm);
@@ -152,33 +156,79 @@ export function mergeMcpJsonConfig(existingText, serverName, serverDef) {
152
156
  note: `add/update ${serverName} MCP server; existing servers and settings preserved`,
153
157
  };
154
158
  }
159
+ function isProjectLocalBin(exe, projectRoot) {
160
+ if (!projectRoot)
161
+ return false;
162
+ const rel = path.relative(path.resolve(projectRoot), path.resolve(exe));
163
+ return !rel.startsWith('..') && !path.isAbsolute(rel) && rel.split(path.sep).includes('node_modules');
164
+ }
165
+ async function defaultVersionFn(env) {
166
+ const runner = createRunner(env);
167
+ const exe = await runner.which('devworkspace');
168
+ if (!exe)
169
+ return null;
170
+ const r = await runner.run({ command: exe, args: ['--version'], timeoutMs: 10_000 });
171
+ if (!r.ok)
172
+ return null;
173
+ return /\d+\.\d+\.\d+[^\s]*/.exec(`${r.stdout}\n${r.stderr}`)?.[0] ?? null;
174
+ }
155
175
  /**
156
176
  * Resolves the MCP server command and arguments based on the chosen launcher strategy.
157
- * - 'direct': Uses the globally installed or PATH-accessible `devworkspace` binary.
158
- * - 'npx': Uses `npx -y devworkspace` (or `devworkspace@<version>` if packageVersion is set).
159
- * - 'auto': Detects whether `devworkspace` is on PATH and not invoked from temporary npx-cache.
160
- * If devworkspace is on PATH and not running in npx-cache, uses 'direct'; otherwise falls back to 'npx'.
177
+ * - 'direct': the `devworkspace` binary on PATH.
178
+ * - 'npx': `npx -y devworkspace[@version] mcp serve` (wrapped in `cmd /c` on Windows, where clients cannot spawn npx.cmd).
179
+ * - 'auto': direct only when a PATH binary exists, we are not running from the temporary npx cache, and the PATH binary's
180
+ * version equals the running CLI (an installed-but-different version is not silently trusted); otherwise npx.
161
181
  */
162
- export async function resolveMcpServerDef(options = {}) {
182
+ export async function resolveMcpLauncher(options = {}) {
163
183
  const launcher = options.launcher ?? 'auto';
164
184
  const pkgVersion = options.packageVersion;
165
185
  const env = options.env ?? process.env;
166
186
  const whichFn = options.whichFn ?? which;
187
+ const platform = options.platform ?? process.platform;
188
+ // The spec is placed in client config and (on Windows) a shell command line; allow only npm version / dist-tag characters.
189
+ if (pkgVersion !== undefined && !/^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/.test(pkgVersion)) {
190
+ throw new DevWorkspaceError('USAGE', `Invalid --package-version "${pkgVersion}".`, {
191
+ hint: 'Use an exact version such as 0.4.3 or a dist-tag such as latest.',
192
+ });
193
+ }
167
194
  let mode;
195
+ let reason;
168
196
  if (launcher === 'direct') {
169
197
  mode = 'direct';
198
+ reason = 'requested with --launcher direct';
170
199
  }
171
200
  else if (launcher === 'npx') {
172
201
  mode = 'npx';
202
+ reason = 'requested with --launcher npx';
173
203
  }
174
204
  else if (launcher === 'auto') {
175
205
  const provMode = options.provenanceMode ?? detectCliProvenance().mode;
176
206
  const globalExe = await whichFn('devworkspace', env);
177
- if (globalExe !== null && provMode !== 'npx-cache') {
178
- mode = 'direct';
207
+ if (globalExe === null) {
208
+ mode = 'npx';
209
+ reason = 'no "devworkspace" on PATH';
179
210
  }
180
- else {
211
+ else if (provMode === 'npx-cache') {
212
+ mode = 'npx';
213
+ reason = 'running from the temporary npx cache, so a PATH install would be a different copy';
214
+ }
215
+ else if (isProjectLocalBin(globalExe, options.projectRoot)) {
181
216
  mode = 'npx';
217
+ reason = `"devworkspace" on PATH is only this project's node_modules/.bin (${globalExe}); an agent started outside npm would not find it`;
218
+ }
219
+ else {
220
+ mode = 'direct';
221
+ reason = `"devworkspace" found on PATH (${globalExe})`;
222
+ if (provMode === 'installed-package') {
223
+ const globalVersion = await (options.versionFn ?? defaultVersionFn)(env);
224
+ if (globalVersion !== null && globalVersion !== packageVersion()) {
225
+ mode = 'npx';
226
+ reason = `PATH devworkspace is ${globalVersion} but this CLI is ${packageVersion()}; not trusting the mismatched install`;
227
+ }
228
+ else if (globalVersion === null) {
229
+ reason += '; its version could not be determined';
230
+ }
231
+ }
182
232
  }
183
233
  }
184
234
  else {
@@ -187,18 +237,124 @@ export async function resolveMcpServerDef(options = {}) {
187
237
  });
188
238
  }
189
239
  if (mode === 'direct') {
190
- return { command: 'devworkspace', args: ['mcp', 'serve'] };
240
+ return { command: 'devworkspace', args: ['mcp', 'serve'], mode, reason };
241
+ }
242
+ // Published copies (installed or run via npx) pin to their own version so the agent starts the code that was just
243
+ // verified; a source checkout has no published version to pin, so it uses the registry's latest.
244
+ const provForPin = options.provenanceMode ?? detectCliProvenance().mode;
245
+ const pinned = pkgVersion ?? (provForPin === 'source-checkout' ? undefined : packageVersion());
246
+ const pkgSpec = pinned ? `devworkspace@${pinned}` : 'devworkspace';
247
+ if (!pkgVersion && !pinned)
248
+ reason += '; source checkout, so the launcher is not version-pinned';
249
+ const npxArgs = ['-y', pkgSpec, 'mcp', 'serve'];
250
+ return platform === 'win32'
251
+ ? { command: 'cmd', args: ['/c', 'npx', ...npxArgs], mode, reason: `${reason}; wrapped in cmd /c for Windows` }
252
+ : { command: 'npx', args: npxArgs, mode, reason };
253
+ }
254
+ export async function resolveMcpServerDef(options = {}) {
255
+ const { command, args } = await resolveMcpLauncher(options);
256
+ return { command, args };
257
+ }
258
+ const AGENT_SIGNALS = {
259
+ 'claude-code': ['.claude', 'CLAUDE.md', '.mcp.json'],
260
+ codex: ['.codex', 'AGENTS.md'],
261
+ antigravity: ['.antigravity'],
262
+ };
263
+ /** Agents whose marker files already exist in the project. */
264
+ export async function detectMcpAgents(root) {
265
+ const found = [];
266
+ for (const [agent, markers] of Object.entries(AGENT_SIGNALS)) {
267
+ for (const m of markers) {
268
+ if (await pathExists(path.join(root, m))) {
269
+ found.push(agent);
270
+ break;
271
+ }
272
+ }
191
273
  }
192
- const pkgSpec = pkgVersion ? `devworkspace@${pkgVersion}` : 'devworkspace';
274
+ return found;
275
+ }
276
+ export const CODEX_BLOCK_START = '# devworkspace-mcp:start (managed by DevWorkspace MCP - edit outside this block)';
277
+ export const CODEX_BLOCK_END = '# devworkspace-mcp:end';
278
+ const CODEX_BLOCK_RE = /# devworkspace-mcp:start[^\n]*\n[\s\S]*?# devworkspace-mcp:end/;
279
+ /** The managed Codex TOML block. JSON string syntax is valid TOML for these values; 60s covers a cold `npx` download (Codex defaults to 10s). */
280
+ export function buildCodexBlock(def) {
281
+ return [
282
+ CODEX_BLOCK_START,
283
+ '[mcp_servers.devworkspace]',
284
+ `command = ${JSON.stringify(def.command)}`,
285
+ `args = ${JSON.stringify(def.args)}`,
286
+ 'startup_timeout_sec = 60',
287
+ CODEX_BLOCK_END,
288
+ ].join('\n');
289
+ }
290
+ /** Merge the managed block into `.codex/config.toml` without a TOML parser: only text between our markers is ever replaced. */
291
+ export function mergeCodexToml(existing, def) {
292
+ const block = buildCodexBlock(def);
293
+ if (existing === null)
294
+ return { content: block + '\n', kind: 'create', note: 'create Codex project config with the devworkspace MCP server' };
295
+ const eol = detectEol(existing);
296
+ const blockEol = withEol(block, eol);
297
+ const hasStart = existing.includes('# devworkspace-mcp:start');
298
+ const hasEnd = existing.includes(CODEX_BLOCK_END);
299
+ if (hasStart !== hasEnd) {
300
+ return { content: existing, kind: 'conflict', note: 'managed block markers are unbalanced; fix or remove the stray marker by hand' };
301
+ }
302
+ if (hasStart) {
303
+ const next = existing.replace(new RegExp(CODEX_BLOCK_RE.source.replace(/\\n/g, '\\r?\\n')), () => blockEol);
304
+ return next === existing
305
+ ? { content: existing, kind: 'unchanged', note: 'devworkspace MCP server already configured' }
306
+ : { content: next, kind: 'update', note: 'refresh managed block; the rest of the file is untouched' };
307
+ }
308
+ if (/^\s*\[mcp_servers\.(?:"devworkspace"|devworkspace)[\].]/m.test(existing)) {
309
+ return { content: existing, kind: 'conflict', note: 'a user-defined [mcp_servers.devworkspace] table exists; left untouched (remove it or edit it by hand)' };
310
+ }
311
+ const sep = existing.trim() === '' ? '' : existing.endsWith('\n') ? eol : eol + eol;
312
+ return { content: `${existing}${sep}${blockEol}${eol}`, kind: 'update', note: 'append managed block; existing Codex config preserved' };
313
+ }
314
+ /** Guidance for agents whose MCP config is user-level; DevWorkspace never writes user-level config for you. */
315
+ export function antigravityManualSteps(def) {
193
316
  return {
194
- command: 'npx',
195
- args: ['-y', pkgSpec, 'mcp', 'serve'],
317
+ agent: 'antigravity',
318
+ files: ['~/.gemini/config/mcp_config.json', '~/.gemini/antigravity/mcp_config.json'],
319
+ snippet: JSON.stringify({ mcpServers: { devworkspace: def } }, null, 2),
320
+ steps: [
321
+ 'Antigravity reads MCP servers from a user-level mcp_config.json (no project-level file is documented). Which of the two paths is used depends on your Antigravity build; use the one that already exists.',
322
+ 'Add the "devworkspace" entry from the snippet to its "mcpServers" object, keeping your other servers, then reload Antigravity and check its MCP panel.',
323
+ 'The launch directory for user-level servers is not guaranteed to be this project. If DevWorkspace tools report no workspace, append "--cwd" and the absolute path of this project to args.',
324
+ ],
196
325
  };
197
326
  }
327
+ /**
328
+ * Detect the user-level Antigravity MCP configuration path.
329
+ * Checks candidate paths in order:
330
+ * 1. Explicitly configured env path (ANTIGRAVITY_CONFIG_PATH)
331
+ * 2. ~/.gemini/antigravity/mcp_config.json (if file exists)
332
+ * 3. ~/.gemini/config/mcp_config.json (if file exists)
333
+ * 4. ~/.gemini/antigravity/mcp_config.json (if ~/.gemini/antigravity directory exists)
334
+ * 5. ~/.gemini/config/mcp_config.json (if ~/.gemini/config directory exists)
335
+ * 6. Defaults to ~/.gemini/antigravity/mcp_config.json
336
+ */
337
+ export async function detectAntigravityUserConfigPath(homeDir) {
338
+ const home = homeDir ?? process.env.DEVWORKSPACE_HOME ?? os.homedir();
339
+ if (process.env.ANTIGRAVITY_CONFIG_PATH) {
340
+ return path.resolve(process.env.ANTIGRAVITY_CONFIG_PATH);
341
+ }
342
+ const p1 = path.join(home, '.gemini', 'antigravity', 'mcp_config.json');
343
+ const p2 = path.join(home, '.gemini', 'config', 'mcp_config.json');
344
+ if (await pathExists(p1))
345
+ return p1;
346
+ if (await pathExists(p2))
347
+ return p2;
348
+ if (await pathExists(path.join(home, '.gemini', 'antigravity')))
349
+ return p1;
350
+ if (await pathExists(path.join(home, '.gemini', 'config')))
351
+ return p2;
352
+ return p1;
353
+ }
198
354
  export async function planMcpAgentChanges(root, projectName, agentId, options = {}) {
199
355
  const norm = agentId.toLowerCase();
200
356
  const changes = [];
201
- const serverDef = await resolveMcpServerDef(options);
357
+ const serverDef = options.resolved ?? (await resolveMcpServerDef(options));
202
358
  if (norm === 'claude-code' || norm === 'claude') {
203
359
  // 1. Config: .mcp.json
204
360
  const configPath = '.mcp.json';
@@ -234,61 +390,53 @@ export async function planMcpAgentChanges(root, projectName, agentId, options =
234
390
  });
235
391
  }
236
392
  else if (norm === 'codex') {
237
- // 1. Config: mcp.json
238
- const configPath = 'mcp.json';
239
- const configFull = path.join(root, configPath);
240
- const configExisting = await readIfExists(configFull);
241
- const configMerged = mergeMcpJsonConfig(configExisting, 'devworkspace', serverDef);
242
- changes.push({
243
- path: configPath,
244
- kind: configMerged.kind,
245
- mode: 'owned',
246
- content: configMerged.content,
247
- note: configMerged.note,
248
- });
393
+ // 1. Config: .codex/config.toml (project-scoped, used by Codex in trusted projects; [mcp_servers.<name>] tables)
394
+ const configPath = '.codex/config.toml';
395
+ const configExisting = await readIfExists(path.join(root, configPath));
396
+ const merged = mergeCodexToml(configExisting, serverDef);
397
+ changes.push({ path: configPath, kind: merged.kind, mode: 'section', content: merged.content, note: merged.note });
249
398
  // 2. Instructions: AGENTS.md
250
399
  const instPath = 'AGENTS.md';
251
- const instFull = path.join(root, instPath);
252
- const instExisting = await readIfExists(instFull);
253
- const instructions = buildMcpInstructions(projectName, 'OpenAI Codex');
254
- const mergedInst = mergeMcpSection(instExisting, instructions);
255
- changes.push({
256
- path: instPath,
257
- kind: mergedInst.kind,
258
- mode: 'section',
259
- content: mergedInst.content,
260
- note: mergedInst.note,
261
- });
400
+ const instExisting = await readIfExists(path.join(root, instPath));
401
+ const mergedInst = mergeMcpSection(instExisting, buildMcpInstructions(projectName, 'OpenAI Codex'));
402
+ changes.push({ path: instPath, kind: mergedInst.kind, mode: 'section', content: mergedInst.content, note: mergedInst.note });
262
403
  }
263
- else if (norm === 'antigravity') {
264
- // 1. Config: .antigravity/mcp.json
265
- const configPath = '.antigravity/mcp.json';
266
- const configFull = path.join(root, configPath);
267
- const configExisting = await readIfExists(configFull);
268
- const configMerged = mergeMcpJsonConfig(configExisting, 'devworkspace', serverDef);
404
+ else if (norm === 'antigravity' && options.user === true) {
405
+ const userConfigPath = await detectAntigravityUserConfigPath(options.homeDir);
406
+ const existing = await readIfExists(userConfigPath);
407
+ const antigravityArgs = serverDef.args.includes('--cwd') ? serverDef.args : [...serverDef.args, '--cwd', root];
408
+ const antigravityDef = { command: serverDef.command, args: antigravityArgs };
409
+ const merged = mergeMcpJsonConfig(existing, 'devworkspace', antigravityDef);
269
410
  changes.push({
270
- path: configPath,
271
- kind: configMerged.kind,
411
+ path: userConfigPath,
412
+ kind: merged.kind,
272
413
  mode: 'owned',
273
- content: configMerged.content,
274
- note: configMerged.note,
275
- });
276
- // 2. Instructions: .antigravity/rules
277
- const instPath = '.antigravity/rules';
278
- const instFull = path.join(root, instPath);
279
- const instExisting = await readIfExists(instFull);
280
- const instructions = buildMcpInstructions(projectName, 'Google Antigravity');
281
- const mergedInst = mergeMcpSection(instExisting, instructions);
282
- changes.push({
283
- path: instPath,
284
- kind: mergedInst.kind,
285
- mode: 'section',
286
- content: mergedInst.content,
287
- note: mergedInst.note,
414
+ content: merged.content,
415
+ note: merged.note,
288
416
  });
289
417
  }
418
+ // Antigravity without --user: its MCP config is user-level (~/.gemini/.../mcp_config.json) and no project-level file is documented, so
419
+ // there is nothing safe to write without explicit --user authorization; setupMcpAgent returns manual steps instead (see antigravityManualSteps).
290
420
  return changes;
291
421
  }
422
+ /** Re-reads a generated JSON config and confirms it parses and carries the expected devworkspace entry. */
423
+ async function validateMcpConfigFile(root, rel, def) {
424
+ const text = await readIfExists(path.join(root, rel));
425
+ if (text === null)
426
+ return { path: rel, ok: false, detail: 'file is missing after write' };
427
+ if (rel.endsWith('.toml')) {
428
+ const ok = text.includes('[mcp_servers.devworkspace]') && text.includes(`command = ${JSON.stringify(def.command)}`) && text.includes(`args = ${JSON.stringify(def.args)}`);
429
+ return ok ? { path: rel, ok: true, detail: 'contains the expected [mcp_servers.devworkspace] table' } : { path: rel, ok: false, detail: 'devworkspace table is missing or differs from the generated launcher' };
430
+ }
431
+ try {
432
+ const entry = JSON.parse(text).mcpServers?.devworkspace;
433
+ const same = entry?.command === def.command && Array.isArray(entry.args) && entry.args.length === def.args.length && entry.args.every((a, i) => a === def.args[i]);
434
+ return same ? { path: rel, ok: true, detail: 'valid JSON with the expected devworkspace server entry' } : { path: rel, ok: false, detail: 'devworkspace server entry is missing or differs from the generated launcher' };
435
+ }
436
+ catch (e) {
437
+ return { path: rel, ok: false, detail: `invalid JSON: ${e.message}` };
438
+ }
439
+ }
292
440
  export async function setupMcpAgent(opts = {}) {
293
441
  const ws = await requireWorkspace(opts.cwd ?? process.cwd());
294
442
  const project = await loadProject(ws);
@@ -300,40 +448,142 @@ export async function setupMcpAgent(opts = {}) {
300
448
  hint: `Supported agents: ${SUPPORTED_MCP_AGENTS.filter((a) => a !== 'all').join(', ')}, all.`,
301
449
  });
302
450
  }
303
- const targets = norm === 'all' ? ['claude-code', 'codex', 'antigravity'] : [norm];
304
- const allChanges = [];
305
451
  const notes = [];
452
+ let targets;
453
+ if (norm === 'all')
454
+ targets = ['claude-code', 'codex', 'antigravity'];
455
+ else if (norm === 'auto') {
456
+ const detected = await detectMcpAgents(ws.root);
457
+ targets = detected.length > 0 ? detected : ['claude-code'];
458
+ notes.push(detected.length > 0 ? `Detected agent(s): ${detected.join(', ')}` : 'No agent detected; defaulting to claude-code. Use --agent to choose another.');
459
+ }
460
+ else
461
+ targets = [norm === 'claude' ? 'claude-code' : norm];
462
+ const launcher = await resolveMcpLauncher({ launcher: opts.launcher, packageVersion: opts.packageVersion, projectRoot: ws.root });
463
+ const serverDef = { command: launcher.command, args: launcher.args };
464
+ const antigravityDef = {
465
+ command: serverDef.command,
466
+ args: serverDef.args.includes('--cwd') ? serverDef.args : [...serverDef.args, '--cwd', ws.root],
467
+ };
468
+ const allChanges = [];
306
469
  for (const t of targets) {
307
- const planned = await planMcpAgentChanges(ws.root, project.name, t, {
308
- launcher: opts.launcher,
309
- packageVersion: opts.packageVersion,
310
- });
311
- allChanges.push(...planned);
312
- notes.push(`Configured MCP integration for ${t}`);
470
+ allChanges.push(...(await planMcpAgentChanges(ws.root, project.name, t, { resolved: serverDef, user: opts.user, homeDir: opts.homeDir })));
471
+ notes.push(t === 'antigravity' && opts.user ? `Configured user-level MCP integration for ${t}` : `Configured MCP integration for ${t}`);
472
+ }
473
+ const conflicts = allChanges.filter((c) => c.kind === 'conflict');
474
+ for (const c of conflicts) {
475
+ notes.push(`${c.path}: ${c.note}. Nothing was changed. Repair or move that file aside, then re-run "devworkspace setup --agent ${rawAgent}".`);
313
476
  }
314
- const conflicts = allChanges.filter((c) => c.kind === 'conflict').length;
315
- if (!isCheck && conflicts === 0) {
477
+ const validation = [];
478
+ let verification;
479
+ let agentObservation;
480
+ let versionMismatch;
481
+ let backupPath;
482
+ if (!isCheck && conflicts.length === 0) {
316
483
  await withLock(ws.dir, async () => {
317
484
  for (const change of allChanges) {
318
485
  if (change.kind === 'create' || change.kind === 'update') {
319
- const full = resolveInside(ws.root, change.path);
320
- await assertNoSymlinkEscape(ws.root, full);
321
- await atomicWriteFile(full, change.content);
486
+ if (path.isAbsolute(change.path)) {
487
+ const dir = path.dirname(change.path);
488
+ await fs.mkdir(dir, { recursive: true });
489
+ if (change.kind === 'update') {
490
+ backupPath = `${change.path}.bak-${Date.now()}`;
491
+ await fs.copyFile(change.path, backupPath);
492
+ }
493
+ try {
494
+ await atomicWriteFile(change.path, change.content);
495
+ }
496
+ catch (err) {
497
+ if (backupPath && (await pathExists(backupPath))) {
498
+ await fs.copyFile(backupPath, change.path).catch(() => undefined);
499
+ }
500
+ throw new DevWorkspaceError('IO', `Failed to write user-level MCP config: ${err.message}`, {
501
+ hint: backupPath ? `Rolled back from ${backupPath}` : undefined,
502
+ });
503
+ }
504
+ }
505
+ else {
506
+ const full = resolveInside(ws.root, change.path);
507
+ await assertNoSymlinkEscape(ws.root, full);
508
+ await atomicWriteFile(full, change.content);
509
+ }
322
510
  }
323
511
  }
324
512
  });
513
+ for (const c of allChanges.filter((x) => /\.(json|toml)$/.test(x.path))) {
514
+ if (path.isAbsolute(c.path)) {
515
+ const val = await validateMcpConfigFile(path.dirname(c.path), path.basename(c.path), antigravityDef);
516
+ validation.push(val);
517
+ if (!val.ok && backupPath && (await pathExists(backupPath))) {
518
+ await fs.copyFile(backupPath, c.path).catch(() => undefined);
519
+ }
520
+ }
521
+ else {
522
+ validation.push(await validateMcpConfigFile(ws.root, c.path, serverDef));
523
+ }
524
+ }
525
+ if (opts.verify === true && validation.every((v) => v.ok)) {
526
+ verification = await (opts.verifyFn ?? verifyMcpServer)(serverDef, { cwd: ws.root });
527
+ // Only the agent's own CLI can say whether the agent sees the server; ask it, and claim nothing if it is absent.
528
+ const expected = opts.packageVersion && /^\d+\.\d+\.\d+/.test(opts.packageVersion) ? opts.packageVersion : packageVersion();
529
+ if (verification.ok && verification.serverVersion && opts.packageVersion !== 'latest' && verification.serverVersion !== expected) {
530
+ versionMismatch = { expected, actual: verification.serverVersion };
531
+ }
532
+ if (verification.ok && targets.includes('claude-code')) {
533
+ agentObservation = await (opts.observeFn ?? observeClaudeCode)(ws.root);
534
+ }
535
+ }
536
+ }
537
+ const manual = targets.includes('antigravity') && !opts.user ? [antigravityManualSteps(serverDef)] : [];
538
+ const userActions = [];
539
+ if (!isCheck && conflicts.length === 0) {
540
+ if (targets.includes('claude-code')) {
541
+ const o = agentObservation;
542
+ if (o?.status === 'connected')
543
+ userActions.push('Claude Code reports the "devworkspace" server as connected. If your session was already open, reload it to pick up the tools.');
544
+ else if (o?.status === 'failed')
545
+ userActions.push(`Claude Code could not start the server: ${o.detail}. Run "claude mcp get devworkspace" for details.`);
546
+ else
547
+ userActions.push('Claude Code: open or reload the project and approve the "devworkspace" server when prompted (project-scoped servers need your approval; DevWorkspace cannot approve it for you). Check with /mcp.');
548
+ }
549
+ if (targets.includes('codex')) {
550
+ userActions.push('Codex: .codex/config.toml is read only for trusted projects. Trust this project, restart Codex, and check /mcp. Not verified from here: no Codex CLI was exercised.');
551
+ }
552
+ if (targets.includes('antigravity')) {
553
+ if (opts.user) {
554
+ const userPath = await detectAntigravityUserConfigPath(opts.homeDir);
555
+ userActions.push(`Antigravity: user-level MCP configuration written to ${userPath}${backupPath ? ` (backup: ${backupPath})` : ''}. Reload Antigravity to pick up the DevWorkspace tools.`);
556
+ }
557
+ else {
558
+ userActions.push('Antigravity: no project-level MCP file is documented. To configure automatically at user level, re-run with --user (devworkspace setup --agent antigravity --user). Otherwise, add the server to your user-level mcp_config.json yourself (steps below).');
559
+ }
560
+ }
561
+ if (versionMismatch) {
562
+ userActions.push(`The launcher started devworkspace ${versionMismatch.actual}, not ${versionMismatch.expected} (this CLI). Pin it with --package-version ${versionMismatch.expected} once that version is published, or use --launcher direct with a matching install.`);
563
+ }
564
+ if (process.platform === 'win32' && launcher.command === 'cmd' && allChanges.some((c) => /(^|\/)(\.mcp\.json|\.codex\/config\.toml)$/.test(c.path) && c.kind !== 'unchanged')) {
565
+ notes.push('The launcher is written as "cmd /c npx ..." for Windows. If this file is committed and shared, macOS/Linux teammates must re-run "devworkspace setup" locally (or use a user-scoped config) because they have no cmd.');
566
+ }
567
+ if (verification && !verification.ok) {
568
+ userActions.push(`Fix the ${verification.failedStage} failure above, then re-run the same command; it is safe to repeat.`);
569
+ }
325
570
  }
326
571
  return {
327
572
  agent: rawAgent,
328
573
  check: isCheck,
329
- changes: allChanges.map((c) => ({
330
- path: c.path,
331
- kind: c.kind,
332
- mode: c.mode,
333
- note: c.note,
334
- })),
335
- conflicts,
574
+ changes: allChanges.map((c) => ({ path: c.path, kind: c.kind, mode: c.mode, note: c.note })),
575
+ conflicts: conflicts.length,
336
576
  notes,
577
+ agents: targets,
578
+ launcher: { command: launcher.command, args: launcher.args, mode: launcher.mode, reason: launcher.reason },
579
+ validation,
580
+ ...(verification ? { verification } : {}),
581
+ ...(agentObservation ? { agentObservation } : {}),
582
+ ...(versionMismatch ? { versionMismatch } : {}),
583
+ userActions,
584
+ manual,
585
+ ...(backupPath ? { backup: backupPath } : {}),
586
+ cli: (({ version, path: p, mode }) => ({ version, path: p, mode }))(detectCliProvenance()),
337
587
  };
338
588
  }
339
589
  //# sourceMappingURL=setup.js.map