@venizia/vulcan 0.3.8 → 0.3.9

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.
@@ -12,9 +12,23 @@ export interface INameField {
12
12
  optional?: boolean;
13
13
  /** A folder the user chose before, offered as the answer; never a name VULCAN made up. */
14
14
  previous?: string;
15
+ /** Folders that already exist and fit this field: a menu lists them, then offers a new one. */
16
+ choices?: string[];
17
+ /** The only valid answer is `previous` (one folder per side): a menu never asks, a flag still wins. */
18
+ fixed?: boolean;
15
19
  }
16
20
 
17
- export type TAsk = (opts: { question: string; previous?: string }) => string | null;
21
+ /** What a question carries: the text, the earlier choice, the existing folders, the check a menu runs while typing. */
22
+ export interface IAskOptions {
23
+ question: string;
24
+ previous?: string;
25
+ choices?: string[];
26
+ /** The message to show, or nothing when the text is fine. */
27
+ validate?: (value: string) => string | undefined;
28
+ }
29
+
30
+ /** `null` is end of input or a cancelled menu; a menu answers later, so the answer may be a promise. */
31
+ export type TAsk = (opts: IAskOptions) => string | null | Promise<string | null>;
18
32
 
19
33
  /** Reads at most one byte into `buffer` and returns how many were read; 0 is end of input. */
20
34
  export type TByteReader = (opts: { descriptor: number; buffer: Buffer }) => number;
