barndog 0.1.0 → 0.2.0

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 (173) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +24 -11
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,122 +1,77 @@
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 { adoptMoved, localOverlay } from "../workspace/overlay.js";
13
+ import { openWorkspaceSource } from "../workspace/workspace-source.js";
14
+ import { locked, transact } from "./transaction.js";
15
+ import { assertInstalledUntouched, linkWrites, nativeWrites, entryNames, stateText, treeWrites, } from "./writes.js";
16
+ import { fileText } from "../../shared/files.js";
17
+ import { barndogPaths, localWorkspaceFiles } from "../../config/paths.js";
41
18
  /** 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 ?? []) : []);
19
+ export async function installedNames(runtime) {
20
+ const { home } = runtime;
21
+ const { links, native } = await readState(home);
47
22
  return (id) => heldName(id, links, native);
48
23
  }
49
- function inside(parent, child) {
50
- const path = relative(parent, child);
51
- return (!path ||
52
- (!path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path)));
53
- }
54
24
  /** The CLI registers a terminal prompt here; library callers default to skipping. */
55
25
  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));
26
+ /**
27
+ * Locks the environment, plans harness updates and applies journaled writes;
28
+ * dry runs return planned events.
29
+ */
30
+ export async function synchronize(configPath, runtime, override, options = {}) {
31
+ runtime = { ...runtime, home: resolve(runtime.cwd, runtime.home) };
32
+ const { home } = runtime;
33
+ return locked(runtime, async () => {
34
+ const path = resolve(runtime.cwd, configPath ?? barndogPaths(home).settings);
72
35
  const settings = override ?? (await readSettings(home, path));
73
- if (!settings)
36
+ if (!settings) {
74
37
  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
38
  }
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");
39
+ assertSupportedConfigHomes(settings.harnesses, runtime);
40
+ const stateFile = barndogPaths(home).state;
41
+ const rawState = await fileText(stateFile);
42
+ const before = await readState(home);
43
+ const { native: oldNative, installed: installedState } = before;
94
44
  let selection = selectionState(settings);
95
- const followNotices = settings.version === 2 && settings.localWorkspace && !options.dryRun
96
- ? await followImports(settings.localWorkspace.path, options.refresh ?? "always").catch(() => [])
45
+ const local = settings.localWorkspace;
46
+ const followNotices = local && !options.dryRun
47
+ ? await followImports(local.path, options.refresh ?? "always", runtime).catch((error) => [
48
+ `Imported assets weren't checked for updates, because ${localWorkspaceFiles(local.path).sources} couldn't be read: ${friendlyMessage(error)}`,
49
+ ])
97
50
  : [];
98
51
  const source = options.source ??
99
- openWorkspaceSource(settings, home, {
52
+ openWorkspaceSource(settings, runtime, {
100
53
  refresh: options.refresh,
101
54
  });
102
55
  if (!source &&
103
- (selection.subscriptions.length || selection.individualAssetIds.length))
104
- throw new Error("Remote selections require a connection");
56
+ (selection.subscriptions.length || selection.individualAssetIds.length)) {
57
+ throw new CliError("Your selection includes assets from a BarnDog server, but this machine isn't connected to one.", "barndog init");
58
+ }
105
59
  const catalog = source
106
60
  ? (options.catalog ?? (await source.catalog()))
107
61
  : { assets: [], distributions: [] };
108
- const overlay = localOverlay(settings, home);
109
- if (overlay)
62
+ const overlay = localOverlay(settings, runtime);
63
+ if (overlay) {
110
64
  selection = await adoptMoved(overlay, catalog, selection, !options.dryRun);
65
+ }
111
66
  const invalid = source
112
67
  ? await source.invalidAssets()
113
68
  : new Map();
114
69
  let effective = resolveAssets(catalog, selection);
115
- if (effective.diagnostics.length)
70
+ if (effective.diagnostics.length) {
116
71
  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 = [
72
+ }
73
+ const events = [
118
74
  ...new Set([
119
- ...adoptionNotices,
120
75
  ...followNotices,
121
76
  ...(source?.notices() ?? []),
122
77
  ...((await source?.warnings?.()) ?? []),
@@ -125,423 +80,97 @@ export async function synchronize(configPath, home = homedir(), override, option
125
80
  ].map((message) => ({
126
81
  type: "notice",
127
82
  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)));
83
+ }));
84
+ const settled = await settleNames({
85
+ assets: effective.assets,
86
+ invalid,
87
+ state: before,
88
+ savedNames: settings.localNames ?? {},
89
+ resolver: options.prompt === false || options.dryRun
90
+ ? undefined
91
+ : (options.resolveClash ?? clashPrompt.resolver),
92
+ }, runtime);
93
+ const { vanished, localNames, skipped } = settled;
94
+ events.push(...settled.events);
205
95
  selection = {
206
96
  ...selection,
207
97
  disabledAssetIds: [
208
98
  ...new Set([
209
99
  ...selection.disabledAssetIds,
210
- ...outcome.disabledAssetIds.filter((id) => !localIds.has(id)),
100
+ ...settled.disabledAssetIds,
211
101
  ]),
212
102
  ],
213
103
  };
214
104
  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([
105
+ const staged = await stageAssets({
106
+ assets: effective.assets,
107
+ invalid,
108
+ vanished,
109
+ skipped,
110
+ localNames,
111
+ state: before,
112
+ source,
113
+ harnesses: settings.harnesses,
114
+ runtime,
115
+ });
116
+ const { links: desired, native, trees } = staged;
117
+ events.push(...staged.events);
118
+ native.push(...startupEntries(settings, runtime, { knowledge: !!source }));
119
+ const nativeName = entryNames([
387
120
  ...installedState.map((t) => [t.id, basename(t.path)]),
388
121
  // Still known after being deselected, unlike the effective set below.
389
122
  ...catalog.assets.map((a) => [a.id, a.name]),
390
123
  ...effective.assets.map((e) => [e.asset.id, e.asset.name]),
391
124
  ]);
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,
125
+ await assertInstalledUntouched(installedState, settings, runtime);
126
+ const installedFolders = await treeWrites(installedState, trees, runtime);
127
+ const links = await linkWrites(before.links, desired, installedFolders.updated);
128
+ const settingsFiles = await nativeWrites(oldNative, native, {
129
+ trees,
130
+ updated: installedFolders.updated,
131
+ nameOf: nativeName,
132
+ platform: runtime.platform,
521
133
  });
134
+ events.push(...links.events, ...settingsFiles.events);
135
+ const writes = [
136
+ ...installedFolders.writes,
137
+ ...links.writes,
138
+ ...settingsFiles.writes,
139
+ {
140
+ kind: "file",
141
+ path: stateFile,
142
+ before: rawState,
143
+ after: stateText({ links: desired, native, trees }),
144
+ },
145
+ ];
522
146
  // Explicit overrides are one-shot delivery inputs, never a change to default preferences.
523
147
  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)
148
+ const next = source
149
+ ? withSelection(settings, selection)
150
+ : { ...settings };
151
+ if (Object.keys(localNames).length) {
527
152
  next.localNames = localNames;
528
- else
153
+ }
154
+ else {
529
155
  delete next.localNames;
156
+ }
530
157
  writes.push({
531
158
  kind: "file",
532
- path: settingsPath(home),
533
- before: await fileText(settingsPath(home)),
534
- after: stringify(next),
159
+ path: barndogPaths(home).settings,
160
+ before: await fileText(barndogPaths(home).settings),
161
+ after: settingsText(next),
535
162
  });
536
163
  }
537
- if (options.dryRun)
164
+ if (options.dryRun) {
538
165
  return events;
539
- await transact(home, writes, source?.journal, options.checkpoint);
166
+ }
167
+ await transact(runtime, writes, source?.journal, options.checkpoint);
540
168
  // 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);
169
+ if (source) {
170
+ for (const key of [source.cacheKey, ...(source.extraCacheKeys ?? [])]) {
171
+ await pruneCache(key, runtime, new Set(trees.map((tree) => dirname(tree.source)))).catch(() => 0);
172
+ }
173
+ }
544
174
  return events;
545
175
  });
546
176
  }
547
- export { atomicFile };