barndog 0.0.0-stage → 0.1.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -2
  3. package/dist/cli.js +40 -0
  4. package/dist/commands/add.js +99 -0
  5. package/dist/commands/auth.js +25 -0
  6. package/dist/commands/availability.js +87 -0
  7. package/dist/commands/capabilities.js +488 -0
  8. package/dist/commands/collaboration.js +203 -0
  9. package/dist/commands/context.js +1 -0
  10. package/dist/commands/environment.js +416 -0
  11. package/dist/commands/init.js +20 -0
  12. package/dist/commands/origin.js +48 -0
  13. package/dist/commands/status.js +66 -0
  14. package/dist/commands/sync.js +30 -0
  15. package/dist/commands/workspace.js +84 -0
  16. package/dist/config/build.js +2 -0
  17. package/dist/config/environment.js +41 -0
  18. package/dist/config/settings.js +127 -0
  19. package/dist/config/state.js +70 -0
  20. package/dist/errors.js +154 -0
  21. package/dist/features/asset-selection/index.js +212 -0
  22. package/dist/features/asset-selection/types.js +1 -0
  23. package/dist/features/auth/credentials.js +62 -0
  24. package/dist/features/auth/session.js +120 -0
  25. package/dist/features/auth/transport.js +44 -0
  26. package/dist/features/capabilities/index.js +106 -0
  27. package/dist/features/catalog/index.js +102 -0
  28. package/dist/features/collaboration/domain.js +90 -0
  29. package/dist/features/collaboration/index.js +254 -0
  30. package/dist/features/collaboration/remote.js +121 -0
  31. package/dist/features/collaboration/workspace-git.js +362 -0
  32. package/dist/features/collaboration/workspace-github.js +130 -0
  33. package/dist/features/collaboration/workspace-store.js +256 -0
  34. package/dist/features/collaboration/workspace.js +391 -0
  35. package/dist/features/discovery/index.js +66 -0
  36. package/dist/features/doctor/index.js +154 -0
  37. package/dist/features/environment/auto-sync.js +96 -0
  38. package/dist/features/environment/cloud-source.js +27 -0
  39. package/dist/features/environment/installed.js +124 -0
  40. package/dist/features/environment/names.js +153 -0
  41. package/dist/features/environment/operations.js +277 -0
  42. package/dist/features/environment/packages.js +120 -0
  43. package/dist/features/environment/remote.js +71 -0
  44. package/dist/features/environment/source.js +1 -0
  45. package/dist/features/environment/sync.js +547 -0
  46. package/dist/features/environment/transaction.js +284 -0
  47. package/dist/features/environment/workspace-source.js +19 -0
  48. package/dist/features/git-hosts/index.js +148 -0
  49. package/dist/features/git-workspace/assets.js +71 -0
  50. package/dist/features/git-workspace/format.js +310 -0
  51. package/dist/features/git-workspace/git.js +135 -0
  52. package/dist/features/git-workspace/migrate.js +188 -0
  53. package/dist/features/git-workspace/move.js +337 -0
  54. package/dist/features/git-workspace/overlay.js +131 -0
  55. package/dist/features/git-workspace/publish.js +172 -0
  56. package/dist/features/git-workspace/setup.js +135 -0
  57. package/dist/features/git-workspace/snapshot.js +105 -0
  58. package/dist/features/git-workspace/source.js +159 -0
  59. package/dist/features/git-workspace/startup.js +16 -0
  60. package/dist/features/hooks/adapt.js +103 -0
  61. package/dist/features/hooks/divergence.js +38 -0
  62. package/dist/features/hooks/test.js +114 -0
  63. package/dist/features/imports/discover.js +249 -0
  64. package/dist/features/imports/folder.js +52 -0
  65. package/dist/features/imports/local.js +242 -0
  66. package/dist/features/imports/mcp.js +219 -0
  67. package/dist/features/imports/remote.js +85 -0
  68. package/dist/features/inspection/index.js +42 -0
  69. package/dist/features/inventory/index.js +224 -0
  70. package/dist/features/knowledge/index.js +118 -0
  71. package/dist/features/knowledge/startup.js +25 -0
  72. package/dist/features/mcps/index.js +102 -0
  73. package/dist/features/native/adapters.js +143 -0
  74. package/dist/features/native/configuration.js +196 -0
  75. package/dist/features/native/mcp-launch.js +57 -0
  76. package/dist/features/onboarding/environment.js +160 -0
  77. package/dist/features/onboarding/setup.js +123 -0
  78. package/dist/features/repositories/context.js +55 -0
  79. package/dist/features/skills/install.js +25 -0
  80. package/dist/features/skills/remote.js +177 -0
  81. package/dist/features/skills/sync.js +121 -0
  82. package/dist/features/skills/validation.js +34 -0
  83. package/dist/harnesses/claude.js +57 -0
  84. package/dist/harnesses/codex.js +46 -0
  85. package/dist/harnesses/cursor.js +44 -0
  86. package/dist/harnesses/detect.js +61 -0
  87. package/dist/harnesses/registry.js +16 -0
  88. package/dist/harnesses/types.js +1 -0
  89. package/dist/program.js +272 -0
  90. package/dist/ui/add-asset.js +440 -0
  91. package/dist/ui/asset-list.js +50 -0
  92. package/dist/ui/assets.js +142 -0
  93. package/dist/ui/auth.js +138 -0
  94. package/dist/ui/clash.js +43 -0
  95. package/dist/ui/collaboration.js +142 -0
  96. package/dist/ui/connection.js +102 -0
  97. package/dist/ui/environment-onboarding.js +125 -0
  98. package/dist/ui/format.js +154 -0
  99. package/dist/ui/hook-compatibility.js +33 -0
  100. package/dist/ui/mcp.js +40 -0
  101. package/dist/ui/move.js +22 -0
  102. package/dist/ui/onboarding.js +293 -0
  103. package/dist/ui/output.js +155 -0
  104. package/dist/ui/pick.js +153 -0
  105. package/dist/ui/scope-install.js +47 -0
  106. package/dist/ui/selection.js +51 -0
  107. package/dist/ui/theme.js +37 -0
  108. package/dist/version.js +12 -0
  109. package/package.json +73 -4
