barndog 0.2.0 → 0.2.2

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 (112) hide show
  1. package/README.md +45 -24
  2. package/dist/cli.js +27 -1
  3. package/dist/commands/add.js +1 -0
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/asset-install.js +1 -0
  6. package/dist/commands/asset-list.js +12 -3
  7. package/dist/commands/availability.js +25 -8
  8. package/dist/commands/capabilities.js +8 -2
  9. package/dist/commands/collaboration.js +22 -2
  10. package/dist/commands/harnesses.js +104 -0
  11. package/dist/commands/mcp-env.js +167 -0
  12. package/dist/commands/mcp.js +4 -2
  13. package/dist/commands/sets.js +13 -2
  14. package/dist/commands/status.js +2 -1
  15. package/dist/commands/sync.js +2 -1
  16. package/dist/commands/uninstall.js +62 -0
  17. package/dist/commands/workspace.js +43 -5
  18. package/dist/config/paths.js +21 -0
  19. package/dist/config/settings.js +5 -3
  20. package/dist/config/state.js +18 -6
  21. package/dist/entry/update-check.js +15 -0
  22. package/dist/features/adoption/adopt.js +235 -0
  23. package/dist/features/adoption/copies.js +29 -0
  24. package/dist/features/adoption/originals.js +116 -0
  25. package/dist/features/adoption/record.js +120 -0
  26. package/dist/features/adoption/restore.js +28 -0
  27. package/dist/features/adoption/scan.js +482 -0
  28. package/dist/features/adoption/undo.js +42 -0
  29. package/dist/features/asset-kinds/index.js +9 -0
  30. package/dist/features/auth/credentials.js +7 -14
  31. package/dist/features/auth/session.js +26 -5
  32. package/dist/features/auth/transport.js +3 -2
  33. package/dist/features/collaboration/workspace-git.js +13 -7
  34. package/dist/features/collaboration/workspace-github.js +2 -1
  35. package/dist/features/collaboration/workspace-store.js +25 -4
  36. package/dist/features/collaboration/workspace.js +22 -2
  37. package/dist/features/doctor/index.js +46 -7
  38. package/dist/features/environment/events.js +8 -1
  39. package/dist/features/environment/harnesses.js +36 -0
  40. package/dist/features/environment/kept-values.js +68 -0
  41. package/dist/features/environment/moves.js +187 -0
  42. package/dist/features/environment/names.js +10 -6
  43. package/dist/features/environment/operations.js +7 -7
  44. package/dist/features/environment/stage.js +25 -1
  45. package/dist/features/environment/sync.js +17 -6
  46. package/dist/features/environment/writes.js +55 -8
  47. package/dist/features/hooks/compatibility.js +11 -5
  48. package/dist/features/hooks/divergence.js +30 -9
  49. package/dist/features/hooks/test.js +25 -25
  50. package/dist/features/imports/discover.js +1 -1
  51. package/dist/features/imports/local.js +15 -2
  52. package/dist/features/imports/remote.js +2 -1
  53. package/dist/features/inventory/index.js +57 -3
  54. package/dist/features/inventory/show.js +74 -0
  55. package/dist/features/mcps/import.js +95 -21
  56. package/dist/features/mcps/index.js +24 -9
  57. package/dist/features/mcps/values.js +121 -0
  58. package/dist/features/migration/migrate.js +15 -0
  59. package/dist/features/migration/move.js +105 -25
  60. package/dist/features/migration/promote.js +2 -0
  61. package/dist/features/native/adapters.js +20 -7
  62. package/dist/features/native/configuration.js +8 -4
  63. package/dist/features/native/hook-shell.js +11 -0
  64. package/dist/features/native/secret-values.js +74 -0
  65. package/dist/features/secrets/index.js +142 -0
  66. package/dist/features/uninstall/index.js +126 -0
  67. package/dist/features/uninstall/leave.js +152 -0
  68. package/dist/features/uninstall/survey.js +103 -0
  69. package/dist/features/update-check/index.js +108 -0
  70. package/dist/features/workspace/format.js +19 -10
  71. package/dist/features/workspace/git.js +11 -4
  72. package/dist/features/workspace/overlay.js +23 -36
  73. package/dist/features/workspace/packages.js +16 -3
  74. package/dist/features/workspace/publish.js +1 -1
  75. package/dist/features/workspace/repo-source.js +4 -3
  76. package/dist/features/workspace/setup.js +12 -3
  77. package/dist/features/workspace/snapshot.js +7 -1
  78. package/dist/harnesses/claude.js +2 -2
  79. package/dist/harnesses/codex.js +54 -20
  80. package/dist/harnesses/cursor.js +2 -2
  81. package/dist/harnesses/formats.js +12 -5
  82. package/dist/harnesses/opencode.js +3 -6
  83. package/dist/harnesses/read-renamed-variables.js +141 -0
  84. package/dist/harnesses/renamed-variables.js +99 -0
  85. package/dist/platform.js +51 -12
  86. package/dist/program.js +68 -8
  87. package/dist/shared/files.js +35 -0
  88. package/dist/shared/lock.js +87 -23
  89. package/dist/shared/patterns.js +8 -0
  90. package/dist/shared/shell.js +0 -2
  91. package/dist/ui/add-hook.js +8 -2
  92. package/dist/ui/add-mcp.js +82 -13
  93. package/dist/ui/add-skills.js +7 -5
  94. package/dist/ui/adopt.js +202 -0
  95. package/dist/ui/assets.js +5 -3
  96. package/dist/ui/auth.js +2 -1
  97. package/dist/ui/clash.js +2 -3
  98. package/dist/ui/connection.js +9 -2
  99. package/dist/ui/harness-picker.js +23 -0
  100. package/dist/ui/mcp.js +89 -23
  101. package/dist/ui/move.js +49 -2
  102. package/dist/ui/onboarding.js +40 -27
  103. package/dist/ui/output.js +35 -8
  104. package/dist/ui/package-details.js +34 -0
  105. package/dist/ui/scope-install.js +4 -1
  106. package/dist/ui/secret-input.js +28 -0
  107. package/dist/ui/selection.js +3 -1
  108. package/dist/ui/uninstall.js +174 -0
  109. package/dist/ui/update.js +10 -0
  110. package/dist/version.js +2 -2
  111. package/package.json +1 -1
  112. package/dist/entry/mcp-launch.js +0 -71
