barndog 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,123 +1,88 @@
1
- import { homedir } from "node:os";
2
- import { basename, dirname, isAbsolute, join, relative, resolve, sep, } from "node:path";
3
- import { realpath, readFile } from "node:fs/promises";
4
- import { fileURLToPath } from "node:url";
5
- import { stringify, parse } from "yaml";
6
- import { z } from "zod";
7
- import { hookManifestSchema } from "@barndog-ai/api-contract";
1
+ import { basename, dirname, resolve } from "node:path";
8
2
  import { readState } from "../../config/state.js";
9
- import { readSettings, settingsPath, SetupRequiredError, upgradeSettings, } from "../../config/settings.js";
10
- import { packageFingerprint } from "@barndog-ai/api-contract/package";
11
- import { CliError } from "../../errors.js";
12
- import { desiredEntries, installedPath, installedRoot, treeFingerprint, } from "./installed.js";
13
- import { installedName, originLabel, hookFolders, resolveClashes, } from "./names.js";
3
+ import { readSettings, settingsText, SetupRequiredError, } from "../../config/settings.js";
4
+ import { CliError, friendlyMessage } from "../../errors.js";
14
5
  import { selectionState, withSelection } from "../../config/environment.js";
15
- import { harnesses, skillDirectory } from "../../harnesses/registry.js";
16
- import { validateSelection, validateSkillSource, } from "../skills/validation.js";
6
+ import { heldName, settleNames } from "./settle-names.js";
7
+ import { stageAssets } from "./stage.js";
8
+ import { assertSupportedConfigHomes, startupEntries } from "./own-entries.js";
17
9
  import { resolveAssets } from "../asset-selection/index.js";
18
- import { pruneCache } from "./packages.js";
19
- import { adoptLinkedFolders, followImports } from "../imports/local.js";
20
- import { adoptMoved, localOverlay } from "../git-workspace/overlay.js";
21
- import { openWorkspaceSource } from "./workspace-source.js";
22
- import { nativeFile, patchNative, } from "../native/configuration.js";
23
- import { hookEntries, mcpEntry, runtimeRequirements, shellQuote, } from "../native/adapters.js";
24
- import { atomicFile, fileText, linkTarget, locked, transact, } from "./transaction.js";
25
- const nativeSchema = z.array(z
26
- .object({
27
- id: z.string(),
28
- kind: z.enum(["mcp", "hook", "knowledge", "sync"]),
29
- harness: z.enum(harnesses),
30
- file: z.string(),
31
- key: z.string(),
32
- value: z.record(z.string(), z.unknown()),
33
- })
34
- .strict());
35
- /** The name an asset is installed under right now, whatever settings say it should be. */
36
- function heldName(id, links, native) {
37
- const held = links.find((link) => link.id === id)?.target ??
38
- native.find((entry) => entry.id === id && entry.kind === "mcp")?.key;
39
- return held ? basename(held) : undefined;
40
- }
10
+ import { pruneCache } from "../workspace/packages.js";
11
+ import { followImports } from "../imports/local.js";
12
+ import { localOverlay } from "../workspace/overlay.js";
13
+ import { openWorkspaceSource } from "../workspace/workspace-source.js";
14
+ import { finishMoves } from "./moves.js";
15
+ import { readSecrets } from "../secrets/index.js";
16
+ import { locked, transact } from "./transaction.js";
17
+ import { assertInstalledUntouched, linkWrites, nativeWrites, entryNames, stateText, treeWrites, } from "./writes.js";
18
+ import { fileText } from "../../shared/files.js";
19
+ import { barndogPaths, localWorkspaceFiles } from "../../config/paths.js";
41
20
  /** Looks up installed names from state, for checks made outside a sync. */
42
- export async function installedNames(home) {
43
- const path = join(home, ".barndog/state.json");
44
- const raw = await fileText(path);
45
- const { links } = await readState(path, home);
46
- const native = nativeSchema.parse(raw ? (JSON.parse(raw).native ?? []) : []);
21
+ export async function installedNames(runtime) {
22
+ const { home } = runtime;
23
+ const { links, native } = await readState(home);
47
24
  return (id) => heldName(id, links, native);
48
25
  }
49
- function inside(parent, child) {
50
- const path = relative(parent, child);
51
- return (!path ||
52
- (!path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path)));
53
- }
54
26
  /** The CLI registers a terminal prompt here; library callers default to skipping. */
