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
@@ -1,5 +1,4 @@
1
1
  import { localPath } from "../../platform.js";
2
- import { readFile } from "node:fs/promises";
3
2
  import { z } from "zod";
4
3
  import { readSettings, SetupRequiredError, } from "../../config/settings.js";
5
4
  import { selectionState, withSelection } from "../../config/environment.js";
@@ -11,10 +10,11 @@ import { installedNames, synchronize } from "./sync.js";
11
10
  import { openRepoSource } from "../workspace/workspace-source.js";
12
11
  import { localOverlay, mergeLocalCatalog, withOverlay, } from "../workspace/overlay.js";
13
12
  import { CliError, friendlyMessage } from "../../errors.js";
13
+ import { inputFile } from "../../shared/files.js";
14
14
  import { originLabel } from "../server/origin.js";
15
15
  import { assetKinds } from "../asset-kinds/index.js";
16
16
  import { only } from "../../shared/lookup.js";
17
- import { splitOrigin, validAssetName } from "../../shared/patterns.js";
17
+ import { splitOrigin } from "../../shared/patterns.js";
18
18
  const decisionsSchema = z.array(z
19
19
  .object({
20
20
  assetId: z.uuidv4(),
@@ -23,7 +23,7 @@ const decisionsSchema = z.array(z
23
23
  .strict());
24
24
  /** A `--decisions` file: `[{"assetId":"<uuid>","choice":"preserve"}]`. */
25
25
  async function readDecisions(file, runtime) {
26
- const text = await readFile(localPath(file, runtime), "utf8");
26
+ const text = (await inputFile(localPath(file, runtime))).toString("utf8");
27
27
  let value;
28
28
  try {
29
29
  value = JSON.parse(text);
@@ -93,7 +93,7 @@ async function workspaceAccess(settings, runtime) {
93
93
  scopes: () => scopes(conn, runtime),
94
94
  };
95
95
  }
96
- async function readRequiredSettings(runtime) {
96
+ export async function readRequiredSettings(runtime) {
97
97
  const { home } = runtime;
98
98
  const settings = await readSettings(home);
99
99
  if (!settings) {
@@ -163,7 +163,7 @@ function assetId(workspace, target, change) {
163
163
  const id = only(matches)?.id ?? staleId;
164
164
  const [first] = matches;
165
165
  if (!id && first && matches.length > 1) {
166
- throw new CliError(`${target.name} exists in several scopes: ${matches.map((a) => originLabel(a.origin)).join(", ")}. Choose one with --origin.`, `${command} ${target.name} --origin ${originLabel(first.origin)}`);
166
+ throw new CliError(`${target.name} exists in several scopes: ${matches.map((a) => originLabel(a.origin)).join(", ")}. Choose one with --origin.`, `${command} ${target.name} --origin ${originLabel(first.origin)}${change === "rename" ? " --as <new-name>" : ""}`);
167
167
  }
168
168
  if (!id) {
169
169
  throw new CliError(`No ${assetKinds[target.kind].one} named ${target.name}${target.origin ? ` in ${target.origin}` : ""} is available to you.`, `barndog ${assetKinds[target.kind].command} search ${target.name}`);
@@ -215,8 +215,8 @@ export async function renameAsset(target, runtime) {
215
215
  }
216
216
  else {
217
217
  const name = target.as ?? "";
218
- if (!validAssetName(name)) {
219
- throw new CliError("Use lowercase letters, numbers and single hyphens (at most 64 characters).");
218
+ if (!assetKinds[target.kind].validName(name)) {
219
+ throw new CliError(`${assetKinds[target.kind].nameRule}.`);
220
220
  }
221
221
  const held = await installedNames(runtime);
222
222
  const taken = catalog.assets.find((a) => a.id !== id &&
@@ -8,8 +8,26 @@ import { adapters, isHookHarness, skillDirectory, } from "../../harnesses/regist
8
8
  import { isInside } from "../../shared/files.js";
9
9
  import { defined } from "../../shared/lookup.js";
10
10
  import { hookEntries, hookIssue, mcpEntry } from "../native/adapters.js";
11
+ import { applyKeptValues, missingValues, } from "../secrets/index.js";
11
12
  import { desiredEntries, installedPath } from "../workspace/installed.js";
12
13
  import { hookFolders, installedName } from "./names.js";
14
+ /**
15
+ * One event per variable an installed MCP server refers to that has no value
16
+ * here, and one per value kept from a version 1 file that no server has.
17
+ */
18
+ function valueEvents(servers, kept, env) {
19
+ return [
20
+ ...servers.flatMap(({ name, definition, values }) => missingValues(definition, values, env).map((missing) => ({
21
+ type: "unset-variable",
22
+ server: name,
23
+ ...missing,
24
+ }))),
25
+ ...Object.keys(kept.unassigned).map((variable) => ({
26
+ type: "unassigned-value",
27
+ variable,
28
+ })),
29
+ ];
30
+ }
13
31
  export async function stageAssets(input) {
14
32
  const { invalid, vanished, skipped, localNames, source, harnesses, runtime } = input;
15
33
  const { home } = runtime;
@@ -21,6 +39,8 @@ export async function stageAssets(input) {
21
39
  const events = [];
22
40
  const names = new Set();
23
41
  const ids = new Set();
42
+ /** Installed MCP servers, to report the variables they find no value for. */
43
+ const servers = [];
24
44
  const addSkill = (id, source, name) => {
25
45
  if (names.has(name)) {
26
46
  throw new CliError(`Two enabled Skills are named ${name}`, "barndog doctor");
@@ -125,8 +145,11 @@ export async function stageAssets(input) {
125
145
  }
126
146
  else if (ref.kind === "mcp") {
127
147
  const definition = await source.mcpDefinition(ref);
148
+ const values = input.kept.servers[ref.id] ?? {};
149
+ const applied = applyKeptValues(definition, values);
150
+ servers.push({ name, definition, values });
128
151
  for (const harness of harnesses) {
129
- native.push(mcpEntry(harness, { id: ref.id, name }, definition, runtime));
152
+ native.push(mcpEntry(harness, { id: ref.id, name, definition: applied.definition }, applied.kept, runtime));
130
153
  }
131
154
  }
132
155
  else {
@@ -146,6 +169,7 @@ export async function stageAssets(input) {
146
169
  events.push(...registered.events);
147
170
  }
148
171
  }
172
+ events.push(...valueEvents(servers, input.kept, input.runtime.env));
149
173
  return { links: desired, native, trees, events };
150
174
  }
151
175
  /**
@@ -9,8 +9,10 @@ import { assertSupportedConfigHomes, startupEntries } from "./own-entries.js";
9
9
  import { resolveAssets } from "../asset-selection/index.js";
10
10
  import { pruneCache } from "../workspace/packages.js";
11
11
  import { followImports } from "../imports/local.js";
12
- import { adoptMoved, localOverlay } from "../workspace/overlay.js";
12
+ import { localOverlay } from "../workspace/overlay.js";
13
13
  import { openWorkspaceSource } from "../workspace/workspace-source.js";
14
+ import { finishMoves } from "./moves.js";
15
+ import { keptValues } from "./kept-values.js";
14
16
  import { locked, transact } from "./transaction.js";
15
17
  import { assertInstalledUntouched, linkWrites, nativeWrites, entryNames, stateText, treeWrites, } from "./writes.js";
16
18
  import { fileText } from "../../shared/files.js";
@@ -48,7 +50,7 @@ export async function synchronize(configPath, runtime, override, options = {}) {
48
50
  `Imported assets weren't checked for updates, because ${localWorkspaceFiles(local.path).sources} couldn't be read: ${friendlyMessage(error)}`,
49
51
  ])
50
52
  : [];
51
- const source = options.source ??
53
+ let source = options.source ??
52
54
  openWorkspaceSource(settings, runtime, {
53
55
  refresh: options.refresh,
54
56
  });
@@ -56,13 +58,20 @@ export async function synchronize(configPath, runtime, override, options = {}) {
56
58
  (selection.subscriptions.length || selection.individualAssetIds.length)) {
57
59
  throw new CliError("Your selection includes assets from a BarnDog server, but this machine isn't connected to one.", "barndog init");
58
60
  }
59
- const catalog = source
61
+ let catalog = source
60
62
  ? (options.catalog ?? (await source.catalog()))
61
63
  : { assets: [], distributions: [] };
64
+ const moves = await finishMoves({
65
+ settings,
66
+ source,
67
+ catalog,
68
+ selection,
69
+ options,
70
+ configPath,
71
+ runtime,
72
+ });
73
+ ({ source, catalog, selection } = moves);
62
74
  const overlay = localOverlay(settings, runtime);
63
- if (overlay) {
64
- selection = await adoptMoved(overlay, catalog, selection, !options.dryRun);
65
- }
66
75
  const invalid = source
67
76
  ? await source.invalidAssets()
68
77
  : new Map();
@@ -73,6 +82,7 @@ export async function synchronize(configPath, runtime, override, options = {}) {
73
82
  const events = [
74
83
  ...new Set([
75
84
  ...followNotices,
85
+ ...moves.notices,
76
86
  ...(source?.notices() ?? []),
77
87
  ...((await source?.warnings?.()) ?? []),
78
88
  ...((await overlay?.warnings?.()) ?? []),
@@ -111,6 +121,7 @@ export async function synchronize(configPath, runtime, override, options = {}) {
111
121
  state: before,
112
122
  source,
113
123
  harnesses: settings.harnesses,
124
+ kept: await keptValues(runtime),
114
125
  runtime,
115
126
  });
116
127
  const { links: desired, native, trees } = staged;
@@ -4,6 +4,7 @@ import { fixSteps, removeCommand } from "../../platform.js";
4
4
  import { treeFingerprint } from "../workspace/tree.js";
5
5
  import { assetKinds } from "../asset-kinds/index.js";
6
6
  import { patchNative } from "../native/configuration.js";
7
+ import { recordedVariables, redacted, sameValue, } from "../native/secret-values.js";
7
8
  import { inPluginModule, pluginModule } from "../native/plugin-module.js";
8
9
  import { linkTarget } from "./transaction.js";
9
10
  function changeType(change) {
@@ -108,6 +109,45 @@ export async function linkWrites(previous, desired, updated) {
108
109
  }
109
110
  return { writes, events };
110
111
  }
112
+ /** The same entry, comparing kept values with the hashes `state.json` records. */
113
+ const sameEntry = (left, right) => left.id === right.id &&
114
+ left.kind === right.kind &&
115
+ left.harness === right.harness &&
116
+ left.file === right.file &&
117
+ left.key === right.key &&
118
+ sameValue(left.value, right.value);
119
+ /** A notice for kept values a changed entry no longer holds. */
120
+ function removedSecrets(entry, still) {
121
+ const gone = recordedVariables(entry.value).filter((variable) => !still.includes(variable));
122
+ return gone.length
123
+ ? [
124
+ {
125
+ type: "notice",
126
+ message: `Removed the kept ${plural(gone)} ${gone.join(", ")} from ${entry.file}.`,
127
+ },
128
+ ]
129
+ : [];
130
+ }
131
+ /** Says where kept values were written, and where they were taken out. */
132
+ function secretNotices(entry, old, changed, nameOf) {
133
+ if (!changed) {
134
+ return [];
135
+ }
136
+ const written = (entry.secrets ?? []).map((secret) => secret.variable);
137
+ const before = old.find((e) => e.id === entry.id && e.harness === entry.harness);
138
+ return [
139
+ ...(written.length
140
+ ? [
141
+ {
142
+ type: "notice",
143
+ message: `Wrote the kept ${plural(written)} ${written.join(", ")} into ${entry.file} for ${nameOf(entry)}. ${written.length === 1 ? "It stays" : "They stay"} on this machine.`,
144
+ },
145
+ ]
146
+ : []),
147
+ ...(before ? removedSecrets(before, written) : []),
148
+ ];
149
+ }
150
+ const plural = (variables) => variables.length === 1 ? "value of" : "values of";
111
151
  /**
112
152
  * One write per native settings file that holds, or will hold, an entry of
113
153
  * BarnDog's. `nameOf` gives the name an entry is reported under.
@@ -132,21 +172,23 @@ export async function nativeWrites(previous, desired, context) {
132
172
  : patchNative(text, old, next),
133
173
  });
134
174
  for (const entry of next) {
175
+ const action = changeType({
176
+ sameAsset: old.some((e) => e.id === entry.id && e.harness === entry.harness),
177
+ current: old.some((e) => sameEntry(e, entry)),
178
+ contentChanged: entry.kind === "hook" &&
179
+ trees.some((t) => t.id === entry.id && updated.has(t.path)),
180
+ });
135
181
  events.push({
136
182
  type: "native",
137
- action: changeType({
138
- sameAsset: old.some((e) => e.id === entry.id && e.harness === entry.harness),
139
- current: old.some((e) => JSON.stringify(e) === JSON.stringify(entry)),
140
- contentChanged: entry.kind === "hook" &&
141
- trees.some((t) => t.id === entry.id && updated.has(t.path)),
142
- }),
183
+ action,
143
184
  kind: entry.kind,
144
185
  harness: entry.harness,
145
186
  name: nameOf(entry),
146
187
  });
188
+ events.push(...secretNotices(entry, old, action !== "unchanged", nameOf));
147
189
  }
148
190
  for (const entry of old) {
149
- if (!next.some((e) => JSON.stringify(e) === JSON.stringify(entry) ||
191
+ if (!next.some((e) => sameEntry(e, entry) ||
150
192
  (e.id === entry.id && e.harness === entry.harness))) {
151
193
  events.push({
152
194
  type: "native",
@@ -155,6 +197,7 @@ export async function nativeWrites(previous, desired, context) {
155
197
  harness: entry.harness,
156
198
  name: nameOf(entry),
157
199
  });
200
+ events.push(...removedSecrets(entry, []));
158
201
  }
159
202
  }
160
203
  }
@@ -184,7 +227,11 @@ export function stateText(plan) {
184
227
  return (JSON.stringify({
185
228
  version: 1,
186
229
  links: plan.links,
187
- native: plan.native,
230
+ // Kept MCP values are recorded only as hashes; see secret-values.ts.
231
+ native: plan.native.map(({ secrets, ...entry }) => ({
232
+ ...entry,
233
+ value: redacted(entry.value, secrets ?? []),
234
+ })),
188
235
  installed: plan.trees.map(({ id, kind, path, fingerprint, versionId }) => ({
189
236
  id,
190
237
  kind,
@@ -6,19 +6,25 @@ import { runtimeRequirements } from "../native/adapters.js";
6
6
  import { hookHarnesses } from "../../harnesses/registry.js";
7
7
  import { hookMetadata } from "@barndog-ai/api-contract/package";
8
8
  /**
9
- * What a Hook's current version declares for each coding tool, and whether
10
- * this machine has what each implementation needs to run.
9
+ * What a Hook's current version declares for each coding tool BarnDog manages
10
+ * here, and whether this machine has what each implementation needs to run.
11
11
  */
12
12
  export async function hookCompatibility(name, origin, runtime) {
13
13
  const { home } = runtime;
14
14
  const settings = await readSettings(home);
15
+ const managed = (result) => settings
16
+ ? {
17
+ ...result,
18
+ compatibility: result.compatibility.filter((row) => settings.harnesses.includes(row.harness)),
19
+ }
20
+ : result;
15
21
  const repo = settings && repoForOrigin(settings, runtime, origin);
16
22
  if (repo) {
17
- return repoHookCompatibility(selectRepoAsset(await repo.model(), "hook", name, origin), runtime);
23
+ return managed(await repoHookCompatibility(selectRepoAsset(await repo.model(), "hook", name, origin), runtime));
18
24
  }
19
25
  const selected = await selectAsset("hook", name, origin, runtime);
20
26
  const asset = hookSchema.parse(selected.asset);
21
- return {
27
+ return managed({
22
28
  version: asset.version.number,
23
29
  compatibility: await Promise.all(asset.compatibility.map(async (row) => ({
24
30
  ...row,
@@ -26,7 +32,7 @@ export async function hookCompatibility(name, origin, runtime) {
26
32
  ? await runtimeRequirements(row.harness, row.implementation.requirements, runtime)
27
33
  : "No implementation for this harness",
28
34
  }))),
29
- };
35
+ });
30
36
  }
31
37
  /** What a Git or local workspace Hook declares for each coding tool, and what this machine lacks. */
32
38
  async function repoHookCompatibility(asset, runtime) {
@@ -1,22 +1,43 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
- import { divergentHookTools, hookManifestSchema, } from "@barndog-ai/api-contract";
4
+ import { hookManifestSchema, } from "@barndog-ai/api-contract";
5
5
  import { parse } from "yaml";
6
- import { adapters, hookHarnesses } from "../../harnesses/registry.js";
6
+ import { hookHarnesses } from "../../harnesses/registry.js";
7
+ import { toolNames } from "./adapt.js";
8
+ /**
9
+ * Tools grouped by the script files they run, largest group first. A tool
10
+ * whose commands run no script file of the Hook's has nothing to keep in step,
11
+ * so it's left out.
12
+ */
13
+ function scriptGroups(implementations) {
14
+ const groups = new Map();
15
+ for (const harness of hookHarnesses) {
16
+ const scripts = [...new Set(implementations[harness]?.scripts)].sort();
17
+ if (scripts.length) {
18
+ const key = scripts.join("\0");
19
+ groups.set(key, [...(groups.get(key) ?? []), harness]);
20
+ }
21
+ }
22
+ return [...groups.values()].sort((a, b) => b.length - a.length);
23
+ }
24
+ const inToolOrder = (tools) => hookHarnesses.filter((harness) => tools.includes(harness));
7
25
  /**
8
26
  * A caution for Hooks whose coding tools run different scripts: changing one
9
- * tool's scripts leaves the others as they were. Null when all share one set.
27
+ * tool's scripts leaves the others as they were. Null when they all share one
28
+ * set, or when at most one tool runs scripts at all.
10
29
  */
11
30
  function divergenceWarning(implementations) {
12
- const divergent = divergentHookTools(implementations);
13
- if (!divergent.length) {
31
+ const [shared, ...rest] = scriptGroups(implementations);
32
+ if (!shared || !rest.length) {
14
33
  return null;
15
34
  }
16
- const names = hookHarnesses
17
- .filter((harness) => divergent.includes(harness))
18
- .map((harness) => adapters[harness].name);
19
- return `${names.slice(0, -1).join(", ")} and ${names.at(-1)} run different scripts in this Hook. When you change it for one, check whether the others need the same change.`;
35
+ if (shared.length === 1) {
36
+ const tools = inToolOrder([shared, ...rest].flat());
37
+ return `${toolNames(tools)} each run their own scripts in this Hook. When you change one, check whether the ${tools.length === 2 ? "other needs" : "others need"} the same change.`;
38
+ }
39
+ const odd = inToolOrder(rest.flat());
40
+ return `${toolNames(odd)} ${odd.length === 1 ? "runs" : "run"} different scripts from ${toolNames(shared)} in this Hook. When you change one set, check whether the other needs the same change.`;
20
41
  }
21
42
  /** The same caution for a Hook folder on disk; null when it has no readable hook.yaml. */
22
43
  export async function folderDivergence(folder) {
@@ -12,6 +12,7 @@ import { hookInvocation } from "../native/hook-shell.js";
12
12
  import { readSettings } from "../../config/settings.js";
13
13
  import { repoForOrigin, selectRepoAsset } from "../workspace/assets.js";
14
14
  import { CliError } from "../../errors.js";
15
+ import { inputFile } from "../../shared/files.js";
15
16
  /** CLI hook test policy caps each input/output stream at one MiB. */
16
17
  const HOOK_IO_LIMIT_BYTES = 1048576;
17
18
  /** CLI hook test policy defaults to ten seconds. */
@@ -61,11 +62,17 @@ export async function testHook(name, origin, options, runtime) {
61
62
  if (!handler) {
62
63
  throw new CliError(`This event has no command ${options.handler}. Choose 1 to ${handlers.length}.`);
63
64
  }
64
- const input = await readFile(localPath(options.input, runtime));
65
+ const inputPath = localPath(options.input, runtime);
66
+ const input = await inputFile(inputPath);
65
67
  if (input.length > HOOK_IO_LIMIT_BYTES) {
66
68
  throw new CliError("The --input file is over 1 MiB.");
67
69
  }
68
- JSON.parse(input.toString("utf8"));
70
+ try {
71
+ JSON.parse(input.toString("utf8"));
72
+ }
73
+ catch (error) {
74
+ throw new CliError(`${inputPath} isn't valid JSON. --input takes the JSON event the tool would send the Hook.`, undefined, { cause: error });
75
+ }
69
76
  const timeout = options.timeout ?? handler.timeout ?? DEFAULT_HOOK_TIMEOUT_SECONDS;
70
77
  if (!Number.isFinite(timeout) ||
71
78
  timeout <= 0 ||
@@ -80,39 +87,32 @@ export async function testHook(name, origin, options, runtime) {
80
87
  detached: !isWindows(runtime.platform),
81
88
  windowsHide: true,
82
89
  });
83
- let stdout = "";
84
- let stderr = "";
85
- let length = 0;
86
90
  let timedOut = false;
91
+ let overLimit = false;
87
92
  const stop = () => stopProcessTree(child, runtime);
88
93
  const timer = setTimeout(() => {
89
94
  timedOut = true;
90
95
  stop();
91
96
  }, timeout * MILLISECONDS_PER_SECOND);
92
- for (const [stream, append] of [
93
- [
94
- child.stdout,
95
- (text) => {
96
- stdout += text;
97
- },
98
- ],
99
- [
100
- child.stderr,
101
- (text) => {
102
- stderr += text;
103
- },
104
- ],
105
- ]) {
97
+ // Bytes are kept and decoded once at the end, so a character split across
98
+ // chunks survives; each stream has its own limit.
99
+ const collect = (stream) => {
100
+ const chunks = [];
101
+ let length = 0;
106
102
  stream.on("data", (chunk) => {
107
103
  length += chunk.length;
108
104
  if (length > HOOK_IO_LIMIT_BYTES) {
105
+ overLimit = true;
109
106
  stop();
110
107
  }
111
108
  else {
112
- append(chunk.toString());
109
+ chunks.push(chunk);
113
110
  }
114
111
  });
115
- }
112
+ return () => Buffer.concat(chunks).toString("utf8");
113
+ };
114
+ const stdout = collect(child.stdout);
115
+ const stderr = collect(child.stderr);
116
116
  child.stdin.on("error", () => undefined);
117
117
  child.stdin.end(input);
118
118
  try {
@@ -120,16 +120,16 @@ export async function testHook(name, origin, options, runtime) {
120
120
  child.once("error", reject);
121
121
  child.once("close", (code) => resolve(code ?? 1));
122
122
  });
123
- if (length > HOOK_IO_LIMIT_BYTES) {
124
- throw new CliError("The Hook printed more than 1 MiB.");
123
+ if (overLimit) {
124
+ throw new CliError("The Hook printed more than 1 MiB to stdout or stderr.");
125
125
  }
126
126
  return {
127
127
  harness: options.harness,
128
128
  event,
129
129
  exitCode,
130
130
  timedOut,
131
- stdout,
132
- stderr,
131
+ stdout: stdout(),
132
+ stderr: stderr(),
133
133
  };
134
134
  }
135
135
  finally {
@@ -12,7 +12,7 @@ import { asRecord, isRecord } from "../../shared/values.js";
12
12
  * What imported Hook commands use for the installed package folder; BarnDog
13
13
  * binds it when installing.
14
14
  */
15
- const ROOT_TOKEN = "${BARNDOG_HOOK_ROOT}";
15
+ export const ROOT_TOKEN = "${BARNDOG_HOOK_ROOT}";
16
16
  /** A link to a folder or file narrows everything to it; the rest of the repo is ignored. */
17
17
  const inScope = (remote, path) => !remote.path || path === remote.path || path.startsWith(`${remote.path}/`);
18
18
  /** Whether the folder or file the link pointed at is in the repo at all. */
@@ -41,6 +41,14 @@ async function readSources(folder) {
41
41
  return ((await readJsonIfExists(localWorkspaceFiles(folder).sources, sourcesSchema)) ?? { imports: [] });
42
42
  }
43
43
  const writeSources = (folder, sources) => writeAtomic(localWorkspaceFiles(folder).sources, JSON.stringify(sources, null, 2) + "\n", { mode: POSIX_MODE.regularFile });
44
+ /** Stops following a repository for an asset whose local folder is gone. */
45
+ export async function forgetImport(folder, kind, name) {
46
+ const sources = await readSources(folder);
47
+ const kept = sources.imports.filter((entry) => entry.kind !== kind || entry.name !== name);
48
+ if (kept.length !== sources.imports.length) {
49
+ await writeSources(folder, { ...sources, imports: kept });
50
+ }
51
+ }
44
52
  /** The repository an asset still follows, or null for a fork or one made here. */
45
53
  export async function importedFrom(kind, name, runtime) {
46
54
  const { home } = runtime;
@@ -105,9 +113,12 @@ export async function saveImported(input, runtime) {
105
113
  await writePackage(target, input.entries, runtime);
106
114
  // Read back, so Windows (no executable bits) records what an update will see.
107
115
  const fingerprint = packageFingerprint(await readDirectory(target, runtime));
116
+ // A record left by an earlier import of this name goes either way: a fork
117
+ // stops following its repository.
118
+ const sources = await readSources(workspace.path);
119
+ const before = sources.imports.length;
120
+ sources.imports = sources.imports.filter((entry) => !(entry.kind === input.kind && entry.name === input.name));
108
121
  if (input.mode !== "fork") {
109
- const sources = await readSources(workspace.path);
110
- sources.imports = sources.imports.filter((entry) => !(entry.kind === input.kind && entry.name === input.name));
111
122
  sources.imports.push({
112
123
  kind: input.kind,
113
124
  name: input.name,
@@ -119,6 +130,8 @@ export async function saveImported(input, runtime) {
119
130
  ...(input.files ? { files: input.files } : {}),
120
131
  fingerprint,
121
132
  });
133
+ }
134
+ if (sources.imports.length !== before || input.mode !== "fork") {
122
135
  await writeSources(workspace.path, sources);
123
136
  }
124
137
  return { path: target };
@@ -1,3 +1,4 @@
1
+ import { gitAccessCommand } from "../../platform.js";
1
2
  import { POSIX_MODE } from "../../shared/constants.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { mkdir, rm } from "node:fs/promises";
@@ -94,7 +95,7 @@ export async function fetchRemote(location, options, use, runtime) {
94
95
  }
95
96
  catch (error) {
96
97
  if (error instanceof GitError) {
97
- throw new CliError(`Can't read ${location.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine.`, `git clone ${location.url}`, { cause: error });
98
+ throw new CliError(`Can't read ${location.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine.`, gitAccessCommand(location.url, runtime.platform), { cause: error });
98
99
  }
99
100
  throw error;
100
101
  }
@@ -1,17 +1,31 @@
1
1
  import { basename } from "node:path";
2
- import { readSettings, SetupRequiredError } from "../../config/settings.js";
2
+ import { readSettings, SetupRequiredError, } from "../../config/settings.js";
3
3
  import { selectionState } from "../../config/environment.js";
4
4
  import { readState } from "../../config/state.js";
5
5
  import { treeFingerprint } from "../workspace/tree.js";
6
6
  import { linkTarget } from "../environment/transaction.js";
7
7
  import { environmentCatalog } from "../server/catalog.js";
8
8
  import { openRepoSource } from "../workspace/workspace-source.js";
9
- import { localOverlay, mergeLocalCatalog } from "../workspace/overlay.js";
9
+ import { localOverlay, mergeLocalCatalog, moveDestination, readMoved, withOverlay, } from "../workspace/overlay.js";
10
+ import { cloudSource } from "../workspace/cloud-source.js";
11
+ import { secretRefs } from "../../harnesses/formats.js";
12
+ import { missingValues } from "../secrets/index.js";
13
+ import { keptValues } from "../environment/kept-values.js";
10
14
  import { resolveAssets } from "../asset-selection/index.js";
11
15
  import { installedName, resolveClashes } from "../environment/names.js";
12
16
  import { originLabel, scopes } from "../server/origin.js";
13
17
  import { isAssetKind } from "../asset-kinds/index.js";
14
18
  import { isHarness } from "../../harnesses/registry.js";
19
+ /** Local assets still moving to the shared workspace; none without a local folder. */
20
+ async function pendingMoves(settings) {
21
+ const folder = settings.localWorkspace?.path;
22
+ const records = folder ? await readMoved(folder) : [];
23
+ return records.map((entry) => ({
24
+ kind: entry.kind,
25
+ name: entry.name,
26
+ to: moveDestination(entry),
27
+ }));
28
+ }
15
29
  /** What is selected and what is actually installed on this machine. */
16
30
  /** The state of a selected asset; the first that applies wins. */
17
31
  function inventoryState(asset) {
@@ -36,11 +50,42 @@ function leftoverState(modified, offline) {
36
50
  }
37
51
  return offline ? "installed" : "removing";
38
52
  }
53
+ /**
54
+ * Finds an MCP server's variables with no value here, reading its definition
55
+ * from the same sources the inventory's catalog came from.
56
+ */
57
+ function variableCheck(input) {
58
+ const { settings, repo, overlay, runtime } = input;
59
+ const conn = settings.connection;
60
+ const primary = repo ?? (conn ? cloudSource(conn, runtime) : undefined);
61
+ const source = primary && overlay ? withOverlay(primary, overlay) : primary;
62
+ let kept;
63
+ return async ({ asset, enabled }) => {
64
+ if (!input.wanted || !source || asset.kind !== "mcp") {
65
+ return {};
66
+ }
67
+ // Read once, and only when some server needs checking.
68
+ kept ??= keptValues(runtime);
69
+ const values = (await kept).servers[asset.id] ?? {};
70
+ const definition = await source.mcpDefinition(asset);
71
+ const variables = [
72
+ ...new Set(Object.values(secretRefs(definition)).map((ref) => ref.secretRef)),
73
+ ];
74
+ return {
75
+ variables,
76
+ ...(enabled
77
+ ? {
78
+ unsetVariables: missingValues(definition, values, runtime.env).map((missing) => missing.variable),
79
+ }
80
+ : {}),
81
+ };
82
+ };
83
+ }
39
84
  /**
40
85
  * Compares configured selections, catalog and installed files to report status;
41
86
  * unreachable sources fall back to local state.
42
87
  */
43
- export async function inventory(runtime) {
88
+ export async function inventory(runtime, options = {}) {
44
89
  const { home } = runtime;
45
90
  const settings = await readSettings(home);
46
91
  if (!settings) {
@@ -91,6 +136,13 @@ export async function inventory(runtime) {
91
136
  const catalog = overlay
92
137
  ? await mergeLocalCatalog(primaryCatalog, overlay)
93
138
  : primaryCatalog;
139
+ const variablesOf = variableCheck({
140
+ wanted: Boolean(options.checkVariables),
141
+ settings,
142
+ repo,
143
+ overlay,
144
+ runtime,
145
+ });
94
146
  const selection = selectionState(settings);
95
147
  const effective = resolveAssets(catalog, selection);
96
148
  const outcome = await resolveClashes(effective.assets.flatMap(({ asset, enabled }) => {
@@ -144,6 +196,7 @@ export async function inventory(runtime) {
144
196
  ...links.map((l) => l.target),
145
197
  ...new Set(entries.map((n) => `${n.file} (${n.key})`)),
146
198
  ],
199
+ ...(await variablesOf(entry)),
147
200
  });
148
201
  }
149
202
  const visible = await loadScopes();
@@ -209,5 +262,6 @@ export async function inventory(runtime) {
209
262
  knowledge: !!(conn || repo) && settings.knowledge !== false,
210
263
  offline,
211
264
  items,
265
+ moving: await pendingMoves(settings),
212
266
  };
213
267
  }