@@ -14,7 +14,7 @@ import { acceptedCommit, gitRepoSource, recordFetch, trackingRef, } from "../wor
14
14
  import { metadata as packageMetadataFor, packageKindOf, assetKinds, assetNotFound, } from "../asset-kinds/index.js";
15
15
  import { matchesOrigin } from "../server/origin.js";
16
16
  import { markResolved } from "./workspace.js";
17
- import { applyFiles, decodeFiles, encodeFiles, findGit, locked, save, readWorkingCopy, } from "./workspace-store.js";
17
+ import { applyFiles, decodeFiles, encodeFiles, findGit, NoWorkingCopyError, locked, save, readWorkingCopy, } from "./workspace-store.js";
18
18
  import { defined, only } from "../../shared/lookup.js";
19
19
  import { NAME, splitOrigin } from "../../shared/patterns.js";
20
20
  import { barndogPaths } from "../../config/paths.js";
@@ -22,10 +22,11 @@ import { barndogPaths } from "../../config/paths.js";
22
22
  const BRANCH_RANDOM_BYTES = 3;
23
23
  async function latest(workspace, runtime) {
24
24
  const model = await gitRepoSource(workspace, runtime).model();
25
- return {
26
- model,
27
- commit: defined(await acceptedCommit(workspace.workspaceId, runtime), "This Git workspace hasn't been fetched yet"),
28
- };
25
+ const commit = await acceptedCommit(workspace.workspaceId, runtime);
26
+ if (!commit) {
27
+ throw new CliError("This machine hasn't fetched the Git workspace yet.", "barndog sync");
28
+ }
29
+ return { model, commit };
29
30
  }
