opencastle 1.13.0 → 1.13.1

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 (102) hide show
  1. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  2. package/dist/cli/adapters/rules-dir-base.js +8 -5
  3. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  4. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  5. package/dist/cli/adapters/single-file-base.js +25 -4
  6. package/dist/cli/adapters/single-file-base.js.map +1 -1
  7. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  8. package/dist/cli/adapters/vscode.js +8 -5
  9. package/dist/cli/adapters/vscode.js.map +1 -1
  10. package/dist/cli/convoy/engine.d.ts.map +1 -1
  11. package/dist/cli/convoy/engine.git.test.js +206 -1
  12. package/dist/cli/convoy/engine.git.test.js.map +1 -1
  13. package/dist/cli/convoy/engine.js +116 -13
  14. package/dist/cli/convoy/engine.js.map +1 -1
  15. package/dist/cli/convoy/merge.d.ts +24 -5
  16. package/dist/cli/convoy/merge.d.ts.map +1 -1
  17. package/dist/cli/convoy/merge.js +108 -10
  18. package/dist/cli/convoy/merge.js.map +1 -1
  19. package/dist/cli/convoy/merge.test.js +59 -0
  20. package/dist/cli/convoy/merge.test.js.map +1 -1
  21. package/dist/cli/convoy/worktree.d.ts +6 -1
  22. package/dist/cli/convoy/worktree.d.ts.map +1 -1
  23. package/dist/cli/convoy/worktree.js +7 -0
  24. package/dist/cli/convoy/worktree.js.map +1 -1
  25. package/dist/cli/convoy/worktree.test.js +15 -1
  26. package/dist/cli/convoy/worktree.test.js.map +1 -1
  27. package/dist/cli/doctor.d.ts.map +1 -1
  28. package/dist/cli/doctor.js +23 -3
  29. package/dist/cli/doctor.js.map +1 -1
  30. package/dist/cli/foreign-skills.d.ts +23 -0
  31. package/dist/cli/foreign-skills.d.ts.map +1 -1
  32. package/dist/cli/foreign-skills.js +91 -1
  33. package/dist/cli/foreign-skills.js.map +1 -1
  34. package/dist/cli/foreign-skills.test.js +95 -2
  35. package/dist/cli/foreign-skills.test.js.map +1 -1
  36. package/dist/cli/init.d.ts.map +1 -1
  37. package/dist/cli/init.js +17 -5
  38. package/dist/cli/init.js.map +1 -1
  39. package/dist/cli/lock.d.ts +9 -0
  40. package/dist/cli/lock.d.ts.map +1 -1
  41. package/dist/cli/lock.js +16 -0
  42. package/dist/cli/lock.js.map +1 -1
  43. package/dist/cli/mcp-audit.d.ts +6 -3
  44. package/dist/cli/mcp-audit.d.ts.map +1 -1
  45. package/dist/cli/mcp-audit.js +22 -7
  46. package/dist/cli/mcp-audit.js.map +1 -1
  47. package/dist/cli/mcp-ownership.test.d.ts +2 -0
  48. package/dist/cli/mcp-ownership.test.d.ts.map +1 -0
  49. package/dist/cli/mcp-ownership.test.js +141 -0
  50. package/dist/cli/mcp-ownership.test.js.map +1 -0
  51. package/dist/cli/mcp.d.ts +36 -5
  52. package/dist/cli/mcp.d.ts.map +1 -1
  53. package/dist/cli/mcp.js +101 -33
  54. package/dist/cli/mcp.js.map +1 -1
  55. package/dist/cli/remove.d.ts.map +1 -1
  56. package/dist/cli/remove.js +4 -4
  57. package/dist/cli/remove.js.map +1 -1
  58. package/dist/cli/root-files.d.ts +59 -0
  59. package/dist/cli/root-files.d.ts.map +1 -0
  60. package/dist/cli/root-files.js +133 -0
  61. package/dist/cli/root-files.js.map +1 -0
  62. package/dist/cli/root-files.test.d.ts +2 -0
  63. package/dist/cli/root-files.test.d.ts.map +1 -0
  64. package/dist/cli/root-files.test.js +152 -0
  65. package/dist/cli/root-files.test.js.map +1 -0
  66. package/dist/cli/sync-check.d.ts +1 -1
  67. package/dist/cli/sync-check.d.ts.map +1 -1
  68. package/dist/cli/sync-check.js +19 -4
  69. package/dist/cli/sync-check.js.map +1 -1
  70. package/dist/cli/team-ci.test.js +8 -1
  71. package/dist/cli/team-ci.test.js.map +1 -1
  72. package/dist/cli/unreadable-report.d.ts.map +1 -1
  73. package/dist/cli/unreadable-report.js +3 -0
  74. package/dist/cli/unreadable-report.js.map +1 -1
  75. package/dist/cli/update.d.ts.map +1 -1
  76. package/dist/cli/update.js +33 -8
  77. package/dist/cli/update.js.map +1 -1
  78. package/package.json +1 -1
  79. package/src/cli/adapters/rules-dir-base.ts +6 -5
  80. package/src/cli/adapters/single-file-base.ts +25 -4
  81. package/src/cli/adapters/vscode.ts +10 -6
  82. package/src/cli/convoy/engine.git.test.ts +227 -1
  83. package/src/cli/convoy/engine.ts +112 -12
  84. package/src/cli/convoy/merge.test.ts +72 -0
  85. package/src/cli/convoy/merge.ts +128 -15
  86. package/src/cli/convoy/worktree.test.ts +16 -1
  87. package/src/cli/convoy/worktree.ts +13 -3
  88. package/src/cli/doctor.ts +23 -1
  89. package/src/cli/foreign-skills.test.ts +111 -2
  90. package/src/cli/foreign-skills.ts +93 -1
  91. package/src/cli/init.ts +15 -5
  92. package/src/cli/lock.ts +18 -0
  93. package/src/cli/mcp-audit.ts +22 -6
  94. package/src/cli/mcp-ownership.test.ts +167 -0
  95. package/src/cli/mcp.ts +104 -29
  96. package/src/cli/remove.ts +4 -3
  97. package/src/cli/root-files.test.ts +169 -0
  98. package/src/cli/root-files.ts +140 -0
  99. package/src/cli/sync-check.ts +20 -5
  100. package/src/cli/team-ci.test.ts +8 -1
  101. package/src/cli/unreadable-report.ts +3 -0
  102. package/src/cli/update.ts +30 -7
