barndog 0.1.1 → 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 +8 -7
  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 +13 -3
  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,49 +1,65 @@
1
+ import { writePackage, readDirectory } from "../workspace/directory.js";
2
+ import { MILLISECONDS_PER_SECOND } from "../../shared/constants.js";
1
3
  import { randomBytes } from "node:crypto";
2
- import { homedir } from "node:os";
3
4
  import { dirname, resolve } from "node:path";
4
5
  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";
6
+ import { packageFingerprint, validatePackageEntries, } from "@barndog-ai/api-contract/package";
7
+ import { diffEntries, mergeEntries, } from "@barndog-ai/api-contract/collaboration";
7
8
  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";
9
+ import { assetPath, loadWorkspace, } from "../workspace/format.js";
10
+ import { git, gitText } from "../workspace/git.js";
11
+ import { commitFiles, openPullRequest, pushCommit, remoteBranch, } from "../workspace/publish.js";
12
+ import { isBlob, gitSnapshot, GIT_MODE } from "../workspace/snapshot.js";
13
+ import { acceptedCommit, gitRepoSource, recordFetch, trackingRef, } from "../workspace/repo-source.js";
14
+ import { metadata as packageMetadataFor, packageKindOf, assetKinds, assetNotFound, } from "../asset-kinds/index.js";
15
+ import { matchesOrigin } from "../server/origin.js";
15
16
  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();
17
+ import { applyFiles, decodeFiles, encodeFiles, findGit, locked, save, readWorkingCopy, } from "./workspace-store.js";
18
+ import { defined, only } from "../../shared/lookup.js";
19
+ import { NAME, splitOrigin } from "../../shared/patterns.js";
20
+ import { barndogPaths } from "../../config/paths.js";
21
+ /** Three random bytes provide six hex characters to distinguish work branches. */
22
+ const BRANCH_RANDOM_BYTES = 3;
23
+ async function latest(workspace, runtime) {
24
+ const model = await gitRepoSource(workspace, runtime).model();
19
25
  return {
20
26
  model,
21
- commit: (await acceptedCommit(workspace.workspaceId, home)),
27
+ commit: defined(await acceptedCommit(workspace.workspaceId, runtime), "This Git workspace hasn't been fetched yet"),
22
28
  };
23
29
  }
24
30
  function selectAsset(model, kind, name, origin) {
25
31
  const matches = model.assets.filter((asset) => asset.kind === kind &&
26
32
  asset.name === name &&
27
33
  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];
34
+ const match = only(matches);
35
+ if (!match) {
36
+ throw assetNotFound(kind, name, origin);
37
+ }
38
+ return match;
31
39
  }
40
+ /**
41
+ * The repository scope an origin selector names, for a new asset. A team or
42
+ * repo that has no folder yet is still accepted, so the first asset can create
43
+ * it; personal scopes don't exist in a Git workspace and are refused.
44
+ */
32
45
  export function selectScope(model, origin) {
33
46
  const matches = model.scopes.filter((scope) => matchesOrigin(scope, origin, model));
34
- if (origin === "me" || /^dev[/:]/.test(origin))
47
+ const { type, value: slug } = splitOrigin(origin);
48
+ if (origin === "me" || (type === "dev" && slug !== undefined)) {
35
49
  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(/[/:]/);
50
+ }
51
+ if (!matches.length && (type === "team" || type === "repo") && slug) {
38
52
  return {
39
53
  type,
40
54
  slug,
41
55
  path: `${type === "team" ? "teams" : "repos"}/${slug}`,
42
56
  };
43
57
  }
44
- if (matches.length !== 1)
58
+ const match = only(matches);
59
+ if (!match) {
45
60
  throw new CliError(`No scope named ${origin}. Use org, team/<slug> or repo/<slug>.`);
46
- return pickScope(matches[0]);
61
+ }
62
+ return pickScope(match);
47
63
  }