@@ -0,0 +1,362 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { homedir } from "node:os";
3
+ import { dirname, resolve } from "node:path";
4
+ import { mkdir, realpath, rm } from "node:fs/promises";
5
+ import { packageFingerprint, validatePackageEntries, writePackage, } from "@barndog-ai/api-contract/package";
6
+ import { diffEntries, mergeEntries, readDirectory, } from "@barndog-ai/api-contract/collaboration";
7
+ import { CliError } from "../../errors.js";
8
+ import { assetFolder, loadWorkspace, } from "../git-workspace/format.js";
9
+ import { git, gitText } from "../git-workspace/git.js";
10
+ import { commitFiles, openPullRequest, pushCommit, remoteBranch, } from "../git-workspace/publish.js";
11
+ import { isBlob, gitSnapshot, TREE_MODE } from "../git-workspace/snapshot.js";
12
+ import { acceptedCommit, gitDirectory, gitRepoSource, recordFetch, trackingRef, } from "../git-workspace/source.js";
13
+ import { metadata as packageMetadataFor } from "./domain.js";
14
+ import { matchesOrigin } from "./remote.js";
15
+ import { markResolved } from "./workspace.js";
16
+ import { applyFiles, decodeFiles, encodeFiles, findGit, locked, save, } from "./workspace-store.js";
17
+ async function latest(workspace, home) {
18
+ const model = await gitRepoSource(workspace, home).model();
19
+ return {
20
+ model,
21
+ commit: (await acceptedCommit(workspace.workspaceId, home)),
22
+ };
23
+ }
24
+ function selectAsset(model, kind, name, origin) {
25
+ const matches = model.assets.filter((asset) => asset.kind === kind &&
26
+ asset.name === name &&
27
+ matchesOrigin(asset.origin, origin, model));
28
+ if (matches.length !== 1)
29
+ throw new CliError(`No ${kind === "skill" ? "Skill" : kind === "hook" ? "Hook" : "MCP server"} named ${name} in ${origin}.`, `barndog ${kind === "skill" ? "skills" : kind === "hook" ? "hooks" : "mcp"} search ${name}`);
30
+ return matches[0];
31
+ }
32
+ export function selectScope(model, origin) {
33
+ const matches = model.scopes.filter((scope) => matchesOrigin(scope, origin, model));
34
+ if (origin === "me" || /^dev[/:]/.test(origin))
35
+ throw new CliError("Personal scopes don't exist in a Git repo workspace. Use org, team/<slug> or repo/<slug>.");
36
+ if (!matches.length && /^(team|repo)[/:]/.test(origin)) {
37
+ const [type, slug] = origin.split(/[/:]/);
38
+ return {
39
+ type,
40
+ slug,
41
+ path: `${type === "team" ? "teams" : "repos"}/${slug}`,
42
+ };
43
+ }
44
+ if (matches.length !== 1)
45
+ throw new CliError(`No scope named ${origin}. Use org, team/<slug> or repo/<slug>.`);
46
+ return pickScope(matches[0]);
47
+ }
48
+ const pickScope = (scope) => ({
49
+ type: scope.type,
50
+ slug: scope.slug,
51
+ path: scope.path,
52
+ });
53
+ const usable = (asset) => {
54
+ if (asset.invalid)
55
+ throw new CliError(`${asset.path} is invalid: ${asset.invalid}. Fix it on the Git host first.`);
56
+ return asset;
57
+ };
58
+ const scaffold = (kind, name) => kind === "skill"
59
+ ? [
60
+ {
61
+ path: "SKILL.md",
62
+ data: Buffer.from(`---\nname: ${name}\ndescription: Describe this Skill\n---\n\nAdd instructions here.\n`),
63
+ executable: false,
64
+ },
65
+ ]
66
+ : [
67
+ {
68
+ path: "hook.yaml",
69
+ data: Buffer.from(`name: ${name}\ndescription: Describe this Hook\nimplementations:\n claude:\n compatibility: supported\n scripts: [scripts/hook.sh]\n requirements:\n commands: [sh]\n events:\n SessionStart:\n - hooks:\n - type: command\n command: '\${BARNDOG_HOOK_ROOT}/scripts/hook.sh'\n`),
70
+ executable: false,
71
+ },
72
+ {
73
+ path: "scripts/hook.sh",
74
+ data: Buffer.from("#!/bin/sh\n# Read native input; implement the desired behavior here.\ncat >/dev/null\n"),
75
+ executable: true,
76
+ },
77
+ ];
78
+ async function newFolder(cwd, target) {
79
+ const path = resolve(cwd, target);
80
+ await mkdir(dirname(path), { recursive: true });
81
+ // Never overwrite an existing directory, even if it appears empty.
82
+ await mkdir(path);
83
+ return realpath(path);
84
+ }
85
+ async function startWorkingCopy(root, record, entries, base, home) {
86
+ try {
87
+ await writePackage(root, entries);
88
+ await save({ ...record, root, base: encodeFiles(base), conflicts: [] }, home);
89
+ }
90
+ catch (error) {
91
+ await rm(root, { recursive: true, force: true });
92
+ throw error;
93
+ }
94
+ }
95
+ export function pullGitAsset(workspace, options, cwd, home = homedir()) {
96
+ const kind = options.kind ?? "skill";
97
+ return locked(home, async () => {
98
+ const { model, commit } = await latest(workspace, home);
99
+ const asset = usable(selectAsset(model, kind, options.name, options.origin));
100
+ const root = await newFolder(cwd, options.target ?? options.name);
101
+ await startWorkingCopy(root, {
102
+ kind,
103
+ git: workspace,
104
+ name: asset.name,
105
+ scope: pickScope(asset.origin),
106
+ baseCommit: commit,
107
+ }, asset.entries, asset.entries, home);
108
+ return { root, commit };
109
+ });
110
+ }
111
+ export function createGitAsset(workspace, options, cwd, home = homedir()) {
112
+ const kind = options.kind ?? "skill";
113
+ return locked(home, async () => {
114
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options.name))
115
+ throw new Error("Use a lowercase hyphenated package name");
116
+ const { model, commit } = await latest(workspace, home);
117
+ const scope = selectScope(model, options.origin);
118
+ const root = await newFolder(cwd, options.target ?? options.name);
119
+ await startWorkingCopy(root, { kind, git: workspace, name: options.name, scope, baseCommit: commit }, scaffold(kind, options.name), [], home);
120
+ return { root, kind, name: options.name };
121
+ });
122
+ }
123
+ export function gitWorkingStatus(cwd, home = homedir()) {
124
+ return locked(home, async () => {
125
+ const work = await findGit(cwd, home);
126
+ return {
127
+ root: work.root,
128
+ name: work.name,
129
+ baseVersion: null,
130
+ baseCommit: work.baseCommit,
131
+ proposal: null,
132
+ review: work.review
133
+ ? { branch: work.review.branch, url: work.review.url ?? null }
134
+ : null,
135
+ conflicts: work.conflicts,
136
+ pending: false,
137
+ external: null,
138
+ changes: await diffEntries(decodeFiles(work.base), await readDirectory(work.root)),
139
+ };
140
+ });
141
+ }
142
+ const assetIn = (model, work) => model.assets.find((asset) => asset.kind === work.kind &&
143
+ asset.path === assetFolder(work.scope.path, work.kind, work.name));
144
+ const fingerprint = (entries) => packageFingerprint(entries);
145
+ async function branchFiles(work, head, home) {
146
+ const repo = gitDirectory(work.git.workspaceId, home);
147
+ await git([
148
+ "fetch",
149
+ "--quiet",
150
+ "--no-tags",
151
+ "origin",
152
+ `refs/heads/${work.review.branch}`,
153
+ ], { repo });
154
+ const model = await loadWorkspace(await gitSnapshot(repo, head));
155
+ const asset = assetIn(model, work);
156
+ if (!asset)
157
+ throw new CliError(`${work.review.branch} no longer contains ${work.name}.`);
158
+ return usable(asset).entries;
159
+ }
160
+ export function updateGitWorkingCopy(cwd, home = homedir()) {
161
+ return locked(home, async () => {
162
+ const work = await findGit(cwd, home);
163
+ const previous = structuredClone(work);
164
+ if (work.conflicts.length)
165
+ throw new Error("Resolve existing conflicts before pulling again");
166
+ const repo = gitDirectory(work.git.workspaceId, home);
167
+ const { model, commit } = await latest(work.git, home);
168
+ let entries = await readDirectory(work.root);
169
+ const conflicts = new Set();
170
+ const merge = async (base, incoming) => {
171
+ const merged = await mergeEntries(base, entries, incoming);
172
+ entries = merged.entries;
173
+ merged.conflicts.forEach((path) => conflicts.add(path));
174
+ };
175
+ if (work.review) {
176
+ const head = await remoteBranch(repo, work.review.branch);
177
+ if (head && head !== work.review.head) {
178
+ const remote = await branchFiles(work, head, home);
179
+ await merge(decodeFiles(work.review.files), remote);
180
+ work.review = {
181
+ ...work.review,
182
+ head,
183
+ files: encodeFiles(remote),
184
+ };
185
+ }
186
+ }
187
+ const current = assetIn(model, work);
188
+ if (current) {
189
+ const incoming = usable(current).entries;
190
+ if (fingerprint(incoming) !== fingerprint(decodeFiles(work.base)))
191
+ await merge(decodeFiles(work.base), incoming);
192
+ work.base = encodeFiles(incoming);
193
+ // The review is over once its content is what the default branch holds.
194
+ if (work.review &&
195
+ fingerprint(incoming) === fingerprint(decodeFiles(work.review.files)))
196
+ delete work.review;
197
+ }
198
+ work.baseCommit = commit;
199
+ work.conflicts = [...conflicts];
200
+ await applyFiles(work, entries, home, previous);
201
+ return {
202
+ root: work.root,
203
+ conflicts: work.conflicts,
204
+ baseVersion: null,
205
+ commit,
206
+ };
207
+ });
208
+ }
209
+ export function resolveGitConflict(path, cwd, home = homedir()) {
210
+ return locked(home, async () => markResolved(await findGit(cwd, home), path, cwd, home));
211
+ }
212
+ export function pushGitWorkingCopy(workspace, options, cwd, home = homedir()) {
213
+ return locked(home, async () => {
214
+ const { model, commit: tip } = await latest(workspace, home);
215
+ let work;
216
+ try {
217
+ work = await findGit(cwd, home);
218
+ }
219
+ catch (error) {
220
+ if (!options.origin || !(error instanceof CliError))
221
+ throw error;
222
+ const root = await realpath(cwd);
223
+ const kind = options.kind ?? "skill";
224
+ work = {
225
+ root,
226
+ kind,
227
+ git: workspace,
228
+ name: packageMetadataFor(await readDirectory(root), kind).name,
229
+ scope: selectScope(model, options.origin),
230
+ baseCommit: tip,
231
+ base: [],
232
+ conflicts: [],
233
+ };
234
+ await save(work, home);
235
+ }
236
+ if (options.kind && work.kind !== options.kind)
237
+ throw new Error("Working copy belongs to a different asset kind");
238
+ if (options.name && work.name !== options.name)
239
+ throw new Error("Working-copy name does not match the requested asset");
240
+ if (work.git.workspaceId !== workspace.workspaceId)
241
+ throw new CliError("This working copy belongs to a different Git workspace.");
242
+ if (work.conflicts.length)
243
+ throw new Error("Resolve conflicts with barndog resolve <path> before pushing");
244
+ const files = validatePackageEntries(await readDirectory(work.root), undefined, work.kind === "hook" ? "hook.yaml" : "SKILL.md");
245
+ if (packageMetadataFor(files, work.kind).name !== work.name)
246
+ throw new Error("Package name cannot change in this working copy");
247
+ const repo = gitDirectory(workspace.workspaceId, home);
248
+ const path = assetFolder(work.scope.path, work.kind, work.name);
249
+ const change = {
250
+ replace: path,
251
+ files: files.map((file) => ({
252
+ ...file,
253
+ path: `${path}/${file.path}`,
254
+ })),
255
+ };
256
+ const title = options.title ?? `Update ${work.name}`;
257
+ if (options.publish) {
258
+ const current = assetIn(model, work);
259
+ if (fingerprint(current?.entries ?? []) !==
260
+ fingerprint(decodeFiles(work.base)))
261
+ throw new CliError(`${work.name} changed on ${workspace.branch} since you pulled it.`, "barndog pull");
262
+ if (fingerprint(files) === fingerprint(decodeFiles(work.base)))
263
+ return { unchanged: true };
264
+ const commit = await commitFiles(repo, tip, change, title);
265
+ await pushCommit(repo, commit, workspace.branch);
266
+ await git(["update-ref", trackingRef(workspace.branch), commit], {
267
+ repo,
268
+ });
269
+ await recordFetch(workspace, commit, home);
270
+ work.base = encodeFiles(files);
271
+ work.baseCommit = commit;
272
+ delete work.review;
273
+ await save(work, home);
274
+ return { branch: workspace.branch, commit, published: true };
275
+ }
276
+ let review = options.new ? undefined : work.review;
277
+ if (review) {
278
+ const head = await remoteBranch(repo, review.branch);
279
+ if (head === null)
280
+ review = undefined;
281
+ else if (head !== review.head)
282
+ throw new CliError(`${review.branch} changed on the Git host.`, "barndog pull");
283
+ }
284
+ const previous = review
285
+ ? decodeFiles(review.files)
286
+ : decodeFiles(work.base);
287
+ if (fingerprint(files) === fingerprint(previous))
288
+ return { unchanged: true };
289
+ const branch = review?.branch ??
290
+ `barndog/${work.scope.type === "org" ? "org" : `${work.scope.type}-${work.scope.slug}`}-${work.name}-${randomBytes(3).toString("hex")}`;
291
+ const commit = await commitFiles(repo, review?.head ?? work.baseCommit, change, title);
292
+ await pushCommit(repo, commit, branch);
293
+ const opened = review?.url
294
+ ? { url: review.url, opened: false }
295
+ : await openPullRequest({
296
+ url: workspace.url,
297
+ base: workspace.branch,
298
+ branch,
299
+ title,
300
+ });
301
+ work.review = {
302
+ branch,
303
+ head: commit,
304
+ files: encodeFiles(files),
305
+ ...(opened.url ? { url: opened.url } : {}),
306
+ };
307
+ await save(work, home);
308
+ return { branch, commit, url: opened.url ?? null, opened: opened.opened };
309
+ });
310
+ }
311
+ /** Commits that changed an asset, oldest first; their position is the version number. */
312
+ async function assetHistory(repo, commit, path) {
313
+ const output = await gitText(["log", "--reverse", "--format=%H%x00%ct%x00%an%x00%s", commit, "--", path], { repo });
314
+ return output
315
+ .split("\n")
316
+ .filter(Boolean)
317
+ .map((line, index) => {
318
+ const [hash, time, author, subject] = line.split("\0");
319
+ return {
320
+ number: index + 1,
321
+ commit: hash,
322
+ publishedAt: new Date(Number(time) * 1000).toISOString(),
323
+ publishedBy: author,
324
+ description: subject,
325
+ };
326
+ });
327
+ }
328
+ async function filesAt(repo, commit, path) {
329
+ const snapshot = await gitSnapshot(repo, commit);
330
+ const single = snapshot.entries.find((entry) => entry.path === path);
331
+ const members = single && single.mode !== TREE_MODE
332
+ ? [{ ...single, path: path.split("/").at(-1) }]
333
+ : snapshot.entries
334
+ .filter((entry) => entry.path.startsWith(`${path}/`) && isBlob(entry.mode))
335
+ .map((entry) => ({
336
+ ...entry,
337
+ path: entry.path.slice(path.length + 1),
338
+ }));
339
+ const blobs = await snapshot.readBlobs(members.map((entry) => entry.hash));
340
+ return members.map((entry) => ({
341
+ path: entry.path,
342
+ data: blobs.get(entry.hash),
343
+ executable: entry.mode === "100755",
344
+ }));
345
+ }
346
+ export async function gitHistory(workspace, action, options, home = homedir()) {
347
+ const { model, commit } = await latest(workspace, home);
348
+ const asset = selectAsset(model, options.kind ?? "skill", options.name, options.origin);
349
+ const repo = gitDirectory(workspace.workspaceId, home);
350
+ const history = await assetHistory(repo, commit, asset.path);
351
+ if (action === "versions")
352
+ return history;
353
+ const at = (number) => {
354
+ const version = number ? history[number - 1] : history.at(-1);
355
+ if (!version)
356
+ throw new CliError(`${asset.name} has no version ${number}.`);
357
+ return filesAt(repo, version.commit, asset.path);
358
+ };
359
+ if (action === "version-show")
360
+ return { files: encodeFiles(await at(options.version)) };
361
+ return diffEntries(await at(options.from), await at(options.to));
362
+ }
@@ -0,0 +1,130 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { ApiError, gitConnectionSchema, gitPullSchema, gitPullDetailsSchema, } from "@barndog-ai/api-contract";
4
+ import { packageFingerprint, } from "@barndog-ai/api-contract/package";
5
+ import { mergeEntries, readDirectory, } from "@barndog-ai/api-contract/collaboration";
6
+ import { metadata as packageMetadataFor } from "./domain.js";
7
+ import { download } from "./remote.js";
8
+ import { request, getAsset } from "../environment/remote.js";
9
+ import { encodeFiles, decodeFiles, save, applyFiles, } from "./workspace-store.js";
10
+ export async function externalSource(work, home) {
11
+ if (!work.skillId)
12
+ return undefined;
13
+ const connections = await request(work.connection, "/v1/git-connections", z.array(gitConnectionSchema), home);
14
+ const source = connections.find((c) => c.assetId === work.skillId &&
15
+ c.kind === work.kind &&
16
+ c.authority === "github");
17
+ if (work.external && (!source || source.id !== work.external.id))
18
+ throw new Error("External content authority changed; preserve this working copy and pull a new one");
19
+ if (source && source.status !== "active")
20
+ throw new Error(`GitHub synchronization requires attention: ${source.lastError ?? source.status}`);
21
+ if (source && work.pending)
22
+ throw new Error("An internal submission is pending; resolve it before using GitHub");
23
+ return source;
24
+ }
25
+ export async function pullExternal(work, source, entries, previous, home) {
26
+ work.external ??= { id: source.id };
27
+ const conflicts = new Set(), external = work.external;
28
+ if (external.pull) {
29
+ const { pull } = await request(work.connection, `/v1/git-connections/${source.id}/pulls/${external.pull.number}`, gitPullDetailsSchema, home);
30
+ if (pull.head !== external.pull.head) {
31
+ const remote = await download(`/v1/git-connections/${source.id}/pulls/${pull.number}/package`, work.connection, home, pull.head, work.kind);
32
+ const merged = await mergeEntries(decodeFiles(external.pull.files), entries, remote);
33
+ entries = merged.entries;
34
+ merged.conflicts.forEach((p) => conflicts.add(p));
35
+ external.pull = {
36
+ number: pull.number,
37
+ head: pull.head,
38
+ files: encodeFiles(remote),
39
+ };
40
+ }
41
+ if (pull.merged)
42
+ delete external.pull;
43
+ }
44
+ const asset = await getAsset(work.kind, work.skillId, work.connection, home);
45
+ if (!("commit" in asset.version))
46
+ throw new Error("Expected a Git-backed package version");
47
+ if (asset.version.id !== work.baseVersionId) {
48
+ const latest = await download(`/v1/skills/${work.skillId}/versions/${asset.version.number}/package`, work.connection, home, asset.version.commit, work.kind);
49
+ const merged = await mergeEntries(decodeFiles(work.base), entries, latest);
50
+ entries = merged.entries;
51
+ merged.conflicts.forEach((p) => conflicts.add(p));
52
+ work.base = encodeFiles(latest);
53
+ work.baseVersionId = asset.version.id;
54
+ work.baseNumber = asset.version.number;
55
+ }
56
+ work.conflicts = [...conflicts];
57
+ await applyFiles(work, entries, home, previous);
58
+ return {
59
+ root: work.root,
60
+ conflicts: work.conflicts,
61
+ baseVersion: work.baseNumber,
62
+ external: { connectionId: source.id, pull: external.pull?.number },
63
+ };
64
+ }
65
+ export async function pushExternal(work, source, options, home) {
66
+ work.external ??= { id: source.id };
67
+ const external = work.external, path = `/v1/git-connections/${source.id}`;
68
+ if (!external.pending) {
69
+ const asset = await getAsset(work.kind, work.skillId, work.connection, home);
70
+ if (asset.version.id !== work.baseVersionId)
71
+ throw new Error("Published GitHub content changed; run barndog pull before pushing");
72
+ let pull = external.pull
73
+ ? (await request(work.connection, `${path}/pulls/${external.pull.number}`, gitPullDetailsSchema, home)).pull
74
+ : undefined;
75
+ if (pull?.state === "closed" && !options.new)
76
+ throw new Error("Pull request is closed; run barndog pull, then push --new to contribute again");
77
+ if (pull && pull.head !== external.pull.head)
78
+ throw new Error("Pull request changed remotely; run barndog pull before pushing");
79
+ if (options.new)
80
+ pull = undefined;
81
+ const files = await readDirectory(work.root);
82
+ if (packageMetadataFor(files, work.kind).name !== work.name)
83
+ throw new Error("Package name cannot change in this working copy");
84
+ const previous = pull ? external.pull.files : work.base;
85
+ if (packageFingerprint(files) === packageFingerprint(decodeFiles(previous)) &&
86
+ !options.title) {
87
+ if (options.publish && pull)
88
+ return request(work.connection, `${path}/pulls/${pull.number}/merge`, gitConnectionSchema, home, "PUT", { expectedCommit: pull.head });
89
+ return { unchanged: true, pull: pull?.number };
90
+ }
91
+ external.pending = {
92
+ number: pull?.number,
93
+ expectedCommit: pull?.head ?? source.syncedCommit,
94
+ files: encodeFiles(files),
95
+ title: options.title ?? `Update ${work.name}`,
96
+ idempotencyKey: randomUUID(),
97
+ };
98
+ await save(work, home);
99
+ }
100
+ const pending = external.pending;
101
+ let pull;
102
+ try {
103
+ pull = await request(work.connection, pending.number
104
+ ? `${path}/pulls/${pending.number}/revisions`
105
+ : `${path}/pulls`, gitPullSchema, home, pending.number ? "PUT" : "POST", {
106
+ expectedCommit: pending.expectedCommit,
107
+ files: pending.files,
108
+ title: pending.title,
109
+ idempotencyKey: pending.idempotencyKey,
110
+ });
111
+ }
112
+ catch (error) {
113
+ if (error instanceof ApiError &&
114
+ [400, 403, 404, 409, 413].includes(error.status)) {
115
+ delete external.pending;
116
+ await save(work, home);
117
+ }
118
+ throw error;
119
+ }
120
+ external.pull = {
121
+ number: pull.number,
122
+ head: pull.submittedCommit ?? pull.head,
123
+ files: pending.files,
124
+ };
125
+ delete external.pending;
126
+ await save(work, home);
127
+ if (options.publish)
128
+ return request(work.connection, `${path}/pulls/${pull.number}/merge`, gitConnectionSchema, home, "PUT", { expectedCommit: external.pull.head });
129
+ return pull;
130
+ }