@@ -1,7 +1,7 @@
1
1
  import { resolve } from 'node:path'
2
2
  import { existsSync, readFileSync } from 'node:fs'
3
3
  import { PLUGINS } from '../orchestrator/plugins/index.js'
4
- import { getMcpConfigRelPath, upgradeGeneratedServers, canonicalJson } from './mcp.js'
4
+ import { getMcpConfigRelPath, upgradeGeneratedServers, canonicalJson, isOurEntry } from './mcp.js'
5
5
  import { parseMcpConfigText } from './mcp-file.js'
6
6
  import type { IdeChoice } from './types.js'
7
7
  import { disallowedBy, hostDisallowedBy, findInlineSecret, hostOfUrl, type EffectivePolicy } from './policy.js'
@@ -52,7 +52,8 @@ export interface McpFinding {
52
52
  pkg?: string
53
53
  /**
54
54
  * `replaces`: still exactly as a release wrote it, so sync moves it forward.
55
- * `removes`: a plugin's server the project's stack no longer includes.
55
+ * `removes`: a plugin's server, still as a release wrote it, that the
56
+ * project's stack no longer includes.
56
57
  * `keeps`: edited since, or never ours — only a person changes it.
57
58
  * A remedy that says "run sync" is only true for the first.
58
59
  */
@@ -297,6 +298,8 @@ export function auditMcpConfig(
297
298
  ide: IdeChoice,
298
299
  included?: Set<string>,
299
300
  team?: TeamAuditContext,
301
+ /** Integration servers the last compile gave the project, from the lock; null with no lock. */
302
+ given?: ReadonlySet<string> | null,
300
303
  ): McpAudit {
301
304
  const pluginByKey = new Map(
302
305
  Object.values(PLUGINS)
@@ -315,7 +318,7 @@ export function auditMcpConfig(
315
318
  const present = new Set<string>()
316
319
  for (const [server, entry] of serverEntries(config)) {
317
320
  present.add(server)
318
- const plugin = pluginByKey.get(server)
321
+ let plugin = pluginByKey.get(server)
319
322
  const teamWhere = team?.definedIn[server]
320
323
  let sync: SyncEffect = 'keeps'
321
324
  let removal: McpFinding['removal']
@@ -332,9 +335,21 @@ export function auditMcpConfig(
332
335
  sync = 'removes'
333
336
  removal = 'retired'
334
337
  } else if (plugin) {
338
+ // Outside the stack, `sync` removes only an entry it gave the project,
339
+ // still as a release wrote it (`isOurEntry`); one a person changed or
340
+ // wrote under the integration's name stays theirs, and saying `sync`
341
+ // removes it kept `sync --check` red over a file `sync` will rightly
342
+ // never change.
335
343
  if (included && !included.has(server)) {
336
- sync = 'removes'
337
- removal = 'stack'
344
+ if (isOurEntry(server, entry, ide, given)) {
345
+ sync = 'removes'
346
+ removal = 'stack'
347
+ } else {
348
+ // Theirs, under the integration's name: the remedy for it is theirs
349
+ // too, not "changed since OpenCastle wrote it" and a `sync --force`
350
+ // that would not write a server the stack leaves out.
351
+ plugin = undefined
352
+ }
338
353
  } else if (upgradeGeneratedServers({ [server]: structuredClone(entry) }, ide, new Set([server])).length > 0) {
339
354
  sync = 'replaces'
340
355
  }
@@ -572,6 +587,7 @@ export function checkMcpSupplyChain(
572
587
  ide: IdeChoice,
573
588
  included?: Set<string>,
574
589
  team?: TeamAuditContext,
590
+ given?: ReadonlySet<string> | null,
575
591
  ): McpAuditResult {
576
592
  const rel = getMcpConfigRelPath(ide)
577
593
  const abs = resolve(projectRoot, rel)
@@ -583,7 +599,7 @@ export function checkMcpSupplyChain(
583
599
  return { ok: true, label: LABEL, detail: `${rel} could not be read (reported above)` }
584
600
  }
585
601
 
586
- const audit = auditMcpConfig(parsed, ide, included, team)
602
+ const audit = auditMcpConfig(parsed, ide, included, team, given)
587
603
  const broken = audit.findings.filter((f) => isFailure(f, team?.policy))
588
604
  const warned = audit.findings.filter((f) => !isFailure(f, team?.policy))
589
605
  const unpinned = warned.filter((f) => f.problem === 'unpinned')
@@ -0,0 +1,167 @@
1
+ /**
2
+ * An MCP server under an integration's name is not OpenCastle's because of its
3
+ * name.
4
+ *
5
+ * `Sentry`, `Linear`, `chrome-devtools` are the keys each server's own README
6
+ * suggests, and `sync` used to delete any entry under one of them the moment
7
+ * the stack did not include that integration — a teammate's self-hosted URL,
8
+ * args and env gone from a committed file, with a message blaming the stack.
9
+ * `remove` did the same. Only an entry the last compile gave the project (the
10
+ * lock says which) that still reads as a release wrote it is ours to take out.
11
+ */
12
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
13
+ import { spawnSync, execFileSync } from 'node:child_process'
14
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
15
+ import { tmpdir } from 'node:os'
16
+ import { join, resolve } from 'node:path'
17
+ import { rebuildMcpConfig, willKeepSomethingAfterStrip, isGeneratedEntry, isOurEntry } from './mcp.js'
18
+ import { auditMcpConfig } from './mcp-audit.js'
19
+ import type { StackConfig } from './types.js'
20
+
21
+ /** A teammate's own Sentry: self-hosted, its own args and env. */
22
+ const theirSentry = {
23
+ command: 'npx',
24
+ args: ['@sentry/mcp-server@0.42.0', '--host', 'sentry.acme.example'],
25
+ env: { SENTRY_ACCESS_TOKEN: '${SENTRY_ACCESS_TOKEN}', SENTRY_HOST: 'sentry.acme.example' },
26
+ }
27
+ /** Sentry exactly as OpenCastle writes it into `.mcp.json`. */
28
+ const ourSentry = { command: 'npx', args: ['@sentry/mcp-server@0.42.0'], env: { SENTRY_ACCESS_TOKEN: '${SENTRY_ACCESS_TOKEN}' } }
29
+ /** chrome-devtools as its upstream README gives it — to the byte, an earlier OpenCastle default. */
30
+ const readmeChrome = { command: 'npx', args: ['-y', 'chrome-devtools-mcp@latest'] }
31
+
32
+ describe('whose entry it is', () => {
33
+ it('is ours only while it reads as a release wrote it', () => {
34
+ expect(isGeneratedEntry('Sentry', ourSentry, 'claude-code')).toBe(true)
35
+ expect(isGeneratedEntry('Sentry', theirSentry, 'claude-code')).toBe(false)
36
+ expect(isGeneratedEntry('Mine', { command: 'node' }, 'claude-code')).toBe(false)
37
+ })
38
+
39
+ it('is not ours if the stack never gave it to the project, however it reads', () => {
40
+ expect(isGeneratedEntry('chrome-devtools', readmeChrome, 'claude-code')).toBe(true)
41
+ expect(isOurEntry('chrome-devtools', readmeChrome, 'claude-code', new Set(['Sentry']))).toBe(false)
42
+ expect(isOurEntry('chrome-devtools', readmeChrome, 'claude-code', new Set(['chrome-devtools']))).toBe(true)
43
+ // An install from before the lock: the shape alone decides.
44
+ expect(isOurEntry('chrome-devtools', readmeChrome, 'claude-code', null)).toBe(true)
45
+ })
46
+ })
47
+
48
+ describe('sync, when the stack does not include the integration', () => {
49
+ let root: string
50
+ const stack: StackConfig = { ides: ['claude-code'], techTools: [], teamTools: [] }
51
+ const write = (servers: Record<string, unknown>): void =>
52
+ writeFileSync(join(root, '.mcp.json'), JSON.stringify({ mcpServers: servers }, null, 2) + '\n')
53
+ const servers = (): Record<string, unknown> => JSON.parse(readFileSync(join(root, '.mcp.json'), 'utf8')).mcpServers
54
+
55
+ beforeEach(() => {
56
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'mcp-ownership-')))
57
+ })
58
+ afterEach(() => rmSync(root, { recursive: true, force: true }))
59
+
60
+ it('keeps a server someone wrote under its name, and removes the one we wrote', async () => {
61
+ write({ Sentry: theirSentry, Linear: { type: 'http', url: 'https://mcp.linear.app/mcp' } })
62
+ const { removed } = await rebuildMcpConfig(root, 'claude-code', stack, undefined, undefined, new Set(['Sentry', 'Linear']))
63
+ expect(removed).toEqual(['Linear'])
64
+ expect(servers()).toEqual({ Sentry: theirSentry })
65
+ })
66
+
67
+ it('keeps an exact copy of our default that the stack never gave the project', async () => {
68
+ write({ 'chrome-devtools': readmeChrome })
69
+ const { removed } = await rebuildMcpConfig(root, 'claude-code', stack, undefined, undefined, new Set())
70
+ expect(removed).toEqual([])
71
+ expect(servers()).toEqual({ 'chrome-devtools': readmeChrome })
72
+ })
73
+
74
+ it('keeps the VS Code input a kept server still reads', async () => {
75
+ const theirs = { type: 'http', url: 'https://api.githubcopilot.com/mcp/', headers: { Authorization: 'Bearer ${input:github_token}' } }
76
+ const inputs = [{ id: 'github_token', type: 'promptString', description: 'GitHub token', password: true }]
77
+ mkdirSync(join(root, '.vscode'))
78
+ writeFileSync(join(root, '.vscode/mcp.json'), JSON.stringify({ servers: { GitHub: theirs }, inputs }, null, 2) + '\n')
79
+ const vscode: StackConfig = { ides: ['vscode'], techTools: [], teamTools: [] }
80
+ await rebuildMcpConfig(root, 'vscode', vscode, undefined, undefined, new Set(['GitHub']))
81
+ const after = JSON.parse(readFileSync(join(root, '.vscode/mcp.json'), 'utf8'))
82
+ expect(after.servers.GitHub).toEqual(theirs)
83
+ expect(after.inputs).toEqual(inputs)
84
+ })
85
+
86
+ it('is what the audit says sync does: nothing for theirs, removal for ours', () => {
87
+ const given = new Set(['Sentry', 'Linear'])
88
+ const audit = auditMcpConfig(
89
+ { mcpServers: { Sentry: theirSentry, Linear: { type: 'http', url: 'https://mcp.linear.app/mcp' } } },
90
+ 'claude-code',
91
+ new Set(),
92
+ undefined,
93
+ given,
94
+ )
95
+ expect(audit.removed).toEqual(['Linear'])
96
+ // Theirs, so the remedy for anything wrong with it is theirs too.
97
+ expect(audit.findings.every((f) => f.server !== 'Sentry' || (f.sync === 'keeps' && !f.plugin))).toBe(true)
98
+ })
99
+ })
100
+
101
+ describe('remove', () => {
102
+ it('takes out the servers we wrote and leaves theirs', () => {
103
+ const parsed: Record<string, unknown> = { mcpServers: { Sentry: theirSentry, 'chrome-devtools': readmeChrome, Linear: { type: 'http', url: 'https://mcp.linear.app/mcp' } } }
104
+ const keeps = willKeepSomethingAfterStrip(parsed, 'claude-code', [], [], new Set(['Linear']))
105
+ expect(keeps).toBe(true)
106
+ expect(parsed).toEqual({ mcpServers: { Sentry: theirSentry, 'chrome-devtools': readmeChrome } })
107
+ })
108
+ })
109
+
110
+ const repoRoot = resolve(import.meta.dirname, '..', '..')
111
+ const cli = join(repoRoot, 'bin', 'cli.mjs')
112
+ const cliBuilt = existsSync(join(repoRoot, 'dist', 'cli', 'init.js'))
113
+
114
+ describe.skipIf(!cliBuilt)('a teammate’s own Sentry server, through sync and remove', () => {
115
+ let projectRoot: string
116
+ const run = (...args: string[]): { status: number | null; out: string } => {
117
+ const r = spawnSync('node', [cli, ...args], { cwd: projectRoot, encoding: 'utf8', input: '' })
118
+ return { status: r.status, out: `${r.stdout}${r.stderr}` }
119
+ }
120
+ const servers = (): Record<string, unknown> => JSON.parse(readFileSync(join(projectRoot, '.mcp.json'), 'utf8')).mcpServers
121
+
122
+ beforeEach(() => {
123
+ projectRoot = mkdtempSync(join(tmpdir(), 'oc-mcp-ownership-'))
124
+ execFileSync('git', ['init', '-q'], { cwd: projectRoot })
125
+ writeFileSync(join(projectRoot, 'package.json'), JSON.stringify({ name: 'demo' }))
126
+ mkdirSync(join(projectRoot, '.claude'))
127
+ execFileSync('node', [cli, 'init', '--yes'], { cwd: projectRoot, stdio: 'ignore' })
128
+ })
129
+ afterEach(() => rmSync(projectRoot, { recursive: true, force: true }))
130
+
131
+ it('keeps it through sync --yes and remove --all, and the check stays clean', () => {
132
+ const config = JSON.parse(readFileSync(join(projectRoot, '.mcp.json'), 'utf8'))
133
+ config.mcpServers.Sentry = theirSentry
134
+ writeFileSync(join(projectRoot, '.mcp.json'), JSON.stringify(config, null, 2) + '\n')
135
+
136
+ const sync = run('sync', '--yes')
137
+ expect(sync.status).toBe(0)
138
+ expect(sync.out).not.toContain('Sentry')
139
+ expect(servers().Sentry).toEqual(theirSentry)
140
+ expect(run('sync', '--check').status).toBe(0)
141
+
142
+ expect(run('remove', '--all', '--yes').status).toBe(0)
143
+ expect(servers()).toEqual({ Sentry: theirSentry })
144
+ })
145
+
146
+ it('still removes the server we wrote when the stack drops it, and not theirs beside it', () => {
147
+ const config = JSON.parse(readFileSync(join(projectRoot, '.mcp.json'), 'utf8'))
148
+ expect(Object.keys(config.mcpServers)).toContain('chrome-devtools')
149
+ config.mcpServers.Sentry = theirSentry
150
+ writeFileSync(join(projectRoot, '.mcp.json'), JSON.stringify(config, null, 2) + '\n')
151
+ const manifestPath = join(projectRoot, '.opencastle/manifest.json')
152
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
153
+ manifest.stack.techTools = manifest.stack.techTools.filter((t: string) => t !== 'chrome-devtools')
154
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
155
+
156
+ const sync = run('sync', '--yes')
157
+ expect(sync.status).toBe(0)
158
+ expect(sync.out).toContain("Removed 1 MCP server(s) this project's stack no longer includes: chrome-devtools")
159
+ expect(Object.keys(servers())).toEqual(['Sentry'])
160
+
161
+ // Added after, from its README: the stack does not give it to the project.
162
+ writeFileSync(join(projectRoot, '.mcp.json'), JSON.stringify({ mcpServers: { ...servers(), 'chrome-devtools': readmeChrome } }, null, 2) + '\n')
163
+ expect(run('sync', '--yes').status).toBe(0)
164
+ expect(servers()['chrome-devtools']).toEqual(readmeChrome)
165
+ expect(run('sync', '--check').status).toBe(0)
166
+ })
167
+ })
package/src/cli/mcp.ts CHANGED
@@ -437,20 +437,7 @@ export function upgradeGeneratedServers(
437
437
  const current = entryFor(serverFor(plugin, ide), ide);
438
438
  const have = canonical(existingServers[key]);
439
439
  if (have === canonical(current)) continue;
440
- // Every shape an earlier release wrote: each earlier default, in the entry
441
- // shape and the env-variable spelling of the time.
442
- const earlier: unknown[] = [];
443
- const configs = [
444
- { mcpConfig: plugin.mcpConfig, envVars: plugin.envVars, tokenAuth: plugin.tokenAuth },
445
- ...(plugin.previousMcpConfigs ?? []).map((p) => ({ mcpConfig: p.mcpConfig, envVars: p.envVars })),
446
- ];
447
- for (const cfg of configs) {
448
- for (const legacyEnv of [false, true]) {
449
- const old = serverFor(cfg, ide, legacyEnv);
450
- earlier.push(entryFor(old, ide), entryFor(old, ide, true));
451
- }
452
- }
453
- if (earlier.some((e) => canonical(e) === have)) {
440
+ if (generatedShapes(plugin, ide).has(have)) {
454
441
  existingServers[key] = current;
455
442
  upgraded.push(key);
456
443
  }
@@ -458,6 +445,74 @@ export function upgradeGeneratedServers(
458
445
  return upgraded;
459
446
  }
460
447
 
448
+ // A record, so a target added to `IdeChoice` and not here fails to compile.
449
+ const TARGETS: Record<IdeChoice, true> = {
450
+ vscode: true, cursor: true, 'claude-code': true, opencode: true, windsurf: true, codex: true, antigravity: true,
451
+ };
452
+ const ALL_TARGETS = Object.keys(TARGETS) as IdeChoice[];
453
+
454
+ /**
455
+ * Every entry a release of this tool has written for `plugin` into `ide`'s
456
+ * config, canonicalised: the current default and each earlier one, in the
457
+ * entry shape and the env-variable spelling of the time.
458
+ */
459
+ function generatedShapes(plugin: PluginConfig, ide: IdeChoice): Set<string> {
460
+ const shapes = new Set<string>();
461
+ if (!plugin.mcpConfig) return shapes;
462
+ const configs = [
463
+ { mcpConfig: plugin.mcpConfig, envVars: plugin.envVars, tokenAuth: plugin.tokenAuth },
464
+ ...(plugin.previousMcpConfigs ?? []).map((p) => ({ mcpConfig: p.mcpConfig, envVars: p.envVars })),
465
+ ];
466
+ for (const cfg of configs) {
467
+ for (const legacyEnv of [false, true]) {
468
+ const old = serverFor(cfg, ide, legacyEnv);
469
+ shapes.add(canonical(entryFor(old, ide)));
470
+ shapes.add(canonical(entryFor(old, ide, true)));
471
+ }
472
+ }
473
+ return shapes;
474
+ }
475
+
476
+ /**
477
+ * Whether an entry under an integration's server key is one this tool wrote
478
+ * and nobody has changed since — the only kind of entry it may take back out.
479
+ *
480
+ * The key alone used to decide it. `Sentry`, `Linear`, `chrome-devtools` are
481
+ * the names each server's own README suggests, so a teammate who added their
482
+ * own — a self-hosted URL, their own args and env — lost it on the next
483
+ * `sync` that found the integration outside the stack, and on `remove`, from
484
+ * a file the team commits, with no backup and a message that blamed the
485
+ * stack. An entry that reads exactly as a release generated it holds nothing
486
+ * of anyone's; one that differs by a single argument is theirs, as it already
487
+ * was for `upgradeGeneratedServers`.
488
+ *
489
+ * Without `ide` — a legacy config, in whatever shape it was written then —
490
+ * the shapes written for any target count.
491
+ */
492
+ export function isGeneratedEntry(key: string, entry: unknown, ide?: IdeChoice): boolean {
493
+ const plugin = Object.values(PLUGINS).find((p) => p.mcpServerKey === key);
494
+ if (!plugin?.mcpConfig) return false;
495
+ const have = canonical(entry);
496
+ return (ide ? [ide] : ALL_TARGETS).some((target) => generatedShapes(plugin, target).has(have));
497
+ }
498
+
499
+ /**
500
+ * Whether `sync` or `remove` may take an integration's entry back out: the
501
+ * last compile gave the project that server (`given`, from the lock — see
502
+ * `priorIntegrations`) and the entry still reads as a release wrote it. With
503
+ * no lock to ask, the entry's shape alone decides.
504
+ */
505
+ export function isOurEntry(key: string, entry: unknown, ide: IdeChoice | undefined, given?: ReadonlySet<string> | null): boolean {
506
+ if (given && !given.has(key)) return false;
507
+ return isGeneratedEntry(key, entry, ide);
508
+ }
509
+
510
+ /** VS Code inputs among `ids` that no server left in the config reads. */
511
+ function unreadInputs(servers: unknown, ids: Iterable<string>): Set<string> {
512
+ const text = JSON.stringify(servers ?? {});
513
+ return new Set([...ids].filter((id) => !text.includes(`\${input:${id}}`)));
514
+ }
515
+
461
516
  /**
462
517
  * The text to write, or the same refusal an unparseable config gets when a
463
518
  * TOML config is laid out in a way that cannot be changed line by line —
@@ -686,23 +741,23 @@ export function willKeepSomethingAfterStrip(
686
741
  teamKeys: string[] = [],
687
742
  /** VS Code inputs those servers asked for. */
688
743
  teamInputs: string[] = [],
744
+ /** Integration servers the last compile gave the project; null with no lock. */
745
+ given?: ReadonlySet<string> | null,
689
746
  ): boolean {
690
747
  const containerKeys = ide
691
748
  ? [containerKeyFor(ide)]
692
749
  : ['mcp', 'servers', 'mcpServers', 'mcp_servers']
693
750
 
694
- const ourServerKeys = new Set([
695
- ...Object.values(PLUGINS)
696
- .filter((p) => p.mcpServerKey)
697
- .map((p) => p.mcpServerKey!),
698
- ...teamKeys,
699
- ]);
751
+ const team = new Set(teamKeys);
700
752
  const pluginInputIds = Object.values(PLUGINS).flatMap((p) => (p.mcpInputs ?? []).map((i) => i.id));
701
753
 
702
754
  for (const containerKey of containerKeys) {
703
755
  const servers = (parsed[containerKey] ?? {}) as Record<string, unknown>;
704
756
  for (const key of Object.keys(servers)) {
705
- if (ourServerKeys.has(key)) delete servers[key];
757
+ // A team server is written as its layer defines it, whatever was there,
758
+ // so it is ours by key. An integration's is ours only if we gave it to
759
+ // the project and it still reads as we wrote it (see `isOurEntry`).
760
+ if (team.has(key) || isOurEntry(key, servers[key], ide, given)) delete servers[key];
706
761
  }
707
762
  if (Object.keys(servers).length === 0) delete parsed[containerKey];
708
763
  else parsed[containerKey] = servers;
@@ -710,8 +765,12 @@ export function willKeepSomethingAfterStrip(
710
765
 
711
766
  if (Array.isArray(parsed.inputs)) {
712
767
  // Judged after the servers came out, so an input a user's own server still
713
- // reads survives the uninstall.
714
- const ourInputIds = new Set([...pluginInputIds, ...ownedUnusedInputs(parsed, teamInputs)]);
768
+ // reads survives the uninstall — an integration's included, now that the
769
+ // user's own server under its name stays.
770
+ const ourInputIds = new Set([
771
+ ...unreadInputs(parsed.servers, pluginInputIds),
772
+ ...ownedUnusedInputs(parsed, teamInputs),
773
+ ]);
715
774
  const kept = (parsed.inputs as McpInput[]).filter((i) => !ourInputIds.has(i.id));
716
775
  if (kept.length > 0) parsed.inputs = kept;
717
776
  else delete parsed.inputs;
@@ -726,8 +785,9 @@ export async function stripManagedMcpServers(
726
785
  createdByUs = false,
727
786
  teamKeys: string[] = [],
728
787
  teamInputs: string[] = [],
788
+ given?: ReadonlySet<string> | null,
729
789
  ): Promise<'deleted' | 'stripped' | 'absent' | 'unreadable'> {
730
- return stripConfigAt(projectRoot, getMcpConfigRelPath(ide), ide, createdByUs, teamKeys, teamInputs);
790
+ return stripConfigAt(projectRoot, getMcpConfigRelPath(ide), ide, createdByUs, teamKeys, teamInputs, given);
731
791
  }
732
792
 
733
793
  /**
@@ -756,11 +816,12 @@ export async function retireLegacyMcpConfig(
756
816
  createdByUs = false,
757
817
  teamKeys: string[] = [],
758
818
  teamInputs: string[] = [],
819
+ given?: ReadonlySet<string> | null,
759
820
  ): Promise<'deleted' | 'stripped' | 'absent' | 'unreadable'> {
760
821
  const rel = LEGACY_MCP_CONFIGS[ide];
761
822
  if (!rel) return 'absent';
762
823
  // No `ide`: the legacy file is in the shape it was written in, not today's.
763
- return stripConfigAt(projectRoot, rel, undefined, createdByUs, teamKeys, teamInputs);
824
+ return stripConfigAt(projectRoot, rel, undefined, createdByUs, teamKeys, teamInputs, given);
764
825
  }
765
826
 
766
827
  async function stripConfigAt(
@@ -770,6 +831,7 @@ async function stripConfigAt(
770
831
  createdByUs: boolean,
771
832
  teamKeys: string[],
772
833
  teamInputs: string[],
834
+ given: ReadonlySet<string> | null | undefined,
773
835
  ): Promise<'deleted' | 'stripped' | 'absent' | 'unreadable'> {
774
836
  const destPath = resolve(projectRoot, rel);
775
837
  if (!existsSync(destPath)) return 'absent';
@@ -793,7 +855,7 @@ async function stripConfigAt(
793
855
  // A copy to compare against: `willKeepSomethingAfterStrip` edits `parsed` in
794
856
  // place, so this is the only record of what the file said before.
795
857
  const untouched = JSON.stringify(parsed);
796
- const keepsSomething = willKeepSomethingAfterStrip(parsed, ide, teamKeys, teamInputs);
858
+ const keepsSomething = willKeepSomethingAfterStrip(parsed, ide, teamKeys, teamInputs, given);
797
859
 
798
860
  // Nothing of ours was in there, so there is nothing to do — and in particular
799
861
  // nothing to delete.
@@ -837,7 +899,10 @@ async function stripConfigAt(
837
899
  export interface RebuildOutcome {
838
900
  /** Integration servers moved to the current default. */
839
901
  upgraded: string[];
840
- /** Integration servers the stack no longer includes, deleted. */
902
+ /**
903
+ * Integration servers the stack no longer includes, deleted — only entries
904
+ * still as a release wrote them; a changed one under the same key is kept.
905
+ */
841
906
  removed: string[];
842
907
  /** Team servers written or rewritten to match their layer. */
843
908
  teamWritten: string[];
@@ -851,6 +916,8 @@ export async function rebuildMcpConfig(
851
916
  stack: StackConfig,
852
917
  repoInfo?: RepoInfo,
853
918
  team?: TeamMcpPlan,
919
+ /** Integration servers the last compile gave the project, from the lock; null with no lock. */
920
+ given?: ReadonlySet<string> | null,
854
921
  ): Promise<RebuildOutcome> {
855
922
  const destRelPath = getMcpConfigRelPath(ide);
856
923
  const destPath = resolve(projectRoot, destRelPath);
@@ -903,6 +970,11 @@ export async function rebuildMcpConfig(
903
970
  const removed: string[] = [];
904
971
  for (const key of Object.keys(existingServers)) {
905
972
  if (allPluginServerKeys.has(key) && !includedServers.has(key) && !teamOwned.has(key)) {
973
+ // Only one we gave the project, still exactly as we wrote it. One under
974
+ // the same name that differs is a person's — their own server, or ours
975
+ // tuned since — and deleting it lost their URL, args and env without a
976
+ // backup; one the stack never included is theirs however it reads.
977
+ if (!isOurEntry(key, existingServers[key], ide, given)) continue;
906
978
  delete existingServers[key];
907
979
  removed.push(key);
908
980
  }
@@ -933,9 +1005,12 @@ export async function rebuildMcpConfig(
933
1005
  }
934
1006
  }
935
1007
  }
936
- if (removedInputIds.size > 0) {
1008
+ // Not one a server still in the file reads: a person's own server kept
1009
+ // under an integration's name above may use the integration's input.
1010
+ const unread = unreadInputs(existingServers, removedInputIds);
1011
+ if (unread.size > 0) {
937
1012
  const existingInputs = (existing.inputs as McpInput[]) ?? [];
938
- const filteredInputs = existingInputs.filter((i) => !removedInputIds.has(i.id));
1013
+ const filteredInputs = existingInputs.filter((i) => !unread.has(i.id));
939
1014
  if (filteredInputs.length > 0) {
940
1015
  existing.inputs = filteredInputs;
941
1016
  } else {
package/src/cli/remove.ts CHANGED
@@ -10,7 +10,7 @@ import { LESSON_RULES } from './lessons-rules.js'
10
10
  import { stripManagedBlockFromFile, predictStripFile } from './managed-block.js'
11
11
  import { resolveManagedPaths, ownerOf, removeOwnedFiles } from './managed-paths.js'
12
12
  import { stripManagedMcpServers, getMcpConfigRelPath, willKeepSomethingAfterStrip, retireLegacyMcpConfig, LEGACY_MCP_CONFIGS } from './mcp.js'
13
- import { priorTeam } from './lock.js'
13
+ import { priorTeam, priorIntegrations } from './lock.js'
14
14
  import { IDE_ADAPTERS } from './adapters/index.js'
15
15
  import type { CliContext, IdeChoice } from './types.js'
16
16
  import { whyLeftAlone } from './unreadable-report.js'
@@ -111,7 +111,7 @@ async function previewCoOwned(
111
111
  const parsed = parseMcpConfigText(await readFile(abs, 'utf8'), p)
112
112
  // Captured before the predicate runs — it edits `parsed` in place.
113
113
  const untouched = JSON.stringify(parsed)
114
- keepsSomething = willKeepSomethingAfterStrip(parsed, ideFor.get(p), ...priorTeam(projectRoot))
114
+ keepsSomething = willKeepSomethingAfterStrip(parsed, ideFor.get(p), ...priorTeam(projectRoot), priorIntegrations(projectRoot))
115
115
  tookAnything = JSON.stringify(parsed) !== untouched
116
116
  } catch {
117
117
  // Unreadable JSON is left alone entirely, so it certainly survives.
@@ -395,6 +395,7 @@ export default async function remove({ args }: CliContext): Promise<void> {
395
395
  ide,
396
396
  createdConfigs.has(getMcpConfigRelPath(ide)),
397
397
  ...priorTeam(projectRoot),
398
+ priorIntegrations(projectRoot),
398
399
  )
399
400
  if (outcome === 'deleted') removed++
400
401
  else if (outcome === 'stripped') stripped++
@@ -403,7 +404,7 @@ export default async function remove({ args }: CliContext): Promise<void> {
403
404
  if (mcpParent !== projectRoot) parents.add(mcpParent)
404
405
  const legacyRel = LEGACY_MCP_CONFIGS[ide]
405
406
  if (legacyRel) {
406
- const legacy = await retireLegacyMcpConfig(projectRoot, ide, createdConfigs.has(legacyRel), ...priorTeam(projectRoot))
407
+ const legacy = await retireLegacyMcpConfig(projectRoot, ide, createdConfigs.has(legacyRel), ...priorTeam(projectRoot), priorIntegrations(projectRoot))
407
408
  if (legacy === 'deleted') removed++
408
409
  else if (legacy === 'stripped') stripped++
409
410
  else if (legacy === 'unreadable') unreadable.push(legacyRel)