@@ -14,7 +14,10 @@ import type {
14
14
  import { today, writeFile } from './files.ts';
15
15
  import { recordedPresetOf } from './lib-preset.ts';
16
16
  import { renderDockerignore } from './dockerignore.ts';
17
- import { askWithPrompt, findFolderClash, readFlag, resolveNames, SIDE_FIELDS } from './names.ts';
17
+ import { menusAvailable } from '../ui/index.ts';
18
+ import { askPresetSpec } from './preset-menu.ts';
19
+ import { ABORTED, confirmWrite, planLines } from './plan.ts';
20
+ import { askInTerminal, findFolderClash, readFlag, resolveNames, SIDE_FIELDS } from './names.ts';
18
21
  import { copyPresetFiles, locatePreset, parsePresetSpec } from './preset.ts';
19
22
  import { renderNext } from './next.ts';
20
23
  import { isInstallSkipped, runBun, runGitInit } from './process.ts';
@@ -34,7 +37,6 @@ import {
34
37
  const LAYER_FILES = [
35
38
  { path: 'AGENTS.md', template: 'AGENTS.md' },
36
39
  { path: '.agents/rules.md', template: 'rules.md' },
37
- { path: '.mcp.json', template: 'mcp.json' },
38
40
  { path: 'Makefile', template: 'Makefile' },
39
41
  ];
40
42
 
@@ -195,21 +197,28 @@ const runCreate = async (opts: {
195
197
  args: string[];
196
198
  scratch: string;
197
199
  }): Promise<number> => {
198
- const presetValue = readFlag({ args: opts.args, flag: CreateFlags.PRESET });
200
+ const flagged = readFlag({ args: opts.args, flag: CreateFlags.PRESET });
199
201
 
200
- if (presetValue === undefined) {
202
+ if (flagged === undefined && !menusAvailable()) {
203
+ return fail({ message: '--preset needs a value (a package name, or file:<path>)' });
204
+ }
205
+
206
+ // A new project has no config to list presets from: the official ones, or one typed.
207
+ const presetValue = flagged ?? (await askPresetSpec({ recorded: [] }))?.trim();
208
+
209
+ if (presetValue === undefined || presetValue === '') {
201
210
  return fail({ message: '--preset needs a value (a package name, or file:<path>)' });
202
211
  }
203
212
 
204
213
  const spec = parsePresetSpec({ value: presetValue, cwd: opts.cwd });
205
214
  const interactive = process.stdin.isTTY === true;
206
- const first = resolveNames({
215
+ const first = await resolveNames({
207
216
  fields: [
208
217
  { key: 'project', flag: CreateFlags.PROJECT, question: 'Project name (the monorepo folder)' },
209
218
  ],
210
219
  args: opts.args,
211
220
  interactive,
212
- ask: askWithPrompt,
221
+ ask: askInTerminal,
213
222
  });
214
223
 
215
224
  if (!first.ok) {
@@ -237,11 +246,11 @@ const runCreate = async (opts: {
237
246
  if (isNpm) {
238
247
  // Without a terminal nothing is asked, so a missing flag is refused before the network is used.
239
248
  if (!interactive) {
240
- const early = resolveNames({
249
+ const early = await resolveNames({
241
250
  fields: appFields({}),
242
251
  args: opts.args,
243
252
  interactive,
244
- ask: askWithPrompt,
253
+ ask: askInTerminal,
245
254
  });
246
255
 
247
256
  if (!early.ok) {
@@ -273,11 +282,11 @@ const runCreate = async (opts: {
273
282
  located = result.located;
274
283
  }
275
284
 
276
- const rest = resolveNames({
285
+ const rest = await resolveNames({
277
286
  fields: appFields({ side: located.preset.side }),
278
287
  args: opts.args,
279
288
  interactive,
280
- ask: askWithPrompt,
289
+ ask: askInTerminal,
281
290
  });
282
291
 
283
292
  if (!rest.ok) {
@@ -311,6 +320,22 @@ const runCreate = async (opts: {
311
320
  process.stderr.write(`${warning}\n`);
312
321
  }
313
322
 
323
+ const confirmed = await confirmWrite({
324
+ title: `Create ${project}`,
325
+ lines: planLines({
326
+ rows: [
327
+ ['project', project],
328
+ ['preset', `${located.packageName} ${located.packageVersion}`],
329
+ [`${side} app`, `${folder}/${app}`],
330
+ ['shared', shared === '' ? '(none)' : shared],
331
+ ],
332
+ }),
333
+ });
334
+
335
+ if (!confirmed) {
336
+ return fail({ message: ABORTED });
337
+ }
338
+
314
339
  writeMonorepo({ root, project, spec, presetValue, located, folder, app, shared });
315
340
 
316
341
  for (const step of [
@@ -1,7 +1,15 @@
1
1
  import { readSync } from 'node:fs';
2
2
 
3
+ import { menusAvailable, promptSelect, promptText } from '../ui/index.ts';
3
4
  import { AppSides, CreateConstants, CreateFlags } from './common/index.ts';
4
- import type { INameField, TAppSide, TAsk, TByteReader, TNamesResult } from './common/index.ts';
5
+ import type {
6
+ IAskOptions,
7
+ INameField,
8
+ TAppSide,
9
+ TAsk,
10
+ TByteReader,
11
+ TNamesResult,
12
+ } from './common/index.ts';
5
13
 
6
14
  /** The folder holding every app of one side; `add` offers the one the config already holds. */
7
15
  export const SIDE_FIELDS: Record<TAppSide, INameField> = {
@@ -26,6 +34,12 @@ export const readFlag = (opts: { args: string[]; flag: string }): string | undef
26
34
  const isValidName = (opts: { name: string }): boolean =>
27
35
  CreateConstants.NAME_PATTERN.test(opts.name);
28
36
 
37
+ /** The message a menu shows under a typed name that is not one; nothing when it is fine. */
38
+ export const nameProblem = (opts: { name: string }): string | undefined =>
39
+ isValidName({ name: opts.name })
40
+ ? undefined
41
+ : `'${opts.name}' is not a name: lowercase letters, digits and '-', starting with a letter or digit`;
42
+
29
43
  const NEWLINE = 0x0a;
30
44
  const CARRIAGE_RETURN = 0x0d;
31
45
  const RETRY_PAUSE_MILLISECONDS = 5;
@@ -91,7 +105,7 @@ export const readLine = (opts: {
91
105
  };
92
106
 
93
107
  /** The shown default is the user's own earlier choice, never one VULCAN made up. */
94
- export const askWithPrompt: TAsk = opts => {
108
+ export const askWithPrompt = (opts: IAskOptions): string | null => {
95
109
  process.stdout.write(
96
110
  opts.previous === undefined
97
111
  ? `? ${opts.question} > `
@@ -101,9 +115,55 @@ export const askWithPrompt: TAsk = opts => {
101
115
  return readLine({ descriptor: CreateConstants.STDIN_DESCRIPTOR });
102
116
  };
103
117
 
104
- const askUntilValid = (opts: { field: INameField; ask: TAsk }): string | null => {
118
+ const NEW_FOLDER = ':new-folder';
119
+
120
+ /** A menu, not a line: existing folders are picked, a new name is typed with its default shown. */
121
+ const askWithMenus: TAsk = async opts => {
122
+ if (opts.choices !== undefined && opts.choices.length > 0) {
123
+ const picked = await promptSelect({
124
+ message: opts.question,
125
+ choices: [
126
+ ...opts.choices.map(value => ({ value, label: value })),
127
+ { value: NEW_FOLDER, label: 'New folder...' },
128
+ ],
129
+ initial: opts.previous,
130
+ });
131
+
132
+ if (picked !== NEW_FOLDER) {
133
+ return picked;
134
+ }
135
+ }
136
+
137
+ return promptText({
138
+ message: opts.question,
139
+ defaultValue: opts.previous,
140
+ validate: opts.validate,
141
+ });
142
+ };
143
+
144
+ /** Menus in a terminal that can draw them, the plain question everywhere else. */
145
+ export const askInTerminal: TAsk = opts =>
146
+ menusAvailable() ? askWithMenus(opts) : askWithPrompt(opts);
147
+
148
+ const askUntilValid = async (opts: { field: INameField; ask: TAsk }): Promise<string | null> => {
149
+ const { field } = opts;
150
+ const validate = (value: string): string | undefined => {
151
+ const name = value.trim() === '' ? (field.previous ?? '') : value.trim();
152
+
153
+ if (name === '' && field.optional === true) {
154
+ return undefined;
155
+ }
156
+
157
+ return nameProblem({ name });
158
+ };
159
+
105
160
  for (;;) {
106
- const answer = opts.ask({ question: opts.field.question, previous: opts.field.previous });
161
+ const answer = await opts.ask({
162
+ question: field.question,
163
+ previous: field.previous,
164
+ choices: field.choices,
165
+ validate,
166
+ });
107
167
 
108
168
  if (answer === null) {
109
169
  return null;
@@ -126,12 +186,12 @@ const askUntilValid = (opts: { field: INameField; ask: TAsk }): string | null =>
126
186
  };
127
187
 
128
188
  /** Every name from its flag; a missing one is asked in a TTY and an error otherwise. */
129
- export const resolveNames = (opts: {
189
+ export const resolveNames = async (opts: {
130
190
  fields: INameField[];
131
191
  args: string[];
132
192
  interactive: boolean;
133
193
  ask: TAsk;
134
- }): TNamesResult => {
194
+ }): Promise<TNamesResult> => {
135
195
  const names: Record<string, string> = {};
136
196
 
137
197
  for (const field of opts.fields) {
@@ -166,7 +226,12 @@ export const resolveNames = (opts: {
166
226
  };
167
227
  }
168
228
 
169
- const answer = askUntilValid({ field, ask: opts.ask });
229
+ if (field.fixed === true && field.previous !== undefined) {
230
+ names[field.key] = field.previous;
231
+ continue;
232
+ }
233
+
234
+ const answer = await askUntilValid({ field, ask: opts.ask });
170
235
 
171
236
  if (answer === null) {
172
237
  return { ok: false, error: 'aborted' };
@@ -0,0 +1,17 @@
1
+ import { menusAvailable, promptPlan } from '../ui/index.ts';
2
+
3
+ /** `label value` lines with the values in one column. */
4
+ export const planLines = (opts: { rows: [label: string, value: string][] }): string[] => {
5
+ const width = Math.max(...opts.rows.map(([label]) => label.length));
6
+
7
+ return opts.rows.map(([label, value]) => `${label.padEnd(width)} ${value}`);
8
+ };
9
+
10
+ /**
11
+ * Before anything is written, a terminal that can draw menus shows what will be written and asks.
12
+ * Without one nothing is asked: flags and pipes keep writing as they always did.
13
+ */
14
+ export const confirmWrite = async (opts: { title: string; lines: string[] }): Promise<boolean> =>
15
+ menusAvailable() ? promptPlan(opts) : true;
16
+
17
+ export const ABORTED = 'aborted: nothing was written';
@@ -0,0 +1,45 @@
1
+ import { OFFICIAL_PRESETS, officialIdOf } from '@venizia/vulcan-atlas';
2
+ import { promptSelect, promptText } from '../ui/index.ts';
3
+
4
+ const ANOTHER_PRESET = ':another-preset';
5
+
6
+ /** A preset a project recorded: what `--preset` takes back, the side it builds, what it is. */
7
+ export interface IKnownPreset {
8
+ spec: string;
9
+ side: string;
10
+ summary: string;
11
+ }
12
+
13
+ /**
14
+ * What a menu offers for `--preset`: the presets the project recorded, then the official ones it has
15
+ * not used yet (the one list atlas answers `presets` from), then a text input for any other package
16
+ * or `file:` path. null when the user cancelled.
17
+ */
18
+ export const askPresetSpec = async (opts: { recorded: IKnownPreset[] }): Promise<string | null> => {
19
+ const used = new Set(opts.recorded.map(entry => officialIdOf({ spec: entry.spec })));
20
+ const picked = await promptSelect({
21
+ message: 'Which preset?',
22
+ choices: [
23
+ ...opts.recorded.map(entry => ({
24
+ value: entry.spec,
25
+ label: entry.spec,
26
+ hint: `${entry.side}: ${entry.summary}`,
27
+ })),
28
+ ...OFFICIAL_PRESETS.filter(entry => !used.has(entry.id)).map(entry => ({
29
+ value: entry.id,
30
+ label: entry.id,
31
+ hint: `official, ${entry.side} (app or lib)`,
32
+ })),
33
+ { value: ANOTHER_PRESET, label: 'Another preset...', hint: 'a package name or file:<path>' },
34
+ ],
35
+ });
36
+
37
+ if (picked !== ANOTHER_PRESET) {
38
+ return picked;
39
+ }
40
+
41
+ return promptText({
42
+ message: 'Preset (a package name, or file:<path>)',
43
+ validate: value => (value.trim() === '' ? 'a package name, or file:<path>' : undefined),
44
+ });
45
+ };
@@ -1,7 +1,14 @@
1
1
  import { relative, resolve } from 'node:path';
2
2
  import { coversFolder } from '../init/index.ts';
3
3
  import { CreateConstants } from './common/index.ts';
4
- import type { IApp, IAppsBlock, IPreset, IPresetSpec, IRecordedPreset } from './common/index.ts';
4
+ import type {
5
+ IApp,
6
+ IAppsBlock,
7
+ IPreset,
8
+ IPresetSpec,
9
+ IRecordedPreset,
10
+ TAppSide,
11
+ } from './common/index.ts';
5
12
 
6
13
  const ENV_PORT = /^[A-Z0-9_]*PORT=(\d+)\s*$/m;
7
14
 
@@ -202,6 +209,37 @@ export const renderLibManifest = (opts: {
202
209
  });
203
210
  };
204
211
 
212
+ /** The atlas lookups a package of one kind depends on: what a summary page cannot hold. */
213
+ const ATLAS_LOOKUPS: Record<TAppSide | 'lib', [string, string][]> = {
214
+ backend: [
215
+ ['How a route and its controller are written', '`search` "controller routes", then `get`'],
216
+ [
217
+ 'How a service, a repository and a datasource fit together',
218
+ '`search` "service repository datasource"',
219
+ ],
220
+ ],
221
+ frontend: [
222
+ ['How a page or a resource is added', '`search` "page resource", then `get`'],
223
+ ['How the app reads data from its backend', '`search` "data provider"'],
224
+ ],
225
+ lib: [['How a shared package exposes its API', '`search` "shared package exports", then `get`']],
226
+ };
227
+
228
+ /** The note and the table that turn a package page into a pointer at atlas, for its kind. */
229
+ const renderAtlasLookups = (opts: { kind: TAppSide | 'lib' }): string[] => [
230
+ '> This page is a summary, not a spec: it says what the package is. How code is written here lives',
231
+ '> in atlas; look it up before you explain or write code.',
232
+ '',
233
+ '## How things are done here',
234
+ '',
235
+ '| You need | Ask atlas |',
236
+ '|---|---|',
237
+ ...ATLAS_LOOKUPS[opts.kind].map(([need, call]) => `| ${need} | ${call} |`),
238
+ '| The signature and import path of an export, before you import it | `symbol` with its name |',
239
+ '| A new app or package | `presets`, then the `vulcan add` command it returns |',
240
+ '',
241
+ ];
242
+
205
243
  export const renderLibConcept = (opts: {
206
244
  name: string;
207
245
  path: string;
@@ -221,6 +259,7 @@ export const renderLibConcept = (opts: {
221
259
  '',
222
260
  `The shared package at \`${opts.path}\`, created from the ${opts.presetPackage} preset (lib kind). ${oneLine({ text: opts.summary })}`,
223
261
  '',
262
+ ...renderAtlasLookups({ kind: 'lib' }),
224
263
  ].join('\n');
225
264
 
226
265
  export const renderAppsBlock = (opts: { block: IAppsBlock }): string =>
@@ -445,6 +484,7 @@ export const renderAppConcept = (opts: {
445
484
  '',
446
485
  `The ${opts.app.side} app at \`${opts.app.folder}/${opts.app.name}\`, created from the ${opts.presetPackage} preset. ${oneLine({ text: opts.summary })}`,
447
486
  '',
487
+ ...renderAtlasLookups({ kind: opts.app.side }),
448
488
  ].join('\n');
449
489
 
450
490
  export const renderLogEntry = (opts: { date: string; text: string }): string =>
@@ -23,8 +23,14 @@ import {
23
23
  projectNameOf,
24
24
  renderManifest,
25
25
  } from '../manifest/index.ts';
26
- import { readLocalChoice, resolveAgentsQuietly } from '../agents/index.ts';
27
26
  import {
27
+ AgentScopes,
28
+ readAgentTable,
29
+ readLocalChoice,
30
+ resolveAgentsQuietly,
31
+ } from '../agents/index.ts';
32
+ import {
33
+ isTracked,
28
34
  mergedAtlasBlock,
29
35
  planManifest,
30
36
  planPrune,
@@ -620,23 +626,33 @@ const mcpWarning = (opts: { file: string; message: string }): IViolation =>
620
626
  createViolation({ check: DoctorChecks.MCP, file: opts.file, message: opts.message });
621
627
 
622
628
  /**
623
- * The atlas server is registered the one way every project does: the tracked `.mcp.json` holds an
624
- * `atlas` entry that runs the project's own atlas (`--root .`), and the managed Claude settings
625
- * enable `atlas` by that name. A server under another name, or one that serves another folder, is
626
- * never enabled automatically or serves the wrong knowledge. Warnings, not violations.
629
+ * The atlas server is registered the one way every project does: the root `.mcp.json` (a per-machine
630
+ * file `sync` writes for the agents that read it) holds an `atlas` entry that runs the project's own
631
+ * atlas (`--root .`), and the managed Claude settings enable `atlas` by that name. A server under
632
+ * another name, or one that serves another folder, is never enabled automatically or serves the wrong
633
+ * knowledge. A `.mcp.json` git still tracks is told how to hand over to `sync`. Warnings, not violations.
627
634
  */
628
635
  export const checkMcpAtlas = (opts: ICheckContext): IViolation[] => {
629
636
  const warnings: IViolation[] = [];
630
637
  const file = join(opts.root, MCP_FILE);
638
+ const chosen = resolveAgentsQuietly({ root: opts.root, configAgents: opts.config.agents });
639
+ const readsMcpFile = readAgentTable().some(
640
+ entry => chosen.includes(entry.id) && entry.mcp.scope === AgentScopes.SHARED,
641
+ );
642
+
643
+ // The root `.mcp.json` is a per-machine file of the agents that read it; a missing one is the
644
+ // `adapters` check's (not synced yet), so only an existing file is looked at.
645
+ if (readsMcpFile && existsSync(file)) {
646
+ if (isTracked({ root: opts.root, path: MCP_FILE })) {
647
+ warnings.push(
648
+ mcpWarning({
649
+ file: MCP_FILE,
650
+ message:
651
+ 'tracked by git; VULCAN now writes it per machine. Run `git rm --cached .mcp.json` and let sync manage it.',
652
+ }),
653
+ );
654
+ }
631
655
 
632
- if (!existsSync(file)) {
633
- warnings.push(
634
- mcpWarning({
635
- file: MCP_FILE,
636
- message: `missing: atlas is not registered for Claude Code, omp and Copilot CLI - add ${MCP_SERVER_HINT} under mcpServers`,
637
- }),
638
- );
639
- } else {
640
656
  const parsed = readJsonObject({ file });
641
657
 
642
658
  if (parsed === undefined) {
@@ -7,32 +7,7 @@ import { InitConstants, InitStatuses } from './common/index.ts';
7
7
  import { renderDockerignore } from '../create/dockerignore.ts';
8
8
  import type { IInitEntry, IScaffoldFile } from './common/index.ts';
9
9
 
10
- /**
11
- * Whether a `.mcp.json` already serves atlas: a server named `atlas`, or any server whose arguments run
12
- * `atlas mcp` under another name, as separate arguments or inside a `sh -c` string. A file that is not JSON falls back to looking for the name.
13
- */
14
- export const runsAtlas = (opts: { text: string }): boolean => {
15
- try {
16
- const parsed: { mcpServers?: Record<string, { args?: unknown }> } = JSON.parse(opts.text);
17
- const servers = parsed.mcpServers ?? {};
18
-
19
- return (
20
- 'atlas' in servers ||
21
- Object.values(servers).some(server => {
22
- const args = Array.isArray(server.args)
23
- ? server.args.flatMap(arg => String(arg).split(/\s+/))
24
- : [];
25
- const atlas = args.indexOf('atlas');
26
-
27
- return atlas !== -1 && args[atlas + 1] === 'mcp';
28
- })
29
- );
30
- } catch {
31
- return opts.text.includes('"atlas"');
32
- }
33
- };
34
-
35
- /** The entry for a `.mcp.json` that exists already: atlas serves the knowledge bundle alone, and the wiki when there is one. */
10
+ /** The atlas entry of the root `.mcp.json`, as `sync` writes it and `doctor` shows it. */
36
11
  export const MCP_SERVER_HINT =
37
12
  '"atlas": { "command": "bun", "args": ["x", "--no-install", "vulcan", "x", "atlas", "mcp", "--root", "."] }';
38
13
 
@@ -41,7 +16,6 @@ const SCAFFOLD_FILES: IScaffoldFile[] = [
41
16
  { path: 'AGENTS.md', template: 'AGENTS.md' },
42
17
  { path: '.agents/rules.md', template: 'rules.md' },
43
18
  { path: '.agents/knowledge/index.md', template: 'knowledge-index.md' },
44
- { path: '.mcp.json', template: 'mcp.json' },
45
19
  ];
46
20
 
47
21
  /** The lint configs of a single-package project. A workspaces project keeps them in each app. */
@@ -208,20 +182,6 @@ export const scaffoldProject = (opts: {
208
182
  });
209
183
  }
210
184
 
211
- // A `.mcp.json` that was already there is the project's: it gets the atlas entry as a hint, never an edit.
212
- if (
213
- !entries.some(entry => entry.subject === '.mcp.json' && entry.status === InitStatuses.CREATED)
214
- ) {
215
- const servers = readFileSync(join(root, '.mcp.json'), 'utf8');
216
-
217
- if (!runsAtlas({ text: servers })) {
218
- entries.push({
219
- status: InitStatuses.ADD,
220
- subject: `.mcp.json: the atlas server, for the knowledge bundle (and the wiki, when there is one; --root pins the project): ${MCP_SERVER_HINT}`,
221
- });
222
- }
223
- }
224
-
225
185
  const gitignore = join(root, '.gitignore');
226
186
  const existing = existsSync(gitignore) ? readFileSync(gitignore, 'utf8') : '';
227
187
  const lines = existing.split('\n');
@@ -1,9 +1,11 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import {
4
+ AgentConstants,
4
5
  AgentRenderers,
5
6
  AgentScopes,
6
7
  atlasServerEntry,
8
+ canonicalAtlasEntry,
7
9
  mergeCodexToml,
8
10
  mergeMcpServers,
9
11
  readAgentTable,
@@ -15,7 +17,7 @@ import type { ISyncAction } from './common/index.ts';
15
17
  const NO_CHANGE = (): void => {};
16
18
 
17
19
  /** A file git tracks cannot be hidden by an exclude entry, and a per-developer edit would show as a diff. */
18
- const isTracked = (opts: { root: string; path: string }): boolean => {
20
+ export const isTracked = (opts: { root: string; path: string }): boolean => {
19
21
  try {
20
22
  return (
21
23
  Bun.spawnSync(['git', 'ls-files', '--error-unmatch', opts.path], {
@@ -99,11 +101,63 @@ const planAgentMcp = (opts: { root: string; entry: TAgentEntry }): ISyncAction[]
99
101
  ];
100
102
  };
101
103
 
102
- /** The MCP files of every chosen agent, in table order. */
103
- export const planAgentFiles = (opts: { root: string; agents: string[] }): ISyncAction[] =>
104
- readAgentTable()
104
+ /**
105
+ * The root `.mcp.json` the chosen agents of the shared scope read: the canonical atlas entry, merged
106
+ * into what is there. A file git tracks belongs to the project, not to this machine: it is never
107
+ * rewritten (the doctor says how to hand it over).
108
+ */
109
+ const planSharedMcp = (opts: { root: string }): ISyncAction[] => {
110
+ const path = join(opts.root, AgentConstants.SHARED_MCP_FILE);
111
+ const text = existsSync(path) ? readFileSync(path, 'utf8') : undefined;
112
+ const merged = mergeMcpServers({ text, key: 'mcpServers', entry: canonicalAtlasEntry() });
113
+
114
+ if (!merged.ok) {
115
+ return [
116
+ {
117
+ path,
118
+ status: SyncStatuses.SKIPPED,
119
+ note: `${merged.reason} - left untouched; fix it, then re-run sync`,
120
+ apply: NO_CHANGE,
121
+ },
122
+ ];
123
+ }
124
+
125
+ if (
126
+ !merged.changed ||
127
+ (text !== undefined && isTracked({ root: opts.root, path: AgentConstants.SHARED_MCP_FILE }))
128
+ ) {
129
+ return [{ path, status: SyncStatuses.UNCHANGED, apply: NO_CHANGE }];
130
+ }
131
+
132
+ return [
133
+ {
134
+ path,
135
+ status: text === undefined ? SyncStatuses.CREATED : SyncStatuses.REPLACED,
136
+ apply: () => writeFileSync(path, merged.text),
137
+ },
138
+ ];
139
+ };
140
+
141
+ /** The MCP files of every chosen agent, in table order; the shared `.mcp.json` once, at its first reader. */
142
+ export const planAgentFiles = (opts: { root: string; agents: string[] }): ISyncAction[] => {
143
+ let sharedPlanned = false;
144
+
145
+ return readAgentTable()
105
146
  .filter(entry => opts.agents.includes(entry.id))
106
- .flatMap(entry => planAgentMcp({ root: opts.root, entry }));
147
+ .flatMap(entry => {
148
+ if (entry.mcp.scope === AgentScopes.PROJECT) {
149
+ return planAgentMcp({ root: opts.root, entry });
150
+ }
151
+
152
+ if (sharedPlanned) {
153
+ return [];
154
+ }
155
+
156
+ sharedPlanned = true;
157
+
158
+ return planSharedMcp({ root: opts.root });
159
+ });
160
+ };
107
161
 
108
162
  /** One line per note of a chosen agent (a trust prompt only the user can answer). */
109
163
  export const agentNotes = (opts: { agents: string[] }): { agent: string; note: string }[] =>
@@ -18,6 +18,7 @@ import {
18
18
  removeMcpEntry,
19
19
  } from '../agents/index.ts';
20
20
  import type { TAgentEntry } from '../agents/index.ts';
21
+ import { isTracked } from './agent-files.ts';
21
22
  import { BASE_DIRECTORY, stableBaseDirectoryOf } from '../common/index.ts';
22
23
  import { SyncConstants, SyncStatuses } from './common/index.ts';
23
24
  import type { ISyncAction, TSettings } from './common/index.ts';
@@ -80,6 +81,51 @@ const removeFile = (opts: { path: string; note?: string; parent?: string }): ISy
80
81
  },
81
82
  });
82
83
 
84
+ /**
85
+ * The root `.mcp.json`, once no remaining agent reads it: sync's own atlas entry is taken out (the file
86
+ * goes when nothing else is in it). A file git tracks is the project's, and an entry the user changed
87
+ * is theirs: both are left, and the line says so.
88
+ */
89
+ const planSharedMcpRemoval = (opts: { root: string }): ISyncAction[] => {
90
+ const path = join(opts.root, AgentConstants.SHARED_MCP_FILE);
91
+
92
+ if (!existsSync(path)) {
93
+ return [];
94
+ }
95
+
96
+ const removed = removeMcpEntry({ text: readFileSync(path, 'utf8'), key: 'mcpServers' });
97
+
98
+ if (!removed.ok) {
99
+ return [{ path, status: SyncStatuses.SKIPPED, note: removed.reason, apply: NO_CHANGE }];
100
+ }
101
+
102
+ if (removed.outcome === 'absent') {
103
+ return [];
104
+ }
105
+
106
+ if (isTracked({ root: opts.root, path: AgentConstants.SHARED_MCP_FILE })) {
107
+ return [
108
+ {
109
+ path,
110
+ status: SyncStatuses.SKIPPED,
111
+ note: 'tracked by git - left alone',
112
+ apply: NO_CHANGE,
113
+ },
114
+ ];
115
+ }
116
+
117
+ return removed.text === undefined
118
+ ? [removeFile({ path })]
119
+ : [
120
+ {
121
+ path,
122
+ status: SyncStatuses.REPLACED,
123
+ note: 'the atlas entry taken out',
124
+ apply: () => writeFileSync(path, removed.text ?? ''),
125
+ },
126
+ ];
127
+ };
128
+
83
129
  const planMcpRemoval = (opts: { root: string; entry: TAgentEntry }): ISyncAction[] => {
84
130
  if (opts.entry.mcp.scope !== AgentScopes.PROJECT) {
85
131
  return [];
@@ -219,6 +265,10 @@ export const planAgentRemoval = (opts: {
219
265
  );
220
266
  const cleaned = new Set<string>();
221
267
  const actions: ISyncAction[] = [];
268
+ const stillReadsShared = table.some(
269
+ entry => opts.remaining.includes(entry.id) && entry.mcp.scope === AgentScopes.SHARED,
270
+ );
271
+ let sharedDone = false;
222
272
 
223
273
  for (const entry of table.filter(item => opts.removed.includes(item.id))) {
224
274
  if (entry.id === AgentConstants.DEFAULT_AGENT) {
@@ -227,6 +277,11 @@ export const planAgentRemoval = (opts: {
227
277
 
228
278
  actions.push(...planMcpRemoval({ root: opts.root, entry }));
229
279
 
280
+ if (entry.mcp.scope === AgentScopes.SHARED && !stillReadsShared && !sharedDone) {
281
+ sharedDone = true;
282
+ actions.push(...planSharedMcpRemoval({ root: opts.root }));
283
+ }
284
+
230
285
  if (
231
286
  entry.skills.dir !== CLAUDE_SKILLS &&
232
287
  !kept.has(entry.skills.dir) &&