30
31
  function selectAsset(model, kind, name, origin) {
31
32
  const matches = model.assets.filter((asset) => asset.kind === kind &&
@@ -251,11 +252,12 @@ export function pushGitWorkingCopy(workspace, options, runtime) {
251
252
  return locked(runtime, async () => {
252
253
  const { model, commit: tip } = await latest(workspace, runtime);
253
254
  let work;
255
+ let unregistered = false;
254
256
  try {
255
257
  work = await findGit(runtime);
256
258
  }
257
259
  catch (error) {
258
- if (!options.origin || !(error instanceof CliError)) {
260
+ if (!options.origin || !(error instanceof NoWorkingCopyError)) {
259
261
  throw error;
260
262
  }
261
263
  const root = await realpath(cwd);
@@ -271,7 +273,7 @@ export function pushGitWorkingCopy(workspace, options, runtime) {
271
273
  base: [],
272
274
  conflicts: [],
273
275
  };
274
- await save(work, runtime);
276
+ unregistered = true;
275
277
  }
276
278
  if (options.kind && work.kind !== options.kind) {
277
279
  throw new CliError(`This working copy holds a ${work.kind}, not a ${options.kind}.`, "barndog status");
@@ -282,6 +284,10 @@ export function pushGitWorkingCopy(workspace, options, runtime) {
282
284
  if (work.git.workspaceId !== workspace.workspaceId) {
283
285
  throw new CliError("This working copy belongs to a different Git workspace.");
284
286
  }
287
+ // Registered only once the folder passed the checks above.
288
+ if (unregistered) {
289
+ await save(work, runtime);
290
+ }
285
291
  if (work.conflicts.length) {
286
292
  throw new CliError("Resolve the conflicts before pushing.", "barndog resolve <path>");
287
293
  }
@@ -1,3 +1,4 @@
1
+ import { fixSteps } from "../../platform.js";
1
2
  import { HTTP_STATUS } from "../../shared/constants.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { z } from "zod";
@@ -116,7 +117,7 @@ export async function pushExternal(work, source, options, runtime) {
116
117
  }))).pull
117
118
  : undefined;
118
119
  if (pull?.state === "closed" && !options.new) {
119
- throw new CliError("The pull request is closed. Pull, then push a new one.", "barndog pull && barndog push --new");
120
+ throw new CliError("The pull request is closed. Pull, then push a new one.", fixSteps(["barndog pull", "barndog push --new"], runtime.platform));
120
121
  }
121
122
  if (pull && pull.head !== external.pull?.head) {
122
123
  throw new CliError("The pull request changed on GitHub since your last pull.", "barndog pull");
@@ -9,7 +9,7 @@ import { changeUploadSchema } from "@barndog-ai/api-contract";
9
9
  import { packageFingerprint, } from "@barndog-ai/api-contract/package";
10
10
  import { packageKindList } from "../../config/selection.js";
11
11
  import { GIT_OBJECT_ID } from "../../shared/patterns.js";
12
- import { readIfExists, writeAtomic } from "../../shared/files.js";
12
+ import { isInside, readIfExists, writeAtomic } from "../../shared/files.js";
13
13
  import { withPidLock } from "../../shared/lock.js";
14
14
  import { barndogPaths } from "../../config/paths.js";
15
15
  const filesSchema = z.array(z.object({ path: z.string(), content: z.string(), executable: z.boolean() }));
@@ -134,7 +134,8 @@ async function recoverySnapshot(work, runtime) {
134
134
  command: removeCommand(recordPath(work.root, runtime), runtime.platform),
135
135
  });
136
136
  const path = work.pendingSnapshot;
137
- if (!path?.startsWith(barndogPaths(runtime.home).workingCopySnapshots + "/")) {
137
+ const snapshots = barndogPaths(runtime.home).workingCopySnapshots;
138
+ if (!path || path === snapshots || !isInside(snapshots, path)) {
138
139
  throw damaged("its record doesn't point at a recovery snapshot");
139
140
  }
140
141
  const text = await readIfExists(path);
@@ -189,12 +190,31 @@ export const findGit = (runtime) => {
189
190
  return gitWorkspaceSchema.parse(value);
190
191
  });
191
192
  };
193
+ /**
194
+ * A working-copy record read from disk. A record that isn't JSON or doesn't
195
+ * match its schema was damaged, so it says how to start the folder over; the
196
+ * errors `parse` raises itself pass through.
197
+ */
198
+ function parseRecord(text, root, runtime, parse) {
199
+ try {
200
+ return parse(JSON.parse(text));
201
+ }
202
+ catch (error) {
203
+ if (error instanceof CliError) {
204
+ throw error;
205
+ }
206
+ throw new CliError(`The working-copy record for ${root} is damaged.`, "Save any edits in the folder elsewhere, then remove its working-copy record and pull it again", {
207
+ cause: error,
208
+ command: removeCommand(recordPath(root, runtime), runtime.platform),
209
+ });
210
+ }
211
+ }
192
212
  async function findRecord(runtime, parse) {
193
213
  let path = await realpath(runtime.cwd);
194
214
  while (true) {
195
215
  const text = await readIfExists(recordPath(path, runtime));
196
216
  if (text !== null) {
197
- const work = parse(JSON.parse(text));
217
+ const work = parseRecord(text, path, runtime, parse);
198
218
  if (work.root !== path) {
199
219
  throw new Error(`The working-copy record for ${path} names a different folder`);
200
220
  }
@@ -226,7 +246,6 @@ async function findRecord(runtime, parse) {
226
246
  throw new NoWorkingCopyError("This folder isn't an editable Skill or Hook. Working-copy commands run inside a folder made by barndog skills pull, barndog hooks pull or barndog skills create.", "barndog skills pull <name>");
227
247
  }
228
248
  async function replaceFiles(root, entries, runtime) {
229
- assertPackagePaths(entries, runtime.platform);
230
249
  // Validate paths and directory topology before touching local files.
231
250
  const paths = new Set(entries.map((e) => e.path));
232
251
  for (const path of paths) {
@@ -247,6 +266,8 @@ async function replaceFiles(root, entries, runtime) {
247
266
  }
248
267
  }
249
268
  }
269
+ // After the safety check, so an unsafe path is reported as unsafe.
270
+ assertPackagePaths(entries, runtime.platform);
250
271
  const old = await readDirectory(root, runtime);
251
272
  for (const entry of old) {
252
273
  await rm(join(root, entry.path));
@@ -1,3 +1,4 @@
1
+ import { isWindows } from "../../platform.js";
1
2
  import { writePackage, readDirectory } from "../workspace/directory.js";
2
3
  import { HTTP_STATUS } from "../../shared/constants.js";
3
4
  import { randomUUID } from "node:crypto";
@@ -214,10 +215,24 @@ const CONFLICT_MARKER = /^(?:<{7}|\|{7}|={7}|>{7})(?: |$)/m;
214
215
  */
215
216
  export const hasConflictMarkers = (text) => CONFLICT_MARKER.test(text);
216
217
  /** Clears one conflict once its markers are gone; shared by cloud and Git working copies. */
218
+ /**
219
+ * The conflict `absolute` names. macOS and Windows folders usually ignore
220
+ * case, so there a path that differs only in case still matches, as long as
221
+ * it matches one conflict.
222
+ */
223
+ function conflictAt(work, absolute, platform) {
224
+ const exact = work.conflicts.find((p) => join(work.root, p) === absolute);
225
+ if (exact || (platform !== "darwin" && !isWindows(platform))) {
226
+ return exact;
227
+ }
228
+ const folded = absolute.toLowerCase();
229
+ const matches = work.conflicts.filter((p) => join(work.root, p).toLowerCase() === folded);
230
+ return matches.length === 1 ? matches[0] : undefined;
231
+ }
217
232
  export async function markResolved(work, path, runtime) {
218
233
  const { cwd } = runtime;
219
234
  const absolute = resolve(await realpath(cwd), path);
220
- const conflict = work.conflicts.find((p) => join(work.root, p) === absolute);
235
+ const conflict = conflictAt(work, absolute, runtime.platform);
221
236
  if (!conflict) {
222
237
  throw new CliError(`${path} isn't an unresolved conflict.`, "barndog status");
223
238
  }
@@ -272,6 +287,7 @@ export async function pushWorkspace(options = {}, runtime) {
272
287
  const { cwd } = runtime;
273
288
  return locked(runtime, async () => {
274
289
  let work;
290
+ let unregistered = false;
275
291
  try {
276
292
  work = await find(runtime);
277
293
  }
@@ -296,7 +312,7 @@ export async function pushWorkspace(options = {}, runtime) {
296
312
  base: [],
297
313
  conflicts: [],
298
314
  };
299
- await save(work, runtime);
315
+ unregistered = true;
300
316
  }
301
317
  if (options.kind && work.kind !== options.kind) {
302
318
  throw new CliError(`This working copy holds a ${work.kind}, not a ${options.kind}.`, "barndog status");
@@ -304,6 +320,10 @@ export async function pushWorkspace(options = {}, runtime) {
304
320
  if (options.name && work.name !== options.name) {
305
321
  throw new CliError(`This working copy is ${work.name}, not ${options.name}.`, "barndog status");
306
322
  }
323
+ // Registered only once the folder passed the checks above.
324
+ if (unregistered) {
325
+ await save(work, runtime);
326
+ }
307
327
  await connection(runtime, work.connection);
308
328
  if (options.origin) {
309
329
  const selected = await selectOrigin(options.origin, work.connection, runtime);
@@ -10,9 +10,35 @@ import { LoginRequiredError } from "../auth/transport.js";
10
10
  import { synchronize } from "../environment/sync.js";
11
11
  import { assetKinds } from "../asset-kinds/index.js";
12
12
  import { barndogPaths } from "../../config/paths.js";
13
+ import { unassignedValueMessage, unsetValueMessage, } from "../environment/events.js";
14
+ /** An MCP variable with no value on this machine, or a kept value no server has. */
15
+ function variableCheck(event) {
16
+ if (event.type === "unassigned-value") {
17
+ return [
18
+ {
19
+ name: "MCP variable",
20
+ status: "warn",
21
+ detail: unassignedValueMessage(event.variable),
22
+ fix: `barndog mcp env set <server> ${event.variable}`,
23
+ },
24
+ ];
25
+ }
26
+ if (event.type !== "unset-variable") {
27
+ return [];
28
+ }
29
+ return [
30
+ {
31
+ name: "MCP variable",
32
+ status: "warn",
33
+ detail: `${unsetValueMessage(event)} BarnDog doesn't keep it and it isn't set in this shell. Coding tools opened outside a terminal may not see your shell's variables either.`,
34
+ fix: `barndog mcp env set ${event.server} ${event.variable}`,
35
+ },
36
+ ];
37
+ }
13
38
  const failure = (error) => ({
14
39
  detail: error instanceof Error ? error.message : String(error),
15
40
  fix: error instanceof CliError ? error.hint : undefined,
41
+ command: error instanceof CliError ? error.command : undefined,
16
42
  });
17
43
  async function gitChecks(workspace, runtime) {
18
44
  const checks = [];
@@ -26,8 +52,8 @@ async function gitChecks(workspace, runtime) {
26
52
  }
27
53
  catch (error) {
28
54
  checks.push({ name: "Git access", status: "fail", ...failure(error) });
29
- return checks;
30
55
  }
56
+ // Read locally, so it still helps when the remote can't be reached.
31
57
  const state = await readFetchState(workspace.workspaceId, runtime);
32
58
  checks.push({
33
59
  name: "Last fetch",
@@ -37,6 +63,9 @@ async function gitChecks(workspace, runtime) {
37
63
  : "Never fetched.",
38
64
  fix: state.fetchedAt ? undefined : "barndog sync",
39
65
  });
66
+ if (checks.some((check) => check.status === "fail")) {
67
+ return checks;
68
+ }
40
69
  const protectedBranch = await branchProtected(workspace.url, workspace.branch, runtime);
41
70
  if (protectedBranch !== true) {
42
71
  checks.push({
@@ -49,7 +78,10 @@ async function gitChecks(workspace, runtime) {
49
78
  }
50
79
  return checks;
51
80
  }
52
- /** Every check runs; one failure never hides the others. */
81
+ /**
82
+ * Runs every check that can run: a failure hides only the checks that need
83
+ * what failed (a readable configuration, a session).
84
+ */
53
85
  export async function doctor(runtime) {
54
86
  const { home } = runtime;
55
87
  const checks = [];
@@ -77,13 +109,19 @@ export async function doctor(runtime) {
77
109
  });
78
110
  const detected = await detectHarnesses(runtime);
79
111
  for (const harness of settings.harnesses) {
112
+ const { name } = adapters[harness];
80
113
  const found = detected.find((d) => d.id === harness)?.evidence;
114
+ if (found) {
115
+ checks.push({ name, status: "ok", detail: found });
116
+ continue;
117
+ }
118
+ // Disabling removes what BarnDog installed there, so it goes in `command`.
81
119
  checks.push({
82
- name: adapters[harness].name,
83
- status: found ? "ok" : "warn",
84
- detail: found ??
85
- "Not found on this machine; assets are still installed for it.",
86
- fix: found ? undefined : "barndog init",
120
+ name,
121
+ status: "warn",
122
+ detail: "Not found on this machine; assets are still installed for it.",
123
+ fix: `Install ${name}, or stop BarnDog installing for it.`,
124
+ command: `barndog harnesses disable ${harness}`,
87
125
  });
88
126
  }
89
127
  const connected = settings.connection;
@@ -127,6 +165,7 @@ export async function doctor(runtime) {
127
165
  : "Everything selected is installed and up to date.",
128
166
  fix: pending ? "barndog sync" : undefined,
129
167
  });
168
+ checks.push(...events.flatMap(variableCheck));
130
169
  for (const event of events) {
131
170
  if (event.type === "notice") {
132
171
  checks.push({ name: "Notice", status: "warn", detail: event.message });
@@ -1 +1,8 @@
1
- export {};
1
+ /** What an `unset-variable` event means, as one sentence. */
2
+ export function unsetValueMessage(event) {
3
+ return event.from
4
+ ? `${event.from} has no value here, so ${event.server} can't read ${event.variable} from it.`
5
+ : `${event.variable} has no value here, so ${event.server} can't use it.`;
6
+ }
7
+ /** What an `unassigned-value` event means, as one sentence. */
8
+ export const unassignedValueMessage = (variable) => `BarnDog keeps a value for ${variable} from before each value belonged to one MCP server, and no server has it yet.`;
@@ -0,0 +1,36 @@
1
+ import { detectHarnesses } from "../../harnesses/detect.js";
2
+ import { harnesses } from "../../harnesses/registry.js";
3
+ import { locked } from "./transaction.js";
4
+ import { synchronize } from "./sync.js";
5
+ import { readRequiredSettings } from "./operations.js";
6
+ /** Every coding tool BarnDog supports, in registry order. */
7
+ export async function listHarnesses(runtime) {
8
+ const settings = await readRequiredSettings(runtime);
9
+ const detected = await detectHarnesses(runtime);
10
+ return detected.map((harness) => ({
11
+ ...harness,
12
+ enabled: settings.harnesses.includes(harness.id),
13
+ }));
14
+ }
15
+ /** Leaves the tools not named as they are. */
16
+ export function changeHarnesses(change, targets, runtime) {
17
+ return applyHarnesses(runtime, (current) => change === "enable"
18
+ ? [...current, ...targets]
19
+ : current.filter((harness) => !targets.includes(harness)));
20
+ }
21
+ export function selectHarnesses(selected, runtime) {
22
+ return applyHarnesses(runtime, () => selected);
23
+ }
24
+ function applyHarnesses(runtime, next) {
25
+ return locked(runtime, async () => {
26
+ const settings = await readRequiredSettings(runtime);
27
+ const chosen = new Set(next(settings.harnesses));
28
+ // Registry order, so the saved list doesn't depend on the order typed.
29
+ const managed = harnesses.filter((harness) => chosen.has(harness));
30
+ const events = await synchronize(undefined, runtime, {
31
+ ...settings,
32
+ harnesses: managed,
33
+ });
34
+ return { status: "applied", events, harnesses: managed };
35
+ });
36
+ }
@@ -0,0 +1,68 @@
1
+ import { readState } from "../../config/state.js";
2
+ import { recordedVariables } from "../native/secret-values.js";
3
+ import { changeSecrets, readStoredSecrets, } from "../secrets/index.js";
4
+ function converted(values, state) {
5
+ const servers = {};
6
+ const assigned = new Set();
7
+ for (const entry of state.native) {
8
+ if (entry.kind !== "mcp") {
9
+ continue;
10
+ }
11
+ for (const variable of recordedVariables(entry.value)) {
12
+ const value = values[variable];
13
+ if (value !== undefined) {
14
+ servers[entry.id] = { ...servers[entry.id], [variable]: { value } };
15
+ assigned.add(variable);
16
+ }
17
+ }
18
+ }
19
+ return {
20
+ servers,
21
+ unassigned: Object.fromEntries(Object.entries(values).filter(([variable]) => !assigned.has(variable))),
22
+ };
23
+ }
24
+ const upgraded = (stored, state) => stored.version === 2 ? stored : converted(stored.values, state);
25
+ /** The kept values, converting a version 1 file first. */
26
+ export async function keptValues(runtime) {
27
+ const stored = await readStoredSecrets(runtime);
28
+ if (stored.version === 2) {
29
+ return stored;
30
+ }
31
+ const state = await readState(runtime.home);
32
+ const { secrets } = await changeSecrets((latest) => upgraded(latest, state), runtime);
33
+ return secrets;
34
+ }
35
+ /** Saves what `change` makes of the kept values; returns the file's path. */
36
+ export async function updateKeptValues(change, runtime) {
37
+ const state = await readState(runtime.home);
38
+ const { file } = await changeSecrets((latest) => change(upgraded(latest, state)), runtime);
39
+ return file;
40
+ }
41
+ /** `secrets` with `values` set for the server with asset ID `id`; null forgets that variable's value. */
42
+ export function withServerValues(secrets, id, values) {
43
+ const server = { ...secrets.servers[id] };
44
+ for (const [variable, value] of Object.entries(values)) {
45
+ if (value === null) {
46
+ delete server[variable];
47
+ }
48
+ else {
49
+ server[variable] = value;
50
+ }
51
+ }
52
+ return { ...secrets, servers: { ...secrets.servers, [id]: server } };
53
+ }
54
+ /** `secrets` with each moved server's values under its new asset ID. */
55
+ export function withMovedServers(secrets, moves) {
56
+ const servers = { ...secrets.servers };
57
+ for (const { from, to, copy } of moves) {
58
+ const values = servers[from];
59
+ if (!values) {
60
+ continue;
61
+ }
62
+ servers[to] = { ...values, ...servers[to] };
63
+ if (!copy) {
64
+ delete servers[from];
65
+ }
66
+ }
67
+ return { ...secrets, servers };
68
+ }
@@ -0,0 +1,187 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { resolveAssets } from "../asset-selection/index.js";
5
+ import { updateKeptValues, withMovedServers, } from "./kept-values.js";
6
+ import { forgetImport } from "../imports/local.js";
7
+ import { saveSettings } from "../../config/settings.js";
8
+ import { withSelection } from "../../config/environment.js";
9
+ import { localOverlay, moveDestination, readMoved, recordMoved, } from "../workspace/overlay.js";
10
+ import { openRepoSource, openWorkspaceSource, } from "../workspace/workspace-source.js";
11
+ import { treeFingerprint } from "../workspace/tree.js";
12
+ const targetOf = (entry) => entry.target ?? "the shared workspace";
13
+ const waiting = (entry) => `${entry.name} is still moving to ${moveDestination(entry)}. Your local copy stays in use until that merges.`;
14
+ /** Whether the local copy still holds exactly what was moved. */
15
+ async function unchanged(entry, local, shared, input) {
16
+ if (entry.version) {
17
+ return local.publishedVersion === entry.version;
18
+ }
19
+ // Moves recorded before versions were kept: compare with the shared copy.
20
+ if (local.kind === "mcp") {
21
+ return isDeepStrictEqual(await input.source.mcpDefinition(shared), local.definition);
22
+ }
23
+ const folder = await input.source.packageFolder(local.kind, shared);
24
+ return ((await treeFingerprint(folder, input.runtime)) ===
25
+ (await treeFingerprint(join(input.overlay.label, local.path), input.runtime)));
26
+ }
27
+ /** Where a knowledge move stands; Cloud knowledge is published at once, so only Git waits. */
28
+ async function knowledgeOutcome(entry, model, input) {
29
+ const doc = model.knowledge.find((d) => d.path === entry.path);
30
+ if (!doc) {
31
+ return "gone";
32
+ }
33
+ // Recorded before versions were kept, and Cloud knowledge can't be compared here.
34
+ if (!entry.version) {
35
+ return "changed";
36
+ }
37
+ if (!(await input.sharedKnowledge())?.includes(entry.name)) {
38
+ return "waiting";
39
+ }
40
+ return doc.version === entry.version ? "unchanged" : "changed";
41
+ }
42
+ /** Only paths the local workspace's own model lists get here, so they stay inside it. */
43
+ async function removeLocal(entry, input) {
44
+ await rm(join(input.overlay.label, entry.path), {
45
+ recursive: true,
46
+ force: true,
47
+ });
48
+ await forgetImport(input.overlay.label, entry.kind, entry.name);
49
+ }
50
+ /** Kept MCP values follow each moved server to its shared copy. */
51
+ async function carryKeptValues(servers, runtime) {
52
+ if (servers.length) {
53
+ await updateKeptValues((secrets) => withMovedServers(secrets, servers), runtime);
54
+ }
55
+ }
56
+ async function settleMoves(input) {
57
+ const records = await readMoved(input.overlay.label);
58
+ if (!records.length) {
59
+ return { selection: input.selection, notices: [], removedLocal: false };
60
+ }
61
+ const model = await input.overlay.model();
62
+ const selected = new Set(resolveAssets(input.catalog, input.selection).assets.map((entry) => entry.asset.id));
63
+ const ids = [...input.selection.individualAssetIds];
64
+ const notices = [];
65
+ const finished = [];
66
+ const removals = [];
67
+ const servers = [];
68
+ const finish = (entry, keep) => {
69
+ finished.push(entry.path);
70
+ if (keep) {
71
+ notices.push(`${entry.name} changed after it was moved to ${targetOf(entry)}, so your local copy stays as a separate asset.`);
72
+ return;
73
+ }
74
+ removals.push(entry);
75
+ notices.push(`${entry.name} moved to ${targetOf(entry)}. Removed the local copy at ${join(input.overlay.label, entry.path)}.`);
76
+ };
77
+ for (const entry of records) {
78
+ if (entry.kind === "knowledge") {
79
+ const outcome = await knowledgeOutcome(entry, model, input);
80
+ if (outcome === "waiting") {
81
+ notices.push(waiting(entry));
82
+ }
83
+ else if (outcome === "gone") {
84
+ finished.push(entry.path);
85
+ }
86
+ else {
87
+ finish(entry, outcome === "changed");
88
+ }
89
+ continue;
90
+ }
91
+ const shared = input.catalog.assets.find((asset) => !asset.origin.localOnly &&
92
+ asset.kind === entry.kind &&
93
+ asset.name === entry.name &&
94
+ asset.origin.id === entry.originId);
95
+ if (!shared) {
96
+ notices.push(waiting(entry));
97
+ continue;
98
+ }
99
+ if (!selected.has(shared.id) && !ids.includes(shared.id)) {
100
+ ids.push(shared.id);
101
+ }
102
+ const local = model.assets.find((asset) => asset.path === entry.path);
103
+ if (!local) {
104
+ finished.push(entry.path);
105
+ continue;
106
+ }
107
+ const keep = !(await unchanged(entry, local, shared, input));
108
+ servers.push({
109
+ kind: entry.kind,
110
+ from: local.id,
111
+ to: shared.id,
112
+ copy: keep,
113
+ });
114
+ finish(entry, keep);
115
+ }
116
+ const selection = ids.length === input.selection.individualAssetIds.length
117
+ ? input.selection
118
+ : { ...input.selection, individualAssetIds: ids };
119
+ if (input.persist && finished.length) {
120
+ // Saved first, so an interrupted sync can't leave an asset with neither copy.
121
+ await input.saveSelection(selection);
122
+ await carryKeptValues(servers.filter((server) => server.kind === "mcp"), input.runtime);
123
+ for (const entry of removals) {
124
+ await removeLocal(entry, input);
125
+ }
126
+ await recordMoved(input.overlay.label, [], finished);
127
+ }
128
+ return {
129
+ selection,
130
+ notices,
131
+ removedLocal: input.persist && removals.length > 0,
132
+ };
133
+ }
134
+ /**
135
+ * A machine that stopped using a Git or Cloud workspace can't finish moves
136
+ * into it, so they end here and the local copies stay as they are.
137
+ */
138
+ async function dropUnreachable(settings, persist) {
139
+ const folder = settings.localWorkspace?.path;
140
+ const records = folder ? await readMoved(folder) : [];
141
+ if (!folder || !records.length || !persist) {
142
+ return [];
143
+ }
144
+ await recordMoved(folder, [], records.map((entry) => entry.path));
145
+ return [
146
+ `This machine no longer uses the workspace ${records.map((entry) => entry.name).join(", ")} ${records.length === 1 ? "was" : "were"} moving to, so ${records.length === 1 ? "its local copy stays" : "their local copies stay"} as ${records.length === 1 ? "it is" : "they are"}.`,
147
+ ];
148
+ }
149
+ /**
150
+ * Finishes the moves whose shared copy exists. When a local copy was deleted,
151
+ * the catalog read before it still lists that copy, so it is read again
152
+ * unless the caller supplied it (`reread` false).
153
+ */
154
+ export async function finishMoves(input) {
155
+ const { settings, source, options, runtime } = input;
156
+ // A one-off --config delivery never changes what this machine keeps.
157
+ const persist = !options.dryRun && !input.configPath;
158
+ const reread = !options.source && !options.catalog;
159
+ const overlay = localOverlay(settings, runtime);
160
+ if (!overlay || !source) {
161
+ return {
162
+ source,
163
+ catalog: input.catalog,
164
+ selection: input.selection,
165
+ notices: await dropUnreachable(settings, persist),
166
+ };
167
+ }
168
+ const moves = await settleMoves({
169
+ overlay,
170
+ source,
171
+ catalog: input.catalog,
172
+ selection: input.selection,
173
+ sharedKnowledge: async () => settings.gitWorkspace
174
+ ? ((await openRepoSource(settings, runtime, {
175
+ refresh: "none",
176
+ })?.model())?.knowledge.map((doc) => doc.content.name) ?? null)
177
+ : null,
178
+ persist,
179
+ saveSelection: (next) => saveSettings(withSelection(settings, next), runtime.home),
180
+ runtime,
181
+ });
182
+ if (!moves.removedLocal || !reread) {
183
+ return { source, catalog: input.catalog, ...moves };
184
+ }
185
+ const fresh = openWorkspaceSource(settings, runtime, { refresh: "none" }) ?? source;
186
+ return { source: fresh, catalog: await fresh.catalog(), ...moves };
187
+ }
@@ -1,4 +1,5 @@
1
- import { slugify, validAssetName } from "../../shared/patterns.js";
1
+ import { slugify } from "../../shared/patterns.js";
2
+ import { assetKinds } from "../asset-kinds/index.js";
2
3
  /** Eight ID characters distinguish hooks with the same display name. */
3
4
  const HOOK_ID_SUFFIX_LENGTH = 8;
4
5
  /** Unknown origins sort after all explicitly ranked origins. */
@@ -14,11 +15,14 @@ const rank = {
14
15
  };
15
16
  /** `<origin-type>-<origin-slug>-<name>` with single hyphens, e.g. team-super-team-review. */
16
17
  export function prefixedName(asset) {
17
- return slugify([
18
+ const prefix = [
18
19
  asset.origin.type,
19
20
  asset.origin.slug ?? asset.origin.id ?? "",
20
- asset.name,
21
- ].join("-"));
21
+ ].join("-");
22
+ // An MCP server keeps its own spelling, such as my_server; only the prefix is a slug.
23
+ return asset.kind === "mcp"
24
+ ? `${slugify(prefix)}-${asset.name}`
25
+ : slugify(`${prefix}-${asset.name}`);
22
26
  }
23
27
  /**
24
28
  * The name an asset installs under: its saved rename from `localNames`, else
@@ -45,7 +49,7 @@ export function hookFolders(hooks, localNames) {
45
49
  folders.set(hook.id, folder);
46
50
  used.add(folder);
47
51
  };
48
- const plain = (hook) => localNames[hook.id] ?? prefixedName(hook);
52
+ const plain = (hook) => localNames[hook.id] ?? prefixedName({ ...hook, kind: "hook" });
49
53
  const idText = (hook) => hook.id.replace(/[^a-z0-9]/gi, "").toLowerCase();
50
54
  const suffixed = (hook) => `${plain(hook)}-${idText(hook).slice(0, HOOK_ID_SUFFIX_LENGTH)}`;
51
55
  const whole = (hook) => `${plain(hook)}-${idText(hook)}`;
@@ -149,7 +153,7 @@ export async function resolveClashes(assets, localNames, resolver) {
149
153
  if (rename) {
150
154
  const name = prefixedName(rename);
151
155
  if (rename.renamable === false ||
152
- !validAssetName(name) ||
156
+ !assetKinds[rename.kind].validName(name) ||
153
157
  active.some((other) => other.id !== rename.id &&
154
158
  other.kind === rename.kind &&
155
159
  installedName(other, names) === name)) {