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