48
64
  const pickScope = (scope) => ({
49
65
  type: scope.type,
@@ -51,30 +67,11 @@ const pickScope = (scope) => ({
51
67
  path: scope.path,
52
68
  });
53
69
  const usable = (asset) => {
54
- if (asset.invalid)
70
+ if (asset.invalid) {
55
71
  throw new CliError(`${asset.path} is invalid: ${asset.invalid}. Fix it on the Git host first.`);
72
+ }
56
73
  return asset;
57
74
  };
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
75
  async function newFolder(cwd, target) {
79
76
  const path = resolve(cwd, target);
80
77
  await mkdir(dirname(path), { recursive: true });
@@ -82,20 +79,26 @@ async function newFolder(cwd, target) {
82
79
  await mkdir(path);
83
80
  return realpath(path);
84
81
  }
85
- async function startWorkingCopy(root, record, entries, base, home) {
82
+ async function startWorkingCopy(root, record, { entries, base }, runtime) {
86
83
  try {
87
- await writePackage(root, entries);
88
- await save({ ...record, root, base: encodeFiles(base), conflicts: [] }, home);
84
+ await writePackage(root, entries, runtime);
85
+ await save({ ...record, root, base: encodeFiles(base), conflicts: [] }, runtime);
89
86
  }
90
87
  catch (error) {
91
88
  await rm(root, { recursive: true, force: true });
92
89
  throw error;
93
90
  }
94
91
  }
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);
92
+ /**
93
+ * Creates and registers a working folder from the current Git workspace
94
+ * snapshot. Takes the working-copy lock and attempts a fetch, with cached
95
+ * content used if fetching fails. Rejects existing folders and invalid assets.
96
+ */
97
+ export function pullGitAsset(workspace, options, runtime) {
98
+ const { cwd } = runtime;
99
+ const { kind } = options;
100
+ return locked(runtime, async () => {
101
+ const { model, commit } = await latest(workspace, runtime);
99
102
  const asset = usable(selectAsset(model, kind, options.name, options.origin));
100
103
  const root = await newFolder(cwd, options.target ?? options.name);
101
104
  await startWorkingCopy(root, {
@@ -104,25 +107,35 @@ export function pullGitAsset(workspace, options, cwd, home = homedir()) {
104
107
  name: asset.name,
105
108
  scope: pickScope(asset.origin),
106
109
  baseCommit: commit,
107
- }, asset.entries, asset.entries, home);
110
+ }, { entries: asset.entries, base: asset.entries }, runtime);
108
111
  return { root, commit };
109
112
  });
110
113
  }
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);
114
+ /**
115
+ * Starts a working copy from the kind's scaffold, fetching workspace metadata
116
+ * first. Asset content is not pushed until `push`.
117
+ */
118
+ export function createGitAsset(workspace, options, runtime) {
119
+ const { cwd } = runtime;
120
+ const { kind } = options;
121
+ return locked(runtime, async () => {
122
+ if (!NAME.test(options.name)) {
123
+ throw new CliError(`${options.name} isn't a valid name. Use lowercase letters, digits and hyphens, such as my-skill.`);
124
+ }
125
+ const { model, commit } = await latest(workspace, runtime);
117
126
  const scope = selectScope(model, options.origin);
118
127
  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);
128
+ await startWorkingCopy(root, { kind, git: workspace, name: options.name, scope, baseCommit: commit }, { entries: assetKinds[kind].scaffold(options.name), base: [] }, runtime);
120
129
  return { root, kind, name: options.name };
121
130
  });
122
131
  }
