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,3 +1,4 @@
1
+ import { GIT_MODE } from "./snapshot.js";
1
2
  import { execFile } from "node:child_process";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { rm } from "node:fs/promises";
@@ -5,86 +6,115 @@ import { join } from "node:path";
5
6
  import { promisify } from "node:util";
6
7
  import { normalizeRepositoryRemote } from "@barndog-ai/api-contract";
7
8
  import { CliError } from "../../errors.js";
8
- import { explainIdentity, git, GitError, gitReason, gitText } from "./git.js";
9
+ import { explainIdentity, git, GitError, gitReason, gitText, parseLsRemote, } from "./git.js";
10
+ /** Git SHA-1 object IDs contain forty hexadecimal digits. */
11
+ const SHA1_HEX_LENGTH = 40;
9
12
  const execute = promisify(execFile);
10
- const NULL_HASH = "0".repeat(40);
13
+ const NULL_HASH = "0".repeat(SHA1_HEX_LENGTH);
11
14
  /** Builds a commit in a bare repository using a throwaway index, never a checkout. */
12
- export async function commitFiles(repo, parent, change, message, options = {}) {
15
+ export async function commitFiles(repo, parent, change, options) {
16
+ const { runtime } = options;
13
17
  const index = join(repo, `barndog-index-${randomUUID()}`);
14
18
  const env = { GIT_INDEX_FILE: index };
15
19
  try {
16
- if (parent)
17
- await git(["read-tree", parent], { repo, env });
20
+ if (parent) {
21
+ await git(["read-tree", parent], runtime, { repo, env });
22
+ }
18
23
  const updates = [];
19
24
  if (parent && change.replace) {
20
- const listing = await git(["ls-tree", "-r", "-z", "--name-only", parent, "--", change.replace], { repo });
21
- for (const path of listing.toString("utf8").split("\0").filter(Boolean))
25
+ const listing = await git(["ls-tree", "-r", "-z", "--name-only", parent, "--", change.replace], runtime, { repo });
26
+ for (const path of listing.toString("utf8").split("\0").filter(Boolean)) {
22
27
  updates.push(`0 ${NULL_HASH}\t${path}`);
28
+ }
23
29
  }
24
30
  for (const file of change.files) {
25
- const hash = await gitText(["hash-object", "-w", "--stdin"], {
31
+ const hash = await gitText(["hash-object", "-w", "--stdin"], runtime, {
26
32
  repo,
27
33
  input: file.data,
28
34
  });
29
- updates.push(`${file.executable ? "100755" : "100644"} ${hash}\t${file.path}`);
35
+ updates.push(`${file.executable ? GIT_MODE.executable : GIT_MODE.file} ${hash}\t${file.path}`);
30
36
  }
31
- await git(["update-index", "-z", "--index-info"], {
37
+ await git(["update-index", "-z", "--index-info"], runtime, {
32
38
  repo,
33
39
  env,
34
40
  input: updates.join("\0") + "\0",
35
41
  });
36
- const tree = await gitText(["write-tree"], { repo, env });
37
- return await gitText(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", message], { repo, allowPrompt: options.allowPrompt }).catch(explainIdentity);
42
+ const tree = await gitText(["write-tree"], runtime, { repo, env });
43
+ return await gitText([
44
+ "commit-tree",
45
+ tree,
46
+ ...(parent ? ["-p", parent] : []),
47
+ "-m",
48
+ change.message,
49
+ ], runtime, { repo, allowPrompt: options.allowPrompt }).catch((error) => explainIdentity(error, runtime.platform));
38
50
  }
39
51
  finally {
40
52
  await rm(index, { force: true });
41
53
  await rm(`${index}.lock`, { force: true });
42
54
  }
43
55
  }
44
- export async function pushCommit(repo, commit, branch, allowPrompt = false) {
56
+ /**
57
+ * Pushes a commit to an origin branch; prompts are opt-in and Git rejections
58
+ * become CLI errors.
59
+ */
60
+ export async function pushCommit(repo, commit, branch, options) {
61
+ const { runtime, allowPrompt = false } = options;
45
62
  try {
46
- await git(["push", "--quiet", "origin", `${commit}:refs/heads/${branch}`], {
63
+ await git(["push", "--quiet", "origin", `${commit}:refs/heads/${branch}`], runtime, {
47
64
  repo,
48
65
  allowPrompt,
49
66
  });
50
67
  }
51
68
  catch (error) {
52
- if (error instanceof GitError)
69
+ if (error instanceof GitError) {
53
70
  throw new CliError(`The Git host rejected the push to ${branch}: ${gitReason(error.stderr)}`, undefined, { cause: error });
71
+ }
54
72
  throw error;
55
73
  }
56
74
  }
57
75
  /** The tip of a branch on the host, or null when it no longer exists. */
58
- export async function remoteBranch(repo, branch) {
59
- const output = await gitText(["ls-remote", "origin", `refs/heads/${branch}`], {
76
+ export async function remoteBranch(repo, branch, runtime) {
77
+ const output = await gitText(["ls-remote", "origin", `refs/heads/${branch}`], runtime, {
60
78
  repo,
61
79
  });
62
- return output ? output.split(/\s/)[0] : null;
80
+ return parseLsRemote(output)[0]?.commit ?? null;
63
81
  }
64
- export function hostOf(url) {
82
+ /**
83
+ * Extracts a normalized credential-free host and repository path from a remote
84
+ * URL; invalid remotes return null.
85
+ */
86
+ function hostOf(url) {
65
87
  const remote = normalizeRepositoryRemote(url);
66
- if (!remote)
88
+ if (!remote) {
67
89
  return null;
90
+ }
68
91
  const [host, ...path] = remote.split("/");
69
- if (!host || path.length < 2)
92
+ if (!host || path.length < 2) {
70
93
  return null;
94
+ }
71
95
  return { host, path: path.join("/") };
72
96
  }
73
97
  /** A browser link that starts a pull request, for hosts with a known URL shape. */
74
- export function compareUrl(url, base, branch) {
98
+ function compareUrl(url, base, branch) {
75
99
  const remote = hostOf(url);
76
- if (!remote)
100
+ if (!remote) {
77
101
  return null;
102
+ }
78
103
  const encoded = branch.split("/").map(encodeURIComponent).join("/");
79
- if (remote.host.includes("github"))
104
+ if (remote.host.includes("github")) {
80
105
  return `https://${remote.host}/${remote.path}/compare/${encodeURIComponent(base)}...${encoded}?expand=1`;
81
- if (remote.host.includes("gitlab"))
106
+ }
107
+ if (remote.host.includes("gitlab")) {
82
108
  return `https://${remote.host}/${remote.path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=${encodeURIComponent(branch)}&merge_request%5Btarget_branch%5D=${encodeURIComponent(base)}`;
109
+ }
83
110
  return null;
84
111
  }
85
- const signedIn = async (tool, host) => {
112
+ const signedIn = async (tool, host, runtime) => {
86
113
  try {
87
114
  await execute(tool, ["auth", "status", "--hostname", host], {
115
+ env: { ...runtime.env },
116
+ cwd: runtime.cwd,
117
+ windowsHide: true,
88
118
  timeout: 15_000,
89
119
  });
90
120
  return true;
@@ -93,24 +123,23 @@ const signedIn = async (tool, host) => {
93
123
  return false;
94
124
  }
95
125
  };
96
- const firstUrl = (text) => /https?:\/\/\S+/.exec(text)?.[0];
97
- /** Opens the review with gh or glab when signed in, else hands back a link. */
98
- export async function openPullRequest(request) {
99
- const { url, base, branch, title } = request;
100
- const remote = hostOf(url);
101
- const fallback = {
102
- url: compareUrl(url, base, branch) ?? undefined,
103
- opened: false,
104
- };
105
- if (!remote)
106
- return fallback;
107
- const command = remote.host.includes("github")
108
- ? [
126
+ /**
127
+ * The first web link in a tool's output: `Created https://github.com/o/r/pull/1` → the link.
128
+ *
129
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
130
+ */
131
+ export const firstUrl = (text) => /https?:\/\/\S+/.exec(text)?.[0];
132
+ /** The gh or glab command that opens a review of `branch` against `base`, if the host has one. */
133
+ function pullRequestCommand(remote, change) {
134
+ const repository = `${remote.host}/${remote.path}`;
135
+ const { base, branch, title } = change;
136
+ if (remote.host.includes("github")) {
137
+ return [
109
138
  "gh",
110
139
  "pr",
111
140
  "create",
112
141
  "--repo",
113
- `${remote.host}/${remote.path}`,
142
+ repository,
114
143
  "--head",
115
144
  branch,
116
145
  "--base",
@@ -119,29 +148,49 @@ export async function openPullRequest(request) {
119
148
  title,
120
149
  "--body",
121
150
  "",
122
- ]
123
- : remote.host.includes("gitlab")
124
- ? [
125
- "glab",
126
- "mr",
127
- "create",
128
- "-R",
129
- `${remote.host}/${remote.path}`,
130
- "-s",
131
- branch,
132
- "-b",
133
- base,
134
- "-t",
135
- title,
136
- "-d",
137
- "",
138
- "-y",
139
- ]
140
- : null;
141
- if (!command || !(await signedIn(command[0], remote.host)))
151
+ ];
152
+ }
153
+ if (remote.host.includes("gitlab")) {
154
+ return [
155
+ "glab",
156
+ "mr",
157
+ "create",
158
+ "-R",
159
+ repository,
160
+ "-s",
161
+ branch,
162
+ "-b",
163
+ base,
164
+ "-t",
165
+ title,
166
+ "-d",
167
+ "",
168
+ "-y",
169
+ ];
170
+ }
171
+ return null;
172
+ }
173
+ /** Opens the review with gh or glab when signed in, else hands back a link. */
174
+ export async function openPullRequest(request, runtime) {
175
+ const { url, base, branch, title } = request;
176
+ const remote = hostOf(url);
177
+ const fallback = {
178
+ url: compareUrl(url, base, branch) ?? undefined,
179
+ opened: false,
180
+ };
181
+ if (!remote) {
182
+ return fallback;
183
+ }
184
+ const command = pullRequestCommand(remote, { base, branch, title });
185
+ const [program, ...args] = command ?? [];
186
+ if (!program || !(await signedIn(program, remote.host, runtime))) {
142
187
  return fallback;
188
+ }
143
189
  try {
144
- const { stdout } = await execute(command[0], command.slice(1), {
190
+ const { stdout } = await execute(program, args, {
191
+ env: { ...runtime.env },
192
+ cwd: runtime.cwd,
193
+ windowsHide: true,
145
194
  timeout: 60_000,
146
195
  });
147
196
  return { url: firstUrl(stdout) ?? fallback.url, opened: true };
@@ -151,10 +200,12 @@ export async function openPullRequest(request) {
151
200
  }
152
201
  }
153
202
  /** Reports branch protection where the host will say; null means it can't tell. */
154
- export async function branchProtected(url, branch) {
203
+ export async function branchProtected(url, branch, runtime) {
155
204
  const remote = hostOf(url);
156
- if (!remote?.host.includes("github") || !(await signedIn("gh", remote.host)))
205
+ if (!remote?.host.includes("github") ||
206
+ !(await signedIn("gh", remote.host, runtime))) {
157
207
  return null;
208
+ }
158
209
  try {
159
210
  const { stdout } = await execute("gh", [
160
211
  "api",
@@ -163,7 +214,12 @@ export async function branchProtected(url, branch) {
163
214
  `repos/${remote.path}/branches/${encodeURIComponent(branch)}`,
164
215
  "--jq",
165
216
  ".protected",
166
- ], { timeout: 15_000 });
217
+ ], {
218
+ timeout: 15_000,
219
+ env: { ...runtime.env },
220
+ cwd: runtime.cwd,
221
+ windowsHide: true,
222
+ });
167
223
  return stdout.trim() === "true";
168
224
  }
169
225
  catch {
@@ -0,0 +1,193 @@
1
+ import { gitAccessCommand } from "../../platform.js";
2
+ import { POSIX_MODE, HOURS_PER_DAY, MILLISECONDS_PER_MINUTE, MINUTES_PER_HOUR, } from "../../shared/constants.js";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdir } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { CliError } from "../../errors.js";
7
+ import { storePackage } from "./packages.js";
8
+ import { loadWorkspace, } from "./format.js";
9
+ import { git, GitError, gitReason, gitText } from "./git.js";
10
+ import { folderSnapshot, gitSnapshot } from "./snapshot.js";
11
+ import { defined } from "../../shared/lookup.js";
12
+ import { z } from "zod";
13
+ import { readJsonIfExists, writeAtomic } from "../../shared/files.js";
14
+ import { barndogPaths } from "../../config/paths.js";
15
+ /** Display ages of at least two days in days. */
16
+ const AGE_IN_DAYS_THRESHOLD_HOURS = 48;
17
+ function repoSource(backend, runtime) {
18
+ let loading;
19
+ const model = () => (loading ??= backend.open().then((snapshot) => loadWorkspace(snapshot, backend.workspaceId, {
20
+ localOnly: backend.localOnly ?? false,
21
+ })));
22
+ const find = async (reference) => {
23
+ const asset = (await model()).assets.find((a) => a.id === reference.id);
24
+ if (!asset || asset.publishedVersion !== reference.publishedVersion) {
25
+ throw new CliError("The catalog changed while syncing.", "barndog sync");
26
+ }
27
+ if (asset.invalid) {
28
+ throw new CliError(`${asset.path} is invalid: ${asset.invalid}`);
29
+ }
30
+ return asset;
31
+ };
32
+ return {
33
+ cacheKey: backend.cacheKey,
34
+ journal: { workspaceId: backend.workspaceId },
35
+ label: backend.label,
36
+ model,
37
+ catalog: async () => (await model()).catalog,
38
+ invalidAssets: async () => (await model()).invalid,
39
+ notices: () => backend.notices(),
40
+ warnings: async () => {
41
+ const { invalidKnowledge, problems } = await model();
42
+ return [
43
+ ...invalidKnowledge.map((problem) => `Knowledge file ${problem.path} was skipped: ${problem.reason}`),
44
+ ...problems
45
+ .filter((problem) => problem.badName)
46
+ .map((problem) => `${problem.path} was skipped: ${problem.reason}. Rename it to deliver it.`),
47
+ ];
48
+ },
49
+ packageFolder: async (kind, reference) => {
50
+ const asset = await find(reference);
51
+ return storePackage(kind, {
52
+ id: asset.id,
53
+ name: asset.name,
54
+ revision: asset.publishedVersion,
55
+ }, { key: backend.cacheKey, runtime }, () => Promise.resolve(asset.entries));
56
+ },
57
+ mcpDefinition: async (reference) => defined((await find(reference)).definition, `${reference.name} has no MCP definition`),
58
+ };
59
+ }
60
+ /**
61
+ * The local folder workspace (`~/.barndog/workspace` by default) as a workspace
62
+ * source. Reads the folder directly; nothing is fetched.
63
+ */
64
+ export function localRepoSource(workspace, runtime) {
65
+ return repoSource({
66
+ cacheKey: join("local", workspace.workspaceId),
67
+ workspaceId: workspace.workspaceId,
68
+ label: workspace.path,
69
+ open: () => folderSnapshot(workspace.path, runtime),
70
+ notices: () => [],
71
+ localOnly: true,
72
+ }, runtime);
73
+ }
74
+ /** Background refresh policy: check at most every five minutes (milliseconds). */
75
+ const AUTO_FETCH_INTERVAL_MS = 300000;
76
+ const fetchStateSchema = z.looseObject({
77
+ /** The branch tip this machine last read. */
78
+ accepted: z.string().optional(),
79
+ fetchedAt: z.string().optional(),
80
+ });
81
+ /**
82
+ * The commit this machine last accepted from the Git host and when it fetched;
83
+ * empty before the first fetch.
84
+ */
85
+ export async function readFetchState(workspaceId, runtime) {
86
+ const { home } = runtime;
87
+ return ((await readJsonIfExists(barndogPaths(home).fetchState(workspaceId), fetchStateSchema)) ?? {});
88
+ }
89
+ async function writeFetchState(workspaceId, runtime, state) {
90
+ const { home } = runtime;
91
+ await writeAtomic(barndogPaths(home).fetchState(workspaceId), JSON.stringify(state));
92
+ }
93
+ /** Creates or repairs the bare clone; nothing is ever checked out of it. */
94
+ export async function ensureBareClone(repo, url, runtime) {
95
+ await mkdir(repo, { recursive: true, mode: POSIX_MODE.privateDirectory });
96
+ await git(["init", "--quiet", "--bare", "."], runtime, { repo });
97
+ await git(["config", "remote.origin.url", url], runtime, { repo });
98
+ }
99
+ /**
100
+ * Fetches one branch into the bare clone's tracking ref, without tags.
101
+ * Credential prompts stay off unless `allowPrompt`, so a missing login fails
102
+ * instead of hanging.
103
+ */
104
+ export const fetchBranch = (repo, branch, runtime, allowPrompt = false) => git([
105
+ "fetch",
106
+ "--quiet",
107
+ "--prune",
108
+ "--no-tags",
109
+ "origin",
110
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
111
+ ], runtime, { repo, allowPrompt });
112
+ /** The ref the bare clone keeps a fetched branch in. */
113
+ export function trackingRef(branch) {
114
+ return `refs/remotes/origin/${branch}`;
115
+ }
116
+ const age = (fetchedAt) => {
117
+ if (!fetchedAt) {
118
+ return "an unknown time";
119
+ }
120
+ const minutes = Math.round((Date.now() - Date.parse(fetchedAt)) / MILLISECONDS_PER_MINUTE);
121
+ if (minutes < 1) {
122
+ return "less than a minute";
123
+ }
124
+ if (minutes < MINUTES_PER_HOUR) {
125
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
126
+ }
127
+ const hours = Math.round(minutes / MINUTES_PER_HOUR);
128
+ return hours < AGE_IN_DAYS_THRESHOLD_HOURS
129
+ ? `${hours} hour${hours === 1 ? "" : "s"}`
130
+ : `${Math.round(hours / HOURS_PER_DAY)} days`;
131
+ };
132
+ /**
133
+ * Reads a Git workspace, fetching by default. Auto refresh reuses a successful
134
+ * fetch for five minutes; none uses only the accepted commit. A failed branch
135
+ * fetch falls back to that commit when available and adds a notice.
136
+ */
137
+ export function gitRepoSource(workspace, runtime, options = {}) {
138
+ const { home } = runtime;
139
+ const repo = barndogPaths(home).bareClone(workspace.workspaceId);
140
+ const notices = [];
141
+ async function currentCommit() {
142
+ const state = await readFetchState(workspace.workspaceId, runtime);
143
+ const policy = options.refresh ?? "always";
144
+ const recent = state.fetchedAt &&
145
+ Date.now() - Date.parse(state.fetchedAt) < AUTO_FETCH_INTERVAL_MS;
146
+ if (policy === "none" || (policy === "auto" && recent && state.accepted)) {
147
+ if (!state.accepted) {
148
+ throw new CliError("This Git workspace hasn't been fetched yet.", "barndog sync");
149
+ }
150
+ return state.accepted;
151
+ }
152
+ await ensureBareClone(repo, workspace.url, runtime);
153
+ try {
154
+ await fetchBranch(repo, workspace.branch, runtime);
155
+ }
156
+ catch (error) {
157
+ if (!(error instanceof GitError)) {
158
+ throw error;
159
+ }
160
+ if (!state.accepted) {
161
+ throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, gitAccessCommand(workspace.url, runtime.platform), { cause: error });
162
+ }
163
+ notices.push(`Can't reach ${workspace.url}, so this uses what was fetched ${age(state.fetchedAt)} ago.`);
164
+ return state.accepted;
165
+ }
166
+ const tip = await gitText(["rev-parse", "--verify", trackingRef(workspace.branch)], runtime, { repo });
167
+ await writeFetchState(workspace.workspaceId, runtime, {
168
+ accepted: tip,
169
+ fetchedAt: new Date().toISOString(),
170
+ });
171
+ return tip;
172
+ }
173
+ return repoSource({
174
+ cacheKey: join("git", createHash("sha256").update(workspace.workspaceId).digest("hex")),
175
+ workspaceId: workspace.workspaceId,
176
+ label: workspace.url,
177
+ open: async () => gitSnapshot(repo, await currentCommit(), runtime),
178
+ notices: () => notices,
179
+ }, runtime);
180
+ }
181
+ /**
182
+ * Records an accepted workspace commit and fetch timestamp after setup or
183
+ * publication. Auto-refresh readers can reuse it without another fetch.
184
+ */
185
+ export async function recordFetch(workspace, commit, runtime) {
186
+ await writeFetchState(workspace.workspaceId, runtime, {
187
+ accepted: commit,
188
+ fetchedAt: new Date().toISOString(),
189
+ });
190
+ }
191
+ export const acceptedCommit = async (workspaceId, runtime) => {
192
+ return (await readFetchState(workspaceId, runtime)).accepted;
193
+ };