55
27
  export const clashPrompt = {};
56
- const installedSchema = z.array(z
57
- .object({
58
- id: z.string(),
59
- kind: z.enum(["skill", "hook"]),
60
- path: z.string(),
61
- fingerprint: z.string(),
62
- versionId: z.string().optional(),
63
- })
64
- .strict());
65
- export async function synchronize(configPath, home = homedir(), override, options = {}) {
66
- home = resolve(home);
67
- return locked(home, async () => {
68
- const adoptionNotices = configPath || override || options.dryRun
69
- ? []
70
- : await adoptLinkedFolders(home);
71
- const path = resolve(configPath ?? settingsPath(home));
28
+ /**
29
+ * Locks the environment, plans harness updates and applies journaled writes;
30
+ * dry runs return planned events.
31
+ */
32
+ export async function synchronize(configPath, runtime, override, options = {}) {
33
+ runtime = { ...runtime, home: resolve(runtime.cwd, runtime.home) };
34
+ const { home } = runtime;
35
+ return locked(runtime, async () => {
36
+ const path = resolve(runtime.cwd, configPath ?? barndogPaths(home).settings);
72
37
  const settings = override ?? (await readSettings(home, path));
73
- if (!settings)
38
+ if (!settings) {
74
39
  throw new SetupRequiredError();
75
- if (home === homedir()) {
76
- if (settings.harnesses.includes("claude") &&
77
- process.env.CLAUDE_CONFIG_DIR)
78
- throw new Error("Custom CLAUDE_CONFIG_DIR is not supported by this delivery adapter; use the standard user configuration location");
79
- if (settings.harnesses.includes("codex") &&
80
- process.env.CODEX_HOME &&
81
- resolve(process.env.CODEX_HOME) !== join(home, ".codex"))
82
- throw new Error("Custom CODEX_HOME is not supported by this delivery adapter; use ~/.codex");
83
40
  }
84
- const stateFile = join(home, ".barndog/state.json"), rawState = await fileText(stateFile);
85
- const before = await readState(stateFile, home);
86
- const oldNative = nativeSchema.parse(rawState ? (JSON.parse(rawState).native ?? []) : []);
87
- for (const entry of oldNative)
88
- if (entry.file !== nativeFile(entry.harness, entry.kind, home))
89
- throw new Error("Invalid native installation state");
90
- const installedState = installedSchema.parse(rawState ? (JSON.parse(rawState).installed ?? []) : []);
91
- for (const entry of installedState)
92
- if (dirname(entry.path) !== installedRoot(home, entry.kind))
93
- throw new Error("Invalid installed package state");
41
+ assertSupportedConfigHomes(settings.harnesses, runtime);
42
+ const stateFile = barndogPaths(home).state;
43
+ const rawState = await fileText(stateFile);
44
+ const before = await readState(home);
45
+ const { native: oldNative, installed: installedState } = before;
94
46
  let selection = selectionState(settings);
95
- const followNotices = settings.version === 2 && settings.localWorkspace && !options.dryRun
96
- ? await followImports(settings.localWorkspace.path, options.refresh ?? "always").catch(() => [])
47
+ const local = settings.localWorkspace;
48
+ const followNotices = local && !options.dryRun
49
+ ? await followImports(local.path, options.refresh ?? "always", runtime).catch((error) => [
50
+ `Imported assets weren't checked for updates, because ${localWorkspaceFiles(local.path).sources} couldn't be read: ${friendlyMessage(error)}`,
51
+ ])
97
52
  : [];
98
- const source = options.source ??
99
- openWorkspaceSource(settings, home, {
53
+ let source = options.source ??
54
+ openWorkspaceSource(settings, runtime, {
100
55
  refresh: options.refresh,
101
56
  });
102
57
  if (!source &&
103
- (selection.subscriptions.length || selection.individualAssetIds.length))
104
- throw new Error("Remote selections require a connection");
105
- const catalog = source
58
+ (selection.subscriptions.length || selection.individualAssetIds.length)) {
59
+ throw new CliError("Your selection includes assets from a BarnDog server, but this machine isn't connected to one.", "barndog init");
60
+ }
61
+ let catalog = source
106
62
  ? (options.catalog ?? (await source.catalog()))
107
63
  : { assets: [], distributions: [] };
108
- const overlay = localOverlay(settings, home);
109
- if (overlay)
110
- selection = await adoptMoved(overlay, catalog, selection, !options.dryRun);
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);
74
+ const overlay = localOverlay(settings, runtime);
111
75
  const invalid = source
112
76
  ? await source.invalidAssets()
113
77
  : new Map();
114
78
  let effective = resolveAssets(catalog, selection);
115
- if (effective.diagnostics.length)
79
+ if (effective.diagnostics.length) {
116
80
  throw new CliError(`Some selected assets or scopes are no longer available; nothing was changed: ${effective.diagnostics.map((d) => (d.type === "missing-asset" ? d.assetId : `${d.scope.type}/${d.scope.id}`)).join(", ")}`, "barndog status");
117
- const desired = [], native = [], trees = [], events = [
81
+ }
82
+ const events = [
118
83
  ...new Set([
119
- ...adoptionNotices,
120
84
  ...followNotices,
85
+ ...moves.notices,
121
86
  ...(source?.notices() ?? []),
122
87
  ...((await source?.warnings?.()) ?? []),
123
88
  ...((await overlay?.warnings?.()) ?? []),
@@ -125,423 +90,98 @@ export async function synchronize(configPath, home = homedir(), override, option
125
90
  ].map((message) => ({
126
91
  type: "notice",
127
92
  message,
128
- })), names = new Set(), ids = new Set();
129
- const locals = [];
130
- for (const local of settings.skills) {
131
- if (settings.version === 2 && "kind" in local && local.kind === "api")
132
- continue;
133
- validateSelection(local);
134
- if (ids.has(local.id))
135
- throw new Error(`Duplicate Skill ID: ${local.id}`);
136
- ids.add(local.id);
137
- if (!local.enabled) {
138
- events.push({ type: "disabled", id: local.id });
139
- continue;
140
- }
141
- const root = await realpath(resolve(dirname(path), local.source));
142
- locals.push({
143
- id: local.id,
144
- root,
145
- name: (await validateSkillSource(root)).name,
146
- });
147
- }
148
- // Installed names share one namespace per kind; resolve clashes before staging.
149
- const owned = (id) => before.links.some((link) => link.id === id) ||
150
- oldNative.some((entry) => entry.id === id && entry.kind === "mcp");
151
- // An invalid asset can only stay installed while its own folder is still there.
152
- const vanished = new Set();
153
- for (const entry of installedState) {
154
- if (!invalid.has(entry.id))
155
- continue;
156
- const actual = await treeFingerprint(entry.path);
157
- const shared = installedState.some((other) => other.id !== entry.id && other.path === entry.path);
158
- if (actual === null || (shared && actual !== entry.fingerprint))
159
- vanished.add(entry.id);
160
- }
161
- const savedNames = settings.version === 2 ? (settings.localNames ?? {}) : {};
162
- // An invalid asset stays under the name it's installed at, whatever it was renamed to since.
163
- const heldNames = new Map();
164
- for (const { asset, enabled } of effective.assets) {
165
- if (!enabled || !invalid.has(asset.id) || vanished.has(asset.id))
166
- continue;
167
- const held = heldName(asset.id, before.links, oldNative);
168
- if (held)
169
- heldNames.set(asset.id, held);
170
- }
171
- const outcome = await resolveClashes([
172
- ...locals.map((local) => ({
173
- id: local.id,
174
- kind: "skill",
175
- name: local.name,
176
- origin: { type: "local", slug: "folder" },
177
- installed: owned(local.id),
178
- renamable: false,
179
- })),
180
- ...effective.assets
181
- .filter((entry) => entry.enabled &&
182
- entry.asset.kind !== "hook" &&
183
- (!invalid.has(entry.asset.id) ||
184
- (owned(entry.asset.id) && !vanished.has(entry.asset.id))))
185
- .map((entry) => ({
186
- id: entry.asset.id,
187
- kind: entry.asset.kind,
188
- name: entry.asset.name,
189
- origin: entry.asset.origin,
190
- installed: owned(entry.asset.id),
191
- renamable: !invalid.has(entry.asset.id),
192
- })),
193
- ], { ...savedNames, ...Object.fromEntries(heldNames) }, options.prompt === false || options.dryRun
194
- ? undefined
195
- : (options.resolveClash ?? clashPrompt.resolver));
196
- const localNames = { ...outcome.localNames };
197
- for (const id of heldNames.keys()) {
198
- if (savedNames[id] === undefined)
199
- delete localNames[id];
200
- else
201
- localNames[id] = savedNames[id];
202
- }
203
- const localIds = new Set(locals.map((local) => local.id));
204
- const disabledLocals = new Set(outcome.disabledAssetIds.filter((id) => localIds.has(id)));
93
+ }));
94
+ const settled = await settleNames({
95
+ assets: effective.assets,
96
+ invalid,
97
+ state: before,
98
+ savedNames: settings.localNames ?? {},
99
+ resolver: options.prompt === false || options.dryRun
100
+ ? undefined
101
+ : (options.resolveClash ?? clashPrompt.resolver),
102
+ }, runtime);
103
+ const { vanished, localNames, skipped } = settled;
104
+ events.push(...settled.events);
205
105
  selection = {
206
106
  ...selection,
207
107
  disabledAssetIds: [
208
108
  ...new Set([
209
109
  ...selection.disabledAssetIds,
210
- ...outcome.disabledAssetIds.filter((id) => !localIds.has(id)),
110
+ ...settled.disabledAssetIds,
211
111
  ]),
212
112
  ],
213
113
  };
214
114
  effective = resolveAssets(catalog, selection);
215
- const skipped = new Set(outcome.skipped.map((clash) => clash.incoming.id));
216
- for (const clash of outcome.skipped)
217
- events.push({
218
- type: "clash",
219
- kind: clash.kind,
220
- name: clash.name,
221
- installed: {
222
- name: clash.installed.name,
223
- origin: originLabel(clash.installed.origin),
224
- },
225
- skipped: {
226
- name: clash.incoming.name,
227
- origin: originLabel(clash.incoming.origin),
228
- rename: clash.incomingRename,
229
- },
230
- });
231
- const addSkill = (id, source, name) => {
232
- if (names.has(name))
233
- throw new CliError(`Two enabled Skills are named ${name}`, "barndog doctor");
234
- names.add(name);
235
- for (const harness of settings.harnesses) {
236
- const target = resolve(skillDirectory(harness, home), name);
237
- if (inside(source, target) || inside(target, source))
238
- throw new Error(`Source overlaps installation: ${source}`);
239
- desired.push({ id, harness, source, target });
240
- }
241
- };
242
- for (const local of locals) {
243
- if (skipped.has(local.id) || disabledLocals.has(local.id))
244
- continue;
245
- addSkill(local.id, local.root, local.name);
246
- }
247
- const stage = async (id, kind, name, source, rename, versionId) => {
248
- const path = installedPath(home, kind, name);
249
- trees.push({
250
- id,
251
- kind,
252
- path,
253
- source,
254
- rename,
255
- versionId,
256
- fingerprint: packageFingerprint(await desiredEntries(source, rename)),
257
- });
258
- return path;
259
- };
260
- const folders = hookFolders(effective.assets
261
- .filter(({ asset, enabled }) => enabled &&
262
- asset.kind === "hook" &&
263
- !vanished.has(asset.id) &&
264
- (!invalid.has(asset.id) ||
265
- installedState.some((tree) => tree.id === asset.id)))
266
- .map(({ asset }) => {
267
- const tree = installedState.find((entry) => entry.id === asset.id);
268
- const folder = tree && basename(tree.path);
269
- return {
270
- ...asset,
271
- ...(folder
272
- ? invalid.has(asset.id)
273
- ? { kept: folder }
274
- : { current: folder }
275
- : {}),
276
- };
277
- }), localNames);
278
- for (const chosen of effective.assets) {
279
- const ref = chosen.asset;
280
- if (ids.has(ref.id))
281
- throw new Error("Remote asset ID conflicts with a local selection");
282
- ids.add(ref.id);
283
- if (!chosen.enabled) {
284
- events.push({ type: "disabled", id: ref.id });
285
- continue;
286
- }
287
- if (skipped.has(ref.id))
288
- continue;
289
- const reason = invalid.get(ref.id);
290
- if (reason) {
291
- // Nothing validates a repo before merge, so a bad change must not uninstall what works.
292
- events.push({
293
- type: "invalid",
294
- kind: ref.kind,
295
- name: ref.name,
296
- reason,
297
- });
298
- if (vanished.has(ref.id))
299
- continue;
300
- for (const link of before.links.filter((l) => l.id === ref.id)) {
301
- desired.push(link);
302
- names.add(basename(link.target));
303
- }
304
- native.push(...oldNative.filter((entry) => entry.id === ref.id));
305
- const tree = installedState.find((entry) => entry.id === ref.id);
306
- if (tree)
307
- trees.push({
308
- id: tree.id,
309
- kind: tree.kind,
310
- path: tree.path,
311
- source: tree.path,
312
- rename: null,
313
- fingerprint: tree.fingerprint,
314
- versionId: tree.versionId ?? ref.publishedVersion,
315
- });
316
- continue;
317
- }
318
- const name = installedName(ref, localNames);
319
- if (ref.kind === "skill") {
320
- const cache = await source.skillOrHookPackage("skill", ref);
321
- addSkill(ref.id, await stage(ref.id, "skill", name, cache, name === ref.name ? null : name, ref.publishedVersion), name);
322
- }
323
- else if (ref.kind === "mcp") {
324
- const definition = await source.mcpDefinition(ref);
325
- for (const harness of settings.harnesses)
326
- native.push(mcpEntry(harness, { id: ref.id, name }, definition, home));
327
- }
328
- else {
329
- const cache = await source.skillOrHookPackage("hook", ref);
330
- const manifest = hookManifestSchema.parse(parse(await readFile(join(cache, "hook.yaml"), "utf8")));
331
- // Hook folders are internal, so collisions are settled without prompting.
332
- const root = await stage(ref.id, "hook", folders.get(ref.id), cache, null, ref.publishedVersion);
333
- for (const harness of settings.harnesses) {
334
- const implementation = manifest.implementations[harness];
335
- const reason = !implementation
336
- ? "No implementation for this harness"
337
- : await runtimeRequirements(harness, implementation.requirements);
338
- if (reason) {
339
- events.push({
340
- type: "unsupported",
341
- kind: "hook",
342
- harness,
343
- name: ref.name,
344
- reason,
345
- });
346
- continue;
347
- }
348
- native.push(...hookEntries(harness, ref.id, root, manifest, home));
349
- }
350
- }
351
- }
352
- if (source && (settings.version !== 2 || settings.knowledge !== false)) {
353
- const script = fileURLToPath(new URL("../knowledge/startup.js", import.meta.url));
354
- for (const harness of settings.harnesses) {
355
- const command = `${shellQuote(process.execPath)} ${shellQuote(script)} ${harness} ${shellQuote(home)}`;
356
- native.push({
357
- id: "barndog-knowledge-index",
358
- kind: "knowledge",
359
- harness,
360
- file: nativeFile(harness, "knowledge", home),
361
- key: harness === "cursor" ? "sessionStart" : "SessionStart",
362
- value: harness === "cursor"
363
- ? { command }
364
- : { hooks: [{ type: "command", command }] },
365
- });
366
- }
367
- }
368
- if (settings.version === 2 &&
369
- (settings.connection || settings.gitWorkspace || settings.localWorkspace)) {
370
- const script = fileURLToPath(new URL("../git-workspace/startup.js", import.meta.url));
371
- for (const harness of settings.harnesses) {
372
- const command = `${shellQuote(process.execPath)} ${shellQuote(script)} ${shellQuote(home)}`;
373
- native.push({
374
- id: "barndog-workspace-sync",
375
- kind: "sync",
376
- harness,
377
- file: nativeFile(harness, "sync", home),
378
- key: harness === "cursor" ? "sessionStart" : "SessionStart",
379
- value: harness === "cursor"
380
- ? { command }
381
- : { hooks: [{ type: "command", command }] },
382
- });
383
- }
384
- }
385
- // Hook registrations carry IDs; show the asset or folder name instead.
386
- const hookNames = new Map([
115
+ const staged = await stageAssets({
116
+ assets: effective.assets,
117
+ invalid,
118
+ vanished,
119
+ skipped,
120
+ localNames,
121
+ state: before,
122
+ source,
123
+ harnesses: settings.harnesses,
124
+ kept: await readSecrets(runtime),
125
+ runtime,
126
+ });
127
+ const { links: desired, native, trees } = staged;
128
+ events.push(...staged.events);
129
+ native.push(...startupEntries(settings, runtime, { knowledge: !!source }));
130
+ const nativeName = entryNames([
387
131
  ...installedState.map((t) => [t.id, basename(t.path)]),
388
132
  // Still known after being deselected, unlike the effective set below.
389
133
  ...catalog.assets.map((a) => [a.id, a.name]),
390
134
  ...effective.assets.map((e) => [e.asset.id, e.asset.name]),
391
135
  ]);
392
- const nativeName = (entry) => entry.kind === "mcp"
393
- ? entry.key
394
- : entry.kind === "knowledge"
395
- ? "knowledge index"
396
- : entry.kind === "sync"
397
- ? "workspace sync"
398
- : (hookNames.get(entry.id) ?? entry.id);
399
- const writes = [];
400
- for (const entry of installedState) {
401
- const actual = await treeFingerprint(entry.path);
402
- // Older versions could record two Hooks at one path; either copy is ours.
403
- if (actual !== null &&
404
- !installedState.some((other) => other.path === entry.path && other.fingerprint === actual))
405
- throw new CliError(`The installed copy at ${entry.path} was edited by hand. Syncing would overwrite those edits. ${settings.version === 2 &&
406
- settings.localWorkspace &&
407
- !settings.connection &&
408
- !settings.gitWorkspace
409
- ? "To keep them, copy that folder somewhere else first."
410
- : `To keep them, make an editable copy with \`barndog ${entry.kind === "skill" ? "skills" : "hooks"} pull\` first.`}`, `rm -rf ${shellQuote(entry.path)} && barndog sync`);
411
- }
412
- for (const treePath of new Set([
413
- ...installedState.map((entry) => entry.path),
414
- ...trees.map((tree) => tree.path),
415
- ])) {
416
- const next = trees.find((tree) => tree.path === treePath);
417
- writes.push({
418
- kind: "tree",
419
- path: treePath,
420
- before: await treeFingerprint(treePath),
421
- after: next?.fingerprint ?? null,
422
- source: next?.source ?? null,
423
- rename: next?.rename ?? null,
424
- });
425
- }
426
- const updated = new Set(writes
427
- .filter((w) => w.kind === "tree" &&
428
- w.before !== null &&
429
- w.after !== null &&
430
- w.before !== w.after)
431
- .map((w) => w.path));
432
- for (const link of before.links) {
433
- const actual = await linkTarget(link.target);
434
- if (actual !== null && actual !== link.source)
435
- throw new Error(`Managed link was changed externally: ${link.target}`);
436
- }
437
- for (const link of desired) {
438
- const actual = await linkTarget(link.target), old = before.links.find((l) => l.target === link.target);
439
- if (actual !== null && !old)
440
- throw new Error(`Existing unmanaged Skill: ${link.target}`);
441
- }
442
- for (const target of new Set([
443
- ...before.links.map((l) => l.target),
444
- ...desired.map((l) => l.target),
445
- ])) {
446
- const old = before.links.find((l) => l.target === target), next = desired.find((l) => l.target === target), actual = await linkTarget(target);
447
- if (old && (!next || next.id !== old.id))
448
- events.push({ type: "removed", link: old });
449
- if (next)
450
- events.push({
451
- type: actual === next.source && old?.id === next.id
452
- ? updated.has(next.source)
453
- ? "updated"
454
- : "unchanged"
455
- : old?.id === next.id
456
- ? "updated"
457
- : "installed",
458
- link: next,
459
- });
460
- writes.push({
461
- kind: "link",
462
- path: target,
463
- before: actual,
464
- after: next?.source ?? null,
465
- });
466
- }
467
- for (const file of new Set([
468
- ...oldNative.map((e) => e.file),
469
- ...native.map((e) => e.file),
470
- ])) {
471
- const old = oldNative.filter((e) => e.file === file), next = native.filter((e) => e.file === file), text = await fileText(file);
472
- writes.push({
473
- kind: "file",
474
- path: file,
475
- before: text,
476
- after: patchNative(text, old, next),
477
- });
478
- for (const entry of next)
479
- events.push({
480
- type: "native",
481
- action: old.some((e) => JSON.stringify(e) === JSON.stringify(entry))
482
- ? entry.kind === "hook" &&
483
- trees.some((t) => t.id === entry.id && updated.has(t.path))
484
- ? "updated"
485
- : "unchanged"
486
- : old.some((e) => e.id === entry.id && e.harness === entry.harness)
487
- ? "updated"
488
- : "installed",
489
- kind: entry.kind,
490
- harness: entry.harness,
491
- name: nativeName(entry),
492
- });
493
- for (const entry of old)
494
- if (!next.some((e) => JSON.stringify(e) === JSON.stringify(entry) ||
495
- (e.id === entry.id && e.harness === entry.harness)))
496
- events.push({
497
- type: "native",
498
- action: "removed",
499
- kind: entry.kind,
500
- harness: entry.harness,
501
- name: nativeName(entry),
502
- });
503
- }
504
- const nextState = JSON.stringify({
505
- version: 1,
506
- links: desired,
507
- native,
508
- installed: trees.map(({ id, kind, path, fingerprint, versionId }) => ({
509
- id,
510
- kind,
511
- path,
512
- fingerprint,
513
- versionId,
514
- })),
515
- }, null, 2) + "\n";
516
- writes.push({
517
- kind: "file",
518
- path: stateFile,
519
- before: rawState,
520
- after: nextState,
136
+ await assertInstalledUntouched(installedState, settings, runtime);
137
+ const installedFolders = await treeWrites(installedState, trees, runtime);
138
+ const links = await linkWrites(before.links, desired, installedFolders.updated);
139
+ const settingsFiles = await nativeWrites(oldNative, native, {
140
+ trees,
141
+ updated: installedFolders.updated,
142
+ nameOf: nativeName,
143
+ platform: runtime.platform,
521
144
  });
145
+ events.push(...links.events, ...settingsFiles.events);
146
+ const writes = [
147
+ ...installedFolders.writes,
148
+ ...links.writes,
149
+ ...settingsFiles.writes,
150
+ {
151
+ kind: "file",
152
+ path: stateFile,
153
+ before: rawState,
154
+ after: stateText({ links: desired, native, trees }),
155
+ },
156
+ ];
522
157
  // Explicit overrides are one-shot delivery inputs, never a change to default preferences.
523
158
  if (!configPath) {
524
- const next = upgradeSettings(source ? withSelection(settings, selection) : settings);
525
- next.skills = next.skills.map((skill) => disabledLocals.has(skill.id) ? { ...skill, enabled: false } : skill);
526
- if (Object.keys(localNames).length)
159
+ const next = source
160
+ ? withSelection(settings, selection)
161
+ : { ...settings };
162
+ if (Object.keys(localNames).length) {
527
163
  next.localNames = localNames;
528
- else
164
+ }
165
+ else {
529
166
  delete next.localNames;
167
+ }
530
168
  writes.push({
531
169
  kind: "file",
532
- path: settingsPath(home),
533
- before: await fileText(settingsPath(home)),
534
- after: stringify(next),
170
+ path: barndogPaths(home).settings,
171
+ before: await fileText(barndogPaths(home).settings),
172
+ after: settingsText(next),
535
173
  });
536
174
  }
537
- if (options.dryRun)
175
+ if (options.dryRun) {
538
176
  return events;
539
- await transact(home, writes, source?.journal, options.checkpoint);
177
+ }
178
+ await transact(runtime, writes, source?.journal, options.checkpoint);
540
179
  // Only versions the installed folders were just filled from are worth keeping.
541
- if (source)
542
- for (const key of [source.cacheKey, ...(source.extraCacheKeys ?? [])])
543
- await pruneCache(key, home, new Set(trees.map((tree) => dirname(tree.source)))).catch(() => 0);
180
+ if (source) {
181
+ for (const key of [source.cacheKey, ...(source.extraCacheKeys ?? [])]) {
182
+ await pruneCache(key, runtime, new Set(trees.map((tree) => dirname(tree.source)))).catch(() => 0);
183
+ }
184
+ }
544
185
  return events;
545
186
  });
546
187
  }
547
- export { atomicFile };