123
- export function gitWorkingStatus(cwd, home = homedir()) {
124
- return locked(home, async () => {
125
- const work = await findGit(cwd, home);
132
+ /**
133
+ * The working copy containing `cwd`, with its edits as diffs against the commit
134
+ * it started from. Throws `CliError` outside a working copy.
135
+ */
136
+ export function gitWorkingStatus(runtime) {
137
+ return locked(runtime, async () => {
138
+ const work = await findGit(runtime);
126
139
  return {
127
140
  root: work.root,
128
141
  name: work.name,
@@ -135,37 +148,43 @@ export function gitWorkingStatus(cwd, home = homedir()) {
135
148
  conflicts: work.conflicts,
136
149
  pending: false,
137
150
  external: null,
138
- changes: await diffEntries(decodeFiles(work.base), await readDirectory(work.root)),
151
+ changes: await diffEntries(decodeFiles(work.base), await readWorkingCopy(work, runtime)),
139
152
  };
140
153
  });
141
154
  }
142
155
  const assetIn = (model, work) => model.assets.find((asset) => asset.kind === work.kind &&
143
- asset.path === assetFolder(work.scope.path, work.kind, work.name));
156
+ asset.path === assetPath(work.scope.path, work.kind, work.name));
144
157
  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));
158
+ async function branchFiles(work, head, runtime) {
159
+ const { home } = runtime;
160
+ const { branch } = defined(work.review, "This working copy has no review branch");
161
+ const repo = barndogPaths(home).bareClone(work.git.workspaceId);
162
+ await git(["fetch", "--quiet", "--no-tags", "origin", `refs/heads/${branch}`], runtime, { repo });
163
+ const model = await loadWorkspace(await gitSnapshot(repo, head, runtime));
155
164
  const asset = assetIn(model, work);
156
- if (!asset)
157
- throw new CliError(`${work.review.branch} no longer contains ${work.name}.`);
165
+ if (!asset) {
166
+ throw new CliError(`${branch} no longer contains ${work.name}.`);
167
+ }
158
168
  return usable(asset).entries;
159
169
  }
160
- export function updateGitWorkingCopy(cwd, home = homedir()) {
161
- return locked(home, async () => {
162
- const work = await findGit(cwd, home);
170
+ /**
171
+ * `pull` for a Git working copy: merges edits pushed to its review branch, then
172
+ * the newest default-branch content, into the folder. Conflicting text gets
173
+ * base/local/remote markers and is listed in `conflicts`; refuses to run while
174
+ * earlier conflicts are unresolved. Drops the review once the default branch
175
+ * holds its content.
176
+ */
177
+ export function updateGitWorkingCopy(runtime) {
178
+ const { home } = runtime;
179
+ return locked(runtime, async () => {
180
+ const work = await findGit(runtime);
163
181
  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);
182
+ if (work.conflicts.length) {
183
+ throw new CliError("Resolve the existing conflicts before pulling again.", "barndog resolve <path>");
184
+ }
185
+ const repo = barndogPaths(home).bareClone(work.git.workspaceId);
186
+ const { model, commit } = await latest(work.git, runtime);
187
+ let entries = await readWorkingCopy(work, runtime);
169
188
  const conflicts = new Set();
170
189
  const merge = async (base, incoming) => {
171
190
  const merged = await mergeEntries(base, entries, incoming);
@@ -173,9 +192,9 @@ export function updateGitWorkingCopy(cwd, home = homedir()) {
173
192
  merged.conflicts.forEach((path) => conflicts.add(path));
174
193
  };
175
194
  if (work.review) {
176
- const head = await remoteBranch(repo, work.review.branch);
195
+ const head = await remoteBranch(repo, work.review.branch, runtime);
177
196
  if (head && head !== work.review.head) {
178
- const remote = await branchFiles(work, head, home);
197
+ const remote = await branchFiles(work, head, runtime);
179
198
  await merge(decodeFiles(work.review.files), remote);
180
199
  work.review = {
181
200
  ...work.review,
@@ -187,17 +206,19 @@ export function updateGitWorkingCopy(cwd, home = homedir()) {
187
206
  const current = assetIn(model, work);
188
207
  if (current) {
189
208
  const incoming = usable(current).entries;
190
- if (fingerprint(incoming) !== fingerprint(decodeFiles(work.base)))
209
+ if (fingerprint(incoming) !== fingerprint(decodeFiles(work.base))) {
191
210
  await merge(decodeFiles(work.base), incoming);
211
+ }
192
212
  work.base = encodeFiles(incoming);
193
213
  // The review is over once its content is what the default branch holds.
194
214
  if (work.review &&
195
- fingerprint(incoming) === fingerprint(decodeFiles(work.review.files)))
215
+ fingerprint(incoming) === fingerprint(decodeFiles(work.review.files))) {
196
216
  delete work.review;
217
+ }
197
218
  }
198
219
  work.baseCommit = commit;
199
220
  work.conflicts = [...conflicts];
200
- await applyFiles(work, entries, home, previous);
221
+ await applyFiles(work, entries, runtime, previous);
201
222
  return {
202
223
  root: work.root,
203
224
  conflicts: work.conflicts,
@@ -206,46 +227,70 @@ export function updateGitWorkingCopy(cwd, home = homedir()) {
206
227
  };
207
228
  });
208
229
  }
209
- export function resolveGitConflict(path, cwd, home = homedir()) {
210
- return locked(home, async () => markResolved(await findGit(cwd, home), path, cwd, home));
230
+ /**
231
+ * Marks one conflicted file resolved, after checking its conflict markers are
232
+ * gone.
233
+ */
234
+ export function resolveGitConflict(path, runtime) {
235
+ const { cwd } = runtime;
236
+ return locked(runtime, async () => markResolved(await findGit(runtime), path, {
237
+ ...runtime,
238
+ cwd: cwd,
239
+ }));
211
240
  }
212
- export function pushGitWorkingCopy(workspace, options, cwd, home = homedir()) {
213
- return locked(home, async () => {
214
- const { model, commit: tip } = await latest(workspace, home);
241
+ /**
242
+ * `push` for a Git working copy. With `publish`, commits straight to the
243
+ * workspace's default branch; otherwise commits to a review branch
244
+ * (`barndog/<scope>-<name>-<random>`) and opens a pull request when the host
245
+ * allows one. Inside a folder that isn't a working copy yet, `origin` registers
246
+ * it first. Refused when the review branch moved on the host since the last
247
+ * pull, or, with `publish`, when the asset changed on the default branch.
248
+ */
249
+ export function pushGitWorkingCopy(workspace, options, runtime) {
250
+ const { home, cwd } = runtime;
251
+ return locked(runtime, async () => {
252
+ const { model, commit: tip } = await latest(workspace, runtime);
215
253
  let work;
216
254
  try {
217
- work = await findGit(cwd, home);
255
+ work = await findGit(runtime);
218
256
  }
219
257
  catch (error) {
220
- if (!options.origin || !(error instanceof CliError))
258
+ if (!options.origin || !(error instanceof CliError)) {
221
259
  throw error;
260
+ }
222
261
  const root = await realpath(cwd);
223
- const kind = options.kind ?? "skill";
262
+ const files = await readDirectory(root, runtime);
263
+ const kind = packageKindOf(files, options.kind);
224
264
  work = {
225
265
  root,
226
266
  kind,
227
267
  git: workspace,
228
- name: packageMetadataFor(await readDirectory(root), kind).name,
268
+ name: packageMetadataFor(files, kind).name,
229
269
  scope: selectScope(model, options.origin),
230
270
  baseCommit: tip,
231
271
  base: [],
232
272
  conflicts: [],
233
273
  };
234
- await save(work, home);
274
+ await save(work, runtime);
235
275
  }
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)
276
+ if (options.kind && work.kind !== options.kind) {
277
+ throw new CliError(`This working copy holds a ${work.kind}, not a ${options.kind}.`, "barndog status");
278
+ }
279
+ if (options.name && work.name !== options.name) {
280
+ throw new CliError(`This working copy is ${work.name}, not ${options.name}.`, "barndog status");
281
+ }
282
+ if (work.git.workspaceId !== workspace.workspaceId) {
241
283
  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);
284
+ }
285
+ if (work.conflicts.length) {
286
+ throw new CliError("Resolve the conflicts before pushing.", "barndog resolve <path>");
287
+ }
288
+ const files = validatePackageEntries(await readWorkingCopy(work, runtime), undefined, assetKinds[work.kind].manifest);
289
+ if (packageMetadataFor(files, work.kind).name !== work.name) {
290
+ throw new CliError(`This working copy's name must stay ${work.name}. Change it back, then push again.`);
291
+ }
292
+ const repo = barndogPaths(home).bareClone(workspace.workspaceId);
293
+ const path = assetPath(work.scope.path, work.kind, work.name);
249
294
  const change = {
250
295
  replace: path,
251
296
  files: files.map((file) => ({
@@ -257,39 +302,56 @@ export function pushGitWorkingCopy(workspace, options, cwd, home = homedir()) {
257
302
  if (options.publish) {
258
303
  const current = assetIn(model, work);
259
304
  if (fingerprint(current?.entries ?? []) !==
260
- fingerprint(decodeFiles(work.base)))
305
+ fingerprint(decodeFiles(work.base))) {
261
306
  throw new CliError(`${work.name} changed on ${workspace.branch} since you pulled it.`, "barndog pull");
262
- if (fingerprint(files) === fingerprint(decodeFiles(work.base)))
307
+ }
308
+ if (fingerprint(files) === fingerprint(decodeFiles(work.base))) {
263
309
  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], {
310
+ }
311
+ const commit = await commitFiles(repo, tip, {
312
+ ...change,
313
+ message: title,
314
+ }, { ...{}, runtime });
315
+ await pushCommit(repo, commit, workspace.branch, {
316
+ runtime,
317
+ allowPrompt: false,
318
+ });
319
+ await git(["update-ref", trackingRef(workspace.branch), commit], runtime, {
267
320
  repo,
268
321
  });
269
- await recordFetch(workspace, commit, home);
322
+ await recordFetch(workspace, commit, runtime);
270
323
  work.base = encodeFiles(files);
271
324
  work.baseCommit = commit;
272
325
  delete work.review;
273
- await save(work, home);
326
+ await save(work, runtime);
274
327
  return { branch: workspace.branch, commit, published: true };
275
328
  }
276
329
  let review = options.new ? undefined : work.review;
277
330
  if (review) {
278
- const head = await remoteBranch(repo, review.branch);
279
- if (head === null)
331
+ const head = await remoteBranch(repo, review.branch, runtime);
332
+ if (head === null) {
280
333
  review = undefined;
281
- else if (head !== review.head)
334
+ }
335
+ else if (head !== review.head) {
282
336
  throw new CliError(`${review.branch} changed on the Git host.`, "barndog pull");
337
+ }
283
338
  }
284
339
  const previous = review
285
340
  ? decodeFiles(review.files)
286
341
  : decodeFiles(work.base);
287
- if (fingerprint(files) === fingerprint(previous))
342
+ if (fingerprint(files) === fingerprint(previous)) {
288
343
  return { unchanged: true };
344
+ }
289
345
  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);
346
+ `barndog/${work.scope.type === "org" ? "org" : `${work.scope.type}-${work.scope.slug}`}-${work.name}-${randomBytes(BRANCH_RANDOM_BYTES).toString("hex")}`;
347
+ const commit = await commitFiles(repo, review?.head ?? work.baseCommit, {
348
+ ...change,
349
+ message: title,
350
+ }, { ...{}, runtime });
351
+ await pushCommit(repo, commit, branch, {
352
+ runtime,
353
+ allowPrompt: false,
354
+ });
293
355
  const opened = review?.url
294
356
  ? { url: review.url, opened: false }
295
357
  : await openPullRequest({
@@ -297,39 +359,42 @@ export function pushGitWorkingCopy(workspace, options, cwd, home = homedir()) {
297
359
  base: workspace.branch,
298
360
  branch,
299
361
  title,
300
- });
362
+ }, runtime);
301
363
  work.review = {
302
364
  branch,
303
365
  head: commit,
304
366
  files: encodeFiles(files),
305
367
  ...(opened.url ? { url: opened.url } : {}),
306
368
  };
307
- await save(work, home);
369
+ await save(work, runtime);
308
370
  return { branch, commit, url: opened.url ?? null, opened: opened.opened };
309
371
  });
310
372
  }
311
373
  /** 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 });
374
+ async function assetHistory(repo, commit, path, runtime) {
375
+ const output = await gitText(["log", "--reverse", "--format=%H%x00%ct%x00%an%x00%s", commit, "--", path], runtime, { repo });
314
376
  return output
315
377
  .split("\n")
316
378
  .filter(Boolean)
317
379
  .map((line, index) => {
318
380
  const [hash, time, author, subject] = line.split("\0");
381
+ if (!hash || author === undefined || subject === undefined) {
382
+ throw new Error(`Unexpected git log line: ${line}`);
383
+ }
319
384
  return {
320
385
  number: index + 1,
321
386
  commit: hash,
322
- publishedAt: new Date(Number(time) * 1000).toISOString(),
387
+ publishedAt: new Date(Number(time) * MILLISECONDS_PER_SECOND).toISOString(),
323
388
  publishedBy: author,
324
389
  description: subject,
325
390
  };
326
391
  });
327
392
  }
328
- async function filesAt(repo, commit, path) {
329
- const snapshot = await gitSnapshot(repo, commit);
393
+ async function filesAt(repo, commit, path, runtime) {
394
+ const snapshot = await gitSnapshot(repo, commit, runtime);
330
395
  const single = snapshot.entries.find((entry) => entry.path === path);
331
- const members = single && single.mode !== TREE_MODE
332
- ? [{ ...single, path: path.split("/").at(-1) }]
396
+ const members = single && single.mode !== GIT_MODE.tree
397
+ ? [{ ...single, path: path.slice(path.lastIndexOf("/") + 1) }]
333
398
  : snapshot.entries
334
399
  .filter((entry) => entry.path.startsWith(`${path}/`) && isBlob(entry.mode))
335
400
  .map((entry) => ({
@@ -339,24 +404,43 @@ async function filesAt(repo, commit, path) {
339
404
  const blobs = await snapshot.readBlobs(members.map((entry) => entry.hash));
340
405
  return members.map((entry) => ({
341
406
  path: entry.path,
342
- data: blobs.get(entry.hash),
343
- executable: entry.mode === "100755",
407
+ data: defined(blobs.get(entry.hash), `Git object ${entry.hash} wasn't read`),
408
+ executable: entry.mode === GIT_MODE.executable,
344
409
  }));
345
410
  }
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)
411
+ /** An asset's published history: one version per commit that changed it. */
412
+ async function history(workspace, target, runtime) {
413
+ const { home } = runtime;
414
+ const { model, commit } = await latest(workspace, runtime);
415
+ const asset = selectAsset(model, target.kind, target.name, target.origin);
416
+ const repo = barndogPaths(home).bareClone(workspace.workspaceId);
417
+ const versions = await assetHistory(repo, commit, asset.path, runtime);
418
+ const filesOf = (number = versions.length) => {
419
+ const version = versions[number - 1];
420
+ if (!version) {
356
421
  throw new CliError(`${asset.name} has no version ${number}.`);
357
- return filesAt(repo, version.commit, asset.path);
422
+ }
423
+ return filesAt(repo, version.commit, asset.path, runtime);
358
424
  };
359
- if (action === "version-show")
360
- return { files: encodeFiles(await at(options.version)) };
361
- return diffEntries(await at(options.from), await at(options.to));
425
+ return { versions, filesOf };
426
+ }
427
+ /**
428
+ * Every commit that changed the asset's folder, oldest first and numbered from
429
+ * 1, as Git workspaces have no published version numbers of their own.
430
+ */
431
+ export async function gitVersions(workspace, target, runtime) {
432
+ return (await history(workspace, target, runtime)).versions;
433
+ }
434
+ /** A version's files, base64-encoded; the newest when `version` is left out. */
435
+ export async function gitVersionFiles(workspace, target, runtime) {
436
+ const { filesOf } = await history(workspace, target, runtime);
437
+ return { files: encodeFiles(await filesOf(target.version)) };
438
+ }
439
+ /**
440
+ * What changed in the asset between two versions, numbered as `gitVersions()`
441
+ * numbers them.
442
+ */
443
+ export async function gitVersionDiff(workspace, target, runtime) {
444
+ const { filesOf } = await history(workspace, target, runtime);
445
+ return diffEntries(await filesOf(target.from), await filesOf(target.to));
362
446
  }