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,337 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import { homedir } from "node:os";
3
- import { basename } from "node:path";
4
- import { knowledgeIndexSchema, scopeSchema } from "@barndog-ai/api-contract";
5
- import { stringify } from "yaml";
6
- import { z } from "zod";
7
- import { readSettings, SetupRequiredError, } from "../../config/settings.js";
8
- import { CliError, friendlyMessage } from "../../errors.js";
9
- import { connection, matchesOrigin, selectOrigin, } from "../collaboration/remote.js";
10
- import { selectScope } from "../collaboration/workspace-git.js";
11
- import { renameSkillEntries } from "../environment/installed.js";
12
- import { originLabel } from "../environment/names.js";
13
- import { environmentCatalog, request } from "../environment/remote.js";
14
- import { synchronize } from "../environment/sync.js";
15
- import { locked } from "../environment/transaction.js";
16
- import { assetFolder, stableId } from "./format.js";
17
- import { checkRepositoryUrl, cloneOrigin, git } from "./git.js";
18
- import { connectGitWorkspace, createGitWorkspace, inspectRepository, } from "./setup.js";
19
- import { LoginRequiredError, normalizeServer } from "../auth/transport.js";
20
- import { connectionContext } from "../skills/remote.js";
21
- import { publishKnowledge, publishMcp, publishPackage } from "./migrate.js";
22
- import { readMoved, recordMoved } from "./overlay.js";
23
- import { commitFiles, openPullRequest, pushCommit } from "./publish.js";
24
- import { acceptedCommit, gitDirectory, gitRepoSource, localRepoSource, recordFetch, trackingRef, } from "./source.js";
25
- /** A one-off destination: nothing about this machine's own setup changes. */
26
- async function repoDestination(value, home) {
27
- const url = checkRepositoryUrl(await cloneOrigin(value));
28
- const head = await inspectRepository(url);
29
- return head
30
- ? connectGitWorkspace(url, head.branch, home)
31
- : createGitWorkspace(url, basename(url).replace(/\.git$/, "") || "Workspace", home);
32
- }
33
- async function serverDestination(value, home) {
34
- const server = normalizeServer(value);
35
- try {
36
- return await connectionContext(server, home);
37
- }
38
- catch (error) {
39
- if (error instanceof LoginRequiredError)
40
- throw new CliError(`Sign in to ${server} first. This machine stays local.`, `barndog login --server ${server}`, { cause: error });
41
- throw error;
42
- }
43
- }
44
- function renamed(asset, name) {
45
- if (asset.name === name)
46
- return asset.entries;
47
- if (asset.kind === "skill")
48
- return renameSkillEntries(asset.entries, name);
49
- return asset.entries.map((entry) => entry.path === "hook.yaml"
50
- ? {
51
- ...entry,
52
- data: Buffer.from(entry.data.toString("utf8").replace(/^name:.*$/m, `name: ${name}`)),
53
- }
54
- : entry);
55
- }
56
- async function candidates(overlay, names, as, kind) {
57
- const model = await overlay.model();
58
- const moved = await readMoved(overlay.label);
59
- const pending = (path) => names?.length ? true : !moved.some((entry) => entry.path === path);
60
- const items = [];
61
- const invalid = [];
62
- for (const asset of model.assets) {
63
- if (!pending(asset.path) ||
64
- (names?.length && !names.includes(asset.name)) ||
65
- (kind && asset.kind !== kind))
66
- continue;
67
- if (asset.invalid) {
68
- invalid.push({
69
- kind: asset.kind,
70
- name: asset.name,
71
- status: "skipped",
72
- detail: asset.invalid,
73
- });
74
- continue;
75
- }
76
- const name = as ?? asset.name;
77
- items.push({
78
- kind: asset.kind,
79
- name,
80
- path: asset.path,
81
- version: asset.publishedVersion,
82
- id: asset.id,
83
- entries: renamed(asset, name),
84
- definition: asset.definition,
85
- });
86
- }
87
- for (const doc of model.knowledge) {
88
- if (!pending(doc.path) ||
89
- (names?.length && !names.includes(doc.content.name)))
90
- continue;
91
- const name = as ?? doc.content.name;
92
- items.push({
93
- kind: "knowledge",
94
- name,
95
- path: doc.path,
96
- version: doc.version,
97
- id: doc.id,
98
- entries: [],
99
- content: { ...doc.content, name },
100
- });
101
- }
102
- for (const name of names ?? [])
103
- if (!items.some((item) => item.path.includes(`/${name}`)) &&
104
- !invalid.some((row) => row.name === name))
105
- throw new CliError(`No local asset named ${name}.`, "barndog local list");
106
- return { items, invalid };
107
- }
108
- function knowledgeFile(content) {
109
- const { description, tags, accessMode, markdown } = content;
110
- return `---\n${stringify({ description, tags, accessMode })}---\n${markdown}`;
111
- }
112
- async function moveToGit(workspace, items, to, home) {
113
- const shared = await gitRepoSource(workspace, home).model();
114
- const tip = (await acceptedCommit(workspace.workspaceId, home));
115
- const scope = selectScope(shared, to ?? "org");
116
- const repo = gitDirectory(workspace.workspaceId, home);
117
- const rows = [];
118
- const moving = [];
119
- for (const item of items) {
120
- const path = item.kind === "knowledge"
121
- ? `org/knowledge/${item.name}.md`
122
- : item.kind === "mcp"
123
- ? `${scope.path}/mcp/${item.name}.yaml`
124
- : assetFolder(scope.path, item.kind, item.name);
125
- if (shared.assets.some((asset) => asset.path === path) ||
126
- shared.knowledge.some((doc) => doc.path === path)) {
127
- rows.push({
128
- kind: item.kind,
129
- name: item.name,
130
- status: "clash",
131
- detail: `${path} already exists`,
132
- });
133
- continue;
134
- }
135
- moving.push({
136
- item,
137
- files: item.kind === "knowledge"
138
- ? [
139
- {
140
- path,
141
- data: Buffer.from(knowledgeFile(item.content)),
142
- executable: false,
143
- },
144
- ]
145
- : item.kind === "mcp"
146
- ? [
147
- {
148
- path,
149
- data: Buffer.from(stringify(item.definition)),
150
- executable: false,
151
- },
152
- ]
153
- : item.entries.map((entry) => ({
154
- ...entry,
155
- path: `${path}/${entry.path}`,
156
- })),
157
- });
158
- }
159
- const result = {
160
- target: workspace.url,
161
- rows,
162
- originId: stableId(workspace.workspaceId, "scope", scope.type, ...(scope.type === "org" ? [] : [scope.slug])),
163
- };
164
- if (!moving.length)
165
- return result;
166
- const title = `Move ${moving.length} local asset${moving.length === 1 ? "" : "s"} into the workspace`;
167
- const commit = await commitFiles(repo, tip, { files: moving.flatMap((entry) => entry.files) }, title);
168
- // A workspace with nothing in it has nothing to review against.
169
- if (!shared.assets.length && !shared.knowledge.length) {
170
- await pushCommit(repo, commit, workspace.branch);
171
- await git(["update-ref", trackingRef(workspace.branch), commit], { repo });
172
- await recordFetch(workspace, commit, home);
173
- result.direct = true;
174
- result.branch = workspace.branch;
175
- }
176
- else {
177
- const branch = `barndog/local-move-${randomBytes(3).toString("hex")}`;
178
- await pushCommit(repo, commit, branch);
179
- const opened = await openPullRequest({
180
- url: workspace.url,
181
- base: workspace.branch,
182
- branch,
183
- title,
184
- });
185
- result.branch = branch;
186
- result.url = opened.url ?? null;
187
- }
188
- rows.push(...moving.map(({ item }) => ({
189
- kind: item.kind,
190
- name: item.name,
191
- status: "moved",
192
- })));
193
- return result;
194
- }
195
- async function moveToCloud(conn, items, to, home) {
196
- const scope = await selectOrigin(to ?? "me", conn, home);
197
- if (!scope.canPublish)
198
- throw new CliError(`You can't publish to ${originLabel(scope)}.`, "barndog local move --to me");
199
- const { catalog } = await environmentCatalog(home, conn);
200
- const docs = (await request(conn, "/v1/knowledge?limit=100", knowledgeIndexSchema, home)).documents;
201
- const scopes = await request(conn, "/v1/scopes", z.array(scopeSchema), home);
202
- const org = scopes.find((s) => s.type === "org");
203
- const rows = [];
204
- for (const item of items) {
205
- const base = { kind: item.kind, name: item.name };
206
- try {
207
- if (item.kind === "knowledge") {
208
- if (docs.some((doc) => doc.name === item.name))
209
- rows.push({ ...base, status: "clash", detail: "Name already used" });
210
- else if (!org?.canPublish)
211
- rows.push({
212
- ...base,
213
- status: "skipped",
214
- detail: "Knowledge is organization-wide, and you can't publish there",
215
- });
216
- else {
217
- await publishKnowledge({ id: item.id, version: item.version, content: item.content }, conn, home);
218
- rows.push({ ...base, status: "moved" });
219
- }
220
- continue;
221
- }
222
- if (catalog.assets.some((asset) => asset.kind === item.kind &&
223
- asset.name === item.name &&
224
- asset.origin.id === scope.id)) {
225
- rows.push({
226
- ...base,
227
- status: "clash",
228
- detail: `Already in ${originLabel(scope)}`,
229
- });
230
- continue;
231
- }
232
- const asset = {
233
- id: item.id,
234
- kind: item.kind,
235
- name: item.name,
236
- publishedVersion: item.version,
237
- entries: item.entries,
238
- definition: item.definition,
239
- };
240
- if (item.kind === "mcp")
241
- await publishMcp(asset, scope, conn, home);
242
- else
243
- await publishPackage(asset, scope, conn, home);
244
- rows.push({ ...base, status: "moved" });
245
- }
246
- catch (error) {
247
- rows.push({
248
- ...base,
249
- status: "failed",
250
- detail: friendlyMessage(error),
251
- });
252
- }
253
- }
254
- return { target: originLabel(scope), rows, originId: scope.id };
255
- }
256
- /** Copies local assets into the shared workspace; the local folder is never deleted. */
257
- export function moveLocalAssets(options, home = homedir()) {
258
- return locked(home, async () => {
259
- const settings = await readSettings(home);
260
- if (!settings)
261
- throw new SetupRequiredError();
262
- if (settings.version !== 2 || !settings.localWorkspace)
263
- throw new CliError("This machine has no local assets to move.");
264
- const overlay = localRepoSource(settings.localWorkspace, home);
265
- const shared = options.repo || options.server
266
- ? null
267
- : (settings.gitWorkspace ?? settings.connection);
268
- if (!options.repo && !options.server && !shared)
269
- throw new CliError("This machine only has its local folder, so there's nowhere to move assets yet. Name a Git repo or a Cloud Workspace as the destination; this machine stays local.", "barndog local move --repo <url> or barndog local move --server <url>");
270
- if (options.as && options.names?.length !== 1)
271
- throw new CliError("--as renames one asset, so name exactly one.", "barndog local move <name> --as <new-name>");
272
- const { items, invalid } = await candidates(overlay, options.names, options.as, options.kind);
273
- const result = options.repo
274
- ? await moveToGit(await repoDestination(options.repo, home), items, options.to, home)
275
- : options.server
276
- ? await moveToCloud(await serverDestination(options.server, home), items, options.to, home)
277
- : settings.gitWorkspace
278
- ? await moveToGit(settings.gitWorkspace, items, options.to, home)
279
- : await moveToCloud(await connection(home), items, options.to, home);
280
- result.rows.unshift(...invalid);
281
- const moved = result.rows.filter((row) => row.status === "moved");
282
- await recordMoved(overlay.label, moved.map((row) => ({
283
- kind: row.kind,
284
- name: row.name,
285
- ...(row.kind !== "knowledge" ? { originId: result.originId } : {}),
286
- path: items.find((i) => i.kind === row.kind && i.name === row.name)
287
- .path,
288
- })));
289
- if (moved.length)
290
- await synchronize(undefined, home, undefined, { prompt: false });
291
- return result;
292
- });
293
- }
294
- export async function listLocalAssets(home = homedir()) {
295
- const settings = await readSettings(home);
296
- if (settings?.version !== 2 || !settings.localWorkspace)
297
- throw new CliError("This machine has no local assets.", "barndog init --local");
298
- const source = localRepoSource(settings.localWorkspace, home);
299
- const model = await source.model();
300
- const moved = await readMoved(source.label);
301
- const state = (path, invalid) => invalid
302
- ? "invalid"
303
- : moved.some((m) => m.path === path)
304
- ? "moved"
305
- : "active";
306
- return {
307
- folder: settings.localWorkspace.path,
308
- assets: [
309
- ...model.assets.map((asset) => ({
310
- kind: asset.kind,
311
- name: asset.name,
312
- path: asset.path,
313
- state: state(asset.path, asset.invalid),
314
- })),
315
- ...model.knowledge.map((doc) => ({
316
- kind: "knowledge",
317
- name: doc.content.name,
318
- path: doc.path,
319
- state: state(doc.path),
320
- })),
321
- ],
322
- };
323
- }
324
- /** Where setup can offer to send local assets in a Cloud Workspace; personal first. */
325
- export async function cloudMoveTargets(home) {
326
- const conn = await connection(home);
327
- const scopes = await request(conn, "/v1/scopes", z.array(scopeSchema), home);
328
- return scopes
329
- .filter((s) => s.canPublish && (s.type !== "dev" || matchesOrigin(s, "me", conn)))
330
- .sort((a, b) => Number(b.type === "dev") - Number(a.type === "dev"))
331
- .map((s) => ({
332
- value: s.type === "dev" ? "me" : originLabel(s),
333
- name: s.type === "dev"
334
- ? "Your personal assets"
335
- : `${s.name} (${originLabel(s)})`,
336
- }));
337
- }
@@ -1,159 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { randomUUID } from "node:crypto";
5
- import { CliError } from "../../errors.js";
6
- import { storePackage } from "../environment/packages.js";
7
- import { loadWorkspace, NAME_RULE, } from "./format.js";
8
- import { git, GitError, gitReason, gitText } from "./git.js";
9
- import { folderSnapshot, gitSnapshot } from "./snapshot.js";
10
- function repoSource(backend, home) {
11
- let loading;
12
- const model = () => (loading ??= backend.open().then((snapshot) => loadWorkspace(snapshot, backend.workspaceId, {
13
- localOnly: backend.localOnly ?? false,
14
- })));
15
- const find = async (reference) => {
16
- const asset = (await model()).assets.find((a) => a.id === reference.id);
17
- if (!asset || asset.publishedVersion !== reference.publishedVersion)
18
- throw new Error("Catalog changed during staging; retry sync");
19
- if (asset.invalid)
20
- throw new CliError(`${asset.path} is invalid: ${asset.invalid}`);
21
- return asset;
22
- };
23
- return {
24
- cacheKey: backend.cacheKey,
25
- journal: { workspaceId: backend.workspaceId },
26
- label: backend.label,
27
- model,
28
- catalog: async () => (await model()).catalog,
29
- invalidAssets: async () => (await model()).invalid,
30
- notices: backend.notices,
31
- warnings: async () => {
32
- const { invalidKnowledge, problems } = await model();
33
- return [
34
- ...invalidKnowledge.map((problem) => `Knowledge file ${problem.path} was skipped: ${problem.reason}`),
35
- ...problems
36
- .filter((problem) => problem.reason === NAME_RULE)
37
- .map((problem) => `${problem.path} was skipped: ${problem.reason}. Rename it to deliver it.`),
38
- ];
39
- },
40
- skillOrHookPackage: async (kind, reference) => {
41
- const asset = await find(reference);
42
- return storePackage(kind, {
43
- id: asset.id,
44
- name: asset.name,
45
- revision: asset.publishedVersion,
46
- }, backend.cacheKey, home, async () => asset.entries);
47
- },
48
- mcpDefinition: async (reference) => (await find(reference)).definition,
49
- };
50
- }
51
- export function localRepoSource(workspace, home) {
52
- return repoSource({
53
- cacheKey: join("local", workspace.workspaceId),
54
- workspaceId: workspace.workspaceId,
55
- label: workspace.path,
56
- open: () => folderSnapshot(workspace.path),
57
- notices: () => [],
58
- localOnly: true,
59
- }, home);
60
- }
61
- const AUTO_FETCH_INTERVAL_MS = 5 * 60 * 1000;
62
- export const gitDirectory = (workspaceId, home) => join(home, ".barndog", "git", `${workspaceId}.git`);
63
- const statePath = (workspaceId, home) => join(home, ".barndog", "git", `${workspaceId}.json`);
64
- export async function readFetchState(workspaceId, home) {
65
- try {
66
- return JSON.parse(await readFile(statePath(workspaceId, home), "utf8"));
67
- }
68
- catch (error) {
69
- if (error.code === "ENOENT")
70
- return {};
71
- throw error;
72
- }
73
- }
74
- async function writeFetchState(workspaceId, home, state) {
75
- const path = statePath(workspaceId, home);
76
- const temporary = `${path}.${randomUUID()}.tmp`;
77
- try {
78
- await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
79
- await rename(temporary, path);
80
- }
81
- finally {
82
- await rm(temporary, { force: true });
83
- }
84
- }
85
- /** Creates or repairs the bare clone; nothing is ever checked out of it. */
86
- export async function ensureBareClone(repo, url) {
87
- await mkdir(repo, { recursive: true, mode: 0o700 });
88
- await git(["init", "--quiet", "--bare", "."], { repo });
89
- await git(["config", "remote.origin.url", url], { repo });
90
- }
91
- export const fetchBranch = (repo, branch, allowPrompt = false) => git([
92
- "fetch",
93
- "--quiet",
94
- "--prune",
95
- "--no-tags",
96
- "origin",
97
- `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
98
- ], { repo, allowPrompt });
99
- export function trackingRef(branch) {
100
- return `refs/remotes/origin/${branch}`;
101
- }
102
- const age = (fetchedAt) => {
103
- if (!fetchedAt)
104
- return "an unknown time";
105
- const minutes = Math.round((Date.now() - Date.parse(fetchedAt)) / 60000);
106
- if (minutes < 1)
107
- return "less than a minute";
108
- if (minutes < 60)
109
- return `${minutes} minute${minutes === 1 ? "" : "s"}`;
110
- const hours = Math.round(minutes / 60);
111
- return hours < 48 ? `${hours} hours` : `${Math.round(hours / 24)} days`;
112
- };
113
- export function gitRepoSource(workspace, home, options = {}) {
114
- const repo = gitDirectory(workspace.workspaceId, home);
115
- const notices = [];
116
- async function currentCommit() {
117
- const state = await readFetchState(workspace.workspaceId, home);
118
- const policy = options.refresh ?? "always";
119
- const recent = state.fetchedAt &&
120
- Date.now() - Date.parse(state.fetchedAt) < AUTO_FETCH_INTERVAL_MS;
121
- if (policy === "none" || (policy === "auto" && recent && state.accepted)) {
122
- if (!state.accepted)
123
- throw new CliError("This Git workspace hasn't been fetched yet.", "barndog sync");
124
- return state.accepted;
125
- }
126
- await ensureBareClone(repo, workspace.url);
127
- try {
128
- await fetchBranch(repo, workspace.branch);
129
- }
130
- catch (error) {
131
- if (!(error instanceof GitError))
132
- throw error;
133
- if (!state.accepted)
134
- throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, `git clone ${workspace.url}`, { cause: error });
135
- notices.push(`Can't reach ${workspace.url}, so this uses what was fetched ${age(state.fetchedAt)} ago.`);
136
- return state.accepted;
137
- }
138
- const tip = await gitText(["rev-parse", "--verify", trackingRef(workspace.branch)], { repo });
139
- await writeFetchState(workspace.workspaceId, home, {
140
- accepted: tip,
141
- fetchedAt: new Date().toISOString(),
142
- });
143
- return tip;
144
- }
145
- return repoSource({
146
- cacheKey: join("git", createHash("sha256").update(workspace.workspaceId).digest("hex")),
147
- workspaceId: workspace.workspaceId,
148
- label: workspace.url,
149
- open: async () => gitSnapshot(repo, await currentCommit()),
150
- notices: () => notices,
151
- }, home);
152
- }
153
- export async function recordFetch(workspace, commit, home) {
154
- await writeFetchState(workspace.workspaceId, home, {
155
- accepted: commit,
156
- fetchedAt: new Date().toISOString(),
157
- });
158
- }
159
- export const acceptedCommit = async (workspaceId, home) => (await readFetchState(workspaceId, home)).accepted;