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,34 +1,55 @@
1
+ import { fixSteps } from "../../platform.js";
2
+ import { HTTP_STATUS } from "../../shared/constants.js";
1
3
  import { randomUUID } from "node:crypto";
2
4
  import { z } from "zod";
3
- import { ApiError, gitConnectionSchema, gitPullSchema, gitPullDetailsSchema, } from "@barndog-ai/api-contract";
5
+ import { ApiError, gitConnectionSchema, gitPullSchema, gitPullDetailsSchema, gitProposalSchema, gitRevisionSchema, } from "@barndog-ai/api-contract";
4
6
  import { packageFingerprint, } from "@barndog-ai/api-contract/package";
5
- import { mergeEntries, readDirectory, } from "@barndog-ai/api-contract/collaboration";
6
- import { metadata as packageMetadataFor } from "./domain.js";
7
- import { download } from "./remote.js";
8
- import { request, getAsset } from "../environment/remote.js";
9
- import { encodeFiles, decodeFiles, save, applyFiles, } from "./workspace-store.js";
10
- export async function externalSource(work, home) {
11
- if (!work.skillId)
7
+ import { mergeEntries } from "@barndog-ai/api-contract/collaboration";
8
+ import { metadata as packageMetadataFor } from "../asset-kinds/index.js";
9
+ import { downloadPull, downloadVersion } from "./remote.js";
10
+ import { getAsset } from "../server/catalog.js";
11
+ import { parsed } from "../server/client.js";
12
+ import { encodeFiles, decodeFiles, save, applyFiles, readWorkingCopy, } from "./workspace-store.js";
13
+ import { defined } from "../../shared/lookup.js";
14
+ import { CliError } from "../../errors.js";
15
+ import { apiClient } from "../auth/transport.js";
16
+ const publishedId = (work) => defined(work.assetId, "This working copy isn't published yet");
17
+ /**
18
+ * The GitHub connection that is authoritative for this working copy's asset, if
19
+ * any. Throws when the authority changed since the copy was made, when the
20
+ * connection needs attention, or when an internal upload is still pending.
21
+ */
22
+ export async function externalSource(work, runtime) {
23
+ if (!work.assetId) {
12
24
  return undefined;
13
- const connections = await request(work.connection, "/v1/git-connections", z.array(gitConnectionSchema), home);
14
- const source = connections.find((c) => c.assetId === work.skillId &&
25
+ }
26
+ const connections = await parsed(z.array(gitConnectionSchema), apiClient(work.connection.server, runtime).GET("/v1/git-connections"));
27
+ const source = connections.find((c) => c.assetId === work.assetId &&
15
28
  c.kind === work.kind &&
16
29
  c.authority === "github");
17
- if (work.external && (!source || source.id !== work.external.id))
18
- throw new Error("External content authority changed; preserve this working copy and pull a new one");
19
- if (source && source.status !== "active")
20
- throw new Error(`GitHub synchronization requires attention: ${source.lastError ?? source.status}`);
21
- if (source && work.pending)
22
- throw new Error("An internal submission is pending; resolve it before using GitHub");
30
+ if (work.external && (!source || source.id !== work.external.id)) {
31
+ throw new CliError("This asset's GitHub connection changed on the server. Save your edits elsewhere, then pull a fresh working copy.", "barndog pull");
32
+ }
33
+ if (source && source.status !== "active") {
34
+ throw new CliError(`GitHub sync needs attention: ${source.lastError ?? source.status}.`, "barndog github list");
35
+ }
36
+ if (source && work.pending) {
37
+ throw new CliError("A push to BarnDog is still waiting for confirmation. Retry it before using GitHub.", "barndog push");
38
+ }
23
39
  return source;
24
40
  }
25
- export async function pullExternal(work, source, entries, previous, home) {
41
+ /**
42
+ * `pull` for a GitHub-authoritative asset: merges edits made to its pull
43
+ * request, then newly published main content, into the folder.
44
+ */
45
+ export async function pullExternal(work, { source, entries, previous, }, runtime) {
26
46
  work.external ??= { id: source.id };
27
- const conflicts = new Set(), external = work.external;
47
+ const conflicts = new Set();
48
+ const external = work.external;
28
49
  if (external.pull) {
29
- const { pull } = await request(work.connection, `/v1/git-connections/${source.id}/pulls/${external.pull.number}`, gitPullDetailsSchema, home);
50
+ const { pull } = await parsed(gitPullDetailsSchema, apiClient(work.connection.server, runtime).GET("/v1/git-connections/{id}/pulls/{number}", { params: { path: { id: source.id, number: external.pull.number } } }));
30
51
  if (pull.head !== external.pull.head) {
31
- const remote = await download(`/v1/git-connections/${source.id}/pulls/${pull.number}/package`, work.connection, home, pull.head, work.kind);
52
+ const remote = await downloadPull({ connectionId: source.id, number: pull.number, head: pull.head }, work.connection, { runtime, kind: work.kind });
32
53
  const merged = await mergeEntries(decodeFiles(external.pull.files), entries, remote);
33
54
  entries = merged.entries;
34
55
  merged.conflicts.forEach((p) => conflicts.add(p));
@@ -38,14 +59,20 @@ export async function pullExternal(work, source, entries, previous, home) {
38
59
  files: encodeFiles(remote),
39
60
  };
40
61
  }
41
- if (pull.merged)
62
+ if (pull.merged) {
42
63
  delete external.pull;
64
+ }
65
+ }
66
+ const asset = await getAsset(work.kind, publishedId(work), work.connection, runtime);
67
+ if (!("commit" in asset.version)) {
68
+ throw new Error("The server returned a GitHub-connected version without its Git commit");
43
69
  }
44
- const asset = await getAsset(work.kind, work.skillId, work.connection, home);
45
- if (!("commit" in asset.version))
46
- throw new Error("Expected a Git-backed package version");
47
70
  if (asset.version.id !== work.baseVersionId) {
48
- const latest = await download(`/v1/skills/${work.skillId}/versions/${asset.version.number}/package`, work.connection, home, asset.version.commit, work.kind);
71
+ const latest = await downloadVersion({
72
+ id: publishedId(work),
73
+ number: asset.version.number,
74
+ commit: asset.version.commit,
75
+ }, work.connection, { runtime, kind: work.kind });
49
76
  const merged = await mergeEntries(decodeFiles(work.base), entries, latest);
50
77
  entries = merged.entries;
51
78
  merged.conflicts.forEach((p) => conflicts.add(p));
@@ -54,7 +81,7 @@ export async function pullExternal(work, source, entries, previous, home) {
54
81
  work.baseNumber = asset.version.number;
55
82
  }
56
83
  work.conflicts = [...conflicts];
57
- await applyFiles(work, entries, home, previous);
84
+ await applyFiles(work, entries, runtime, previous);
58
85
  return {
59
86
  root: work.root,
60
87
  conflicts: work.conflicts,
@@ -62,58 +89,94 @@ export async function pullExternal(work, source, entries, previous, home) {
62
89
  external: { connectionId: source.id, pull: external.pull?.number },
63
90
  };
64
91
  }
65
- export async function pushExternal(work, source, options, home) {
92
+ /**
93
+ * `push` for a GitHub-authoritative asset: opens or revises its pull request
94
+ * with the complete package and, with `publish`, merges it. The request and
95
+ * retry key are saved first so an ambiguous failure retries exactly; a
96
+ * definitive refusal (400, 403, 404, 409, 413) drops it so local edits can be
97
+ * reconciled.
98
+ */
99
+ export async function pushExternal(work, source, options, runtime) {
66
100
  work.external ??= { id: source.id };
67
- const external = work.external, path = `/v1/git-connections/${source.id}`;
101
+ const external = work.external;
102
+ const client = apiClient(work.connection.server, runtime);
103
+ const merge = (number, expectedCommit) => parsed(gitConnectionSchema, client.PUT("/v1/git-connections/{id}/pulls/{number}/merge", {
104
+ params: { path: { id: source.id, number } },
105
+ body: { expectedCommit },
106
+ }));
68
107
  if (!external.pending) {
69
- const asset = await getAsset(work.kind, work.skillId, work.connection, home);
70
- if (asset.version.id !== work.baseVersionId)
71
- throw new Error("Published GitHub content changed; run barndog pull before pushing");
108
+ const asset = await getAsset(work.kind, publishedId(work), work.connection, runtime);
109
+ if (asset.version.id !== work.baseVersionId) {
110
+ throw new CliError("The published content on GitHub changed since your last pull.", "barndog pull");
111
+ }
72
112
  let pull = external.pull
73
- ? (await request(work.connection, `${path}/pulls/${external.pull.number}`, gitPullDetailsSchema, home)).pull
113
+ ? (await parsed(gitPullDetailsSchema, client.GET("/v1/git-connections/{id}/pulls/{number}", {
114
+ params: {
115
+ path: { id: source.id, number: external.pull.number },
116
+ },
117
+ }))).pull
74
118
  : undefined;
75
- if (pull?.state === "closed" && !options.new)
76
- throw new Error("Pull request is closed; run barndog pull, then push --new to contribute again");
77
- if (pull && pull.head !== external.pull.head)
78
- throw new Error("Pull request changed remotely; run barndog pull before pushing");
79
- if (options.new)
119
+ if (pull?.state === "closed" && !options.new) {
120
+ throw new CliError("The pull request is closed. Pull, then push a new one.", fixSteps(["barndog pull", "barndog push --new"], runtime.platform));
121
+ }
122
+ if (pull && pull.head !== external.pull?.head) {
123
+ throw new CliError("The pull request changed on GitHub since your last pull.", "barndog pull");
124
+ }
125
+ if (options.new) {
80
126
  pull = undefined;
81
- const files = await readDirectory(work.root);
82
- if (packageMetadataFor(files, work.kind).name !== work.name)
83
- throw new Error("Package name cannot change in this working copy");
84
- const previous = pull ? external.pull.files : work.base;
127
+ }
128
+ const files = await readWorkingCopy(work, runtime);
129
+ if (packageMetadataFor(files, work.kind).name !== work.name) {
130
+ throw new CliError(`This working copy's name must stay ${work.name}. Change it back, then push again.`);
131
+ }
132
+ const previous = (pull && external.pull?.files) || work.base;
85
133
  if (packageFingerprint(files) === packageFingerprint(decodeFiles(previous)) &&
86
134
  !options.title) {
87
- if (options.publish && pull)
88
- return request(work.connection, `${path}/pulls/${pull.number}/merge`, gitConnectionSchema, home, "PUT", { expectedCommit: pull.head });
135
+ if (options.publish && pull) {
136
+ return merge(pull.number, pull.head);
137
+ }
89
138
  return { unchanged: true, pull: pull?.number };
90
139
  }
91
140
  external.pending = {
92
141
  number: pull?.number,
93
- expectedCommit: pull?.head ?? source.syncedCommit,
142
+ expectedCommit: pull?.head ??
143
+ defined(source.syncedCommit, "This connection hasn't synced yet"),
94
144
  files: encodeFiles(files),
95
145
  title: options.title ?? `Update ${work.name}`,
96
146
  idempotencyKey: randomUUID(),
97
147
  };
98
- await save(work, home);
148
+ await save(work, runtime);
99
149
  }
100
150
  const pending = external.pending;
101
151
  let pull;
102
152
  try {
103
- pull = await request(work.connection, pending.number
104
- ? `${path}/pulls/${pending.number}/revisions`
105
- : `${path}/pulls`, gitPullSchema, home, pending.number ? "PUT" : "POST", {
153
+ const body = {
106
154
  expectedCommit: pending.expectedCommit,
107
155
  files: pending.files,
108
156
  title: pending.title,
109
157
  idempotencyKey: pending.idempotencyKey,
110
- });
158
+ };
159
+ pull = await parsed(gitPullSchema, pending.number
160
+ ? client.PUT("/v1/git-connections/{id}/pulls/{number}/revisions", {
161
+ params: { path: { id: source.id, number: pending.number } },
162
+ body: gitRevisionSchema.parse(body),
163
+ })
164
+ : client.POST("/v1/git-connections/{id}/pulls", {
165
+ params: { path: { id: source.id } },
166
+ body: gitProposalSchema.parse(body),
167
+ }));
111
168
  }
112
169
  catch (error) {
113
170
  if (error instanceof ApiError &&
114
- [400, 403, 404, 409, 413].includes(error.status)) {
171
+ [
172
+ HTTP_STATUS.badRequest,
173
+ HTTP_STATUS.forbidden,
174
+ HTTP_STATUS.notFound,
175
+ HTTP_STATUS.conflict,
176
+ HTTP_STATUS.payloadTooLarge,
177
+ ].includes(error.status)) {
115
178
  delete external.pending;
116
- await save(work, home);
179
+ await save(work, runtime);
117
180
  }
118
181
  throw error;
119
182
  }
@@ -123,8 +186,9 @@ export async function pushExternal(work, source, options, home) {
123
186
  files: pending.files,
124
187
  };
125
188
  delete external.pending;
126
- await save(work, home);
127
- if (options.publish)
128
- return request(work.connection, `${path}/pulls/${pull.number}/merge`, gitConnectionSchema, home, "PUT", { expectedCommit: external.pull.head });
189
+ await save(work, runtime);
190
+ if (options.publish) {
191
+ return merge(pull.number, external.pull.head);
192
+ }
129
193
  return pull;
130
194
  }
@@ -1,21 +1,35 @@
1
- import { CliError } from "../../errors.js";
1
+ import { assertPackagePaths, removeCommand } from "../../platform.js";
2
+ import { writePackage, readDirectory } from "../workspace/directory.js";
3
+ import { CliError, PackageError } from "../../errors.js";
2
4
  import { randomUUID, createHash } from "node:crypto";
3
5
  import { join, dirname, isAbsolute } from "node:path";
4
- import { mkdir, readFile, writeFile, rename, readdir, realpath, rm, lstat, } from "node:fs/promises";
6
+ import { readdir, realpath, rm, lstat } from "node:fs/promises";
5
7
  import { z } from "zod";
6
8
  import { changeUploadSchema } from "@barndog-ai/api-contract";
7
- import { packageFingerprint, writePackage, } from "@barndog-ai/api-contract/package";
8
- import { readDirectory } from "@barndog-ai/api-contract/collaboration";
9
+ import { packageFingerprint, } from "@barndog-ai/api-contract/package";
10
+ import { packageKindList } from "../../config/selection.js";
11
+ import { GIT_OBJECT_ID } from "../../shared/patterns.js";
12
+ import { isInside, readIfExists, writeAtomic } from "../../shared/files.js";
13
+ import { withPidLock } from "../../shared/lock.js";
14
+ import { barndogPaths } from "../../config/paths.js";
9
15
  const filesSchema = z.array(z.object({ path: z.string(), content: z.string(), executable: z.boolean() }));
16
+ /**
17
+ * What a push sends besides the files. `assetId` is the Skill or Hook being
18
+ * revised, absent until the package is first published; the kind's route names
19
+ * it `skillId` or `hookId` (`collaboration/api.ts`).
20
+ */
21
+ const uploadSchema = changeUploadSchema
22
+ .omit({ skillId: true })
23
+ .extend({ assetId: z.uuid().optional() });
10
24
  const workspaceSchema = z.object({
11
- kind: z.enum(["skill", "hook"]).default("skill"),
25
+ kind: z.enum(packageKindList),
12
26
  root: z.string().refine(isAbsolute),
13
27
  connection: z.object({
14
28
  server: z.string(),
15
29
  organizationId: z.uuid(),
16
30
  developerId: z.uuid(),
17
31
  }),
18
- skillId: z.uuid().optional(),
32
+ assetId: z.uuid().optional(),
19
33
  name: z.string(),
20
34
  origin: z.object({
21
35
  type: z.enum(["org", "team", "repo", "dev"]),
@@ -34,7 +48,7 @@ const workspaceSchema = z.object({
34
48
  conflicts: z.array(z.string()),
35
49
  pending: z
36
50
  .object({
37
- metadata: changeUploadSchema,
51
+ metadata: uploadSchema,
38
52
  files: filesSchema,
39
53
  changeId: z.uuid().optional(),
40
54
  })
@@ -64,7 +78,7 @@ const workspaceSchema = z.object({
64
78
  pendingSnapshot: z.string().optional(),
65
79
  });
66
80
  const gitWorkspaceSchema = z.object({
67
- kind: z.enum(["skill", "hook"]),
81
+ kind: z.enum(packageKindList),
68
82
  root: z.string().refine(isAbsolute),
69
83
  git: z.object({
70
84
  url: z.string(),
@@ -77,14 +91,14 @@ const gitWorkspaceSchema = z.object({
77
91
  slug: z.string(),
78
92
  path: z.string(),
79
93
  }),
80
- baseCommit: z.string().regex(/^[0-9a-f]{40}$/),
94
+ baseCommit: z.string().regex(GIT_OBJECT_ID),
81
95
  base: filesSchema,
82
96
  conflicts: z.array(z.string()),
83
97
  /** The branch under review; it stays until its content reaches the default branch. */
84
98
  review: z
85
99
  .object({
86
100
  branch: z.string(),
87
- head: z.string().regex(/^[0-9a-f]{40}$/),
101
+ head: z.string().regex(GIT_OBJECT_ID),
88
102
  files: filesSchema,
89
103
  url: z.string().optional(),
90
104
  })
@@ -92,6 +106,7 @@ const gitWorkspaceSchema = z.object({
92
106
  pendingWrite: filesSchema.optional(),
93
107
  pendingSnapshot: z.string().optional(),
94
108
  });
109
+ /** Package entries as base64 `Files`, to store or send as JSON. */
95
110
  export const encodeFiles = (entries) => entries.map((e) => ({
96
111
  path: e.path,
97
112
  content: e.data.toString("base64"),
@@ -102,155 +117,200 @@ export const decodeFiles = (files) => files.map((e) => ({
102
117
  data: Buffer.from(e.content, "base64"),
103
118
  executable: e.executable,
104
119
  }));
105
- export function directory(home) {
106
- return join(home, ".barndog", "workspaces");
120
+ /**
121
+ * The files in a working copy. On Windows their executable flags come from
122
+ * its base, as they were when BarnDog wrote them (see `readDirectory()`).
123
+ */
124
+ export const readWorkingCopy = (work, runtime) => readDirectory(work.root, runtime, decodeFiles(work.base));
125
+ /** A working copy's record, keyed by a hash of its folder's path. */
126
+ /**
127
+ * The files a working copy held before an interrupted update. Without them
128
+ * BarnDog can't tell its own writes from the person's edits, so it touches
129
+ * nothing and says how to start over.
130
+ */
131
+ async function recoverySnapshot(work, runtime) {
132
+ const damaged = (reason, cause) => new CliError(`An update of ${work.root} was interrupted, and ${reason}, so BarnDog left the folder as it is.`, "Save any edits in the folder elsewhere, then remove its working-copy record and pull it again", {
133
+ cause,
134
+ command: removeCommand(recordPath(work.root, runtime), runtime.platform),
135
+ });
136
+ const path = work.pendingSnapshot;
137
+ const snapshots = barndogPaths(runtime.home).workingCopySnapshots;
138
+ if (!path || path === snapshots || !isInside(snapshots, path)) {
139
+ throw damaged("its record doesn't point at a recovery snapshot");
140
+ }
141
+ const text = await readIfExists(path);
142
+ if (text === null) {
143
+ throw damaged(`its recovery snapshot ${path} is gone`);
144
+ }
145
+ try {
146
+ return z.object({ files: filesSchema }).parse(JSON.parse(text));
147
+ }
148
+ catch (error) {
149
+ throw damaged(`its recovery snapshot ${path} is damaged`, error);
150
+ }
107
151
  }
108
- function recordPath(root, home) {
109
- return join(directory(home), createHash("sha256").update(root).digest("hex") + ".json");
152
+ function recordPath(root, runtime) {
153
+ const { home } = runtime;
154
+ return join(barndogPaths(home).workingCopies, createHash("sha256").update(root).digest("hex") + ".json");
110
155
  }
111
- export async function save(work, home) {
112
- await mkdir(directory(home), { recursive: true, mode: 0o700 });
113
- const file = recordPath(work.root, home), temp = `${file}.${randomUUID()}.tmp`;
114
- await writeFile(temp, JSON.stringify(work), { mode: 0o600 });
115
- await rename(temp, file);
156
+ /** Writes a working-copy record atomically, replacing the previous one. */
157
+ export async function save(work, runtime) {
158
+ await writeAtomic(recordPath(work.root, runtime), JSON.stringify(work));
116
159
  }
117
- // Serialize local mutations across processes. A dead process's lock is reclaimable.
118
- export async function locked(home, run) {
119
- const root = directory(home), lock = join(root, "lock");
120
- await mkdir(root, { recursive: true, mode: 0o700 });
160
+ /** Serializes working-copy changes across processes. */
161
+ export function locked(runtime, run) {
162
+ const { home } = runtime;
163
+ return withPidLock(barndogPaths(home).workingCopiesLock, {
164
+ starting: "Another BarnDog workspace operation is starting; retry shortly",
165
+ running: "Another BarnDog workspace operation is running",
166
+ }, run);
167
+ }
168
+ /** Root working-copy commands only make sense inside a pulled or created folder. */
169
+ export class NoWorkingCopyError extends CliError {
170
+ }
171
+ /**
172
+ * The Cloud working copy containing `cwd`, searching up from it. Finishes an
173
+ * interrupted write first; throws `NoWorkingCopyError` when no folder above
174
+ * `cwd` is registered, and a fix when the record belongs to a Git workspace.
175
+ */
176
+ export const find = (runtime) => {
177
+ return findRecord(runtime, (value) => {
178
+ if (value && typeof value === "object" && "git" in value) {
179
+ throw new CliError("This working copy belongs to a Git repo workspace, but this machine no longer uses one.", "barndog init");
180
+ }
181
+ return workspaceSchema.parse(value);
182
+ });
183
+ };
184
+ /** The Git working copy containing `cwd`; `find()` for Git workspaces. */
185
+ export const findGit = (runtime) => {
186
+ return findRecord(runtime, (value) => {
187
+ if (!value || typeof value !== "object" || !("git" in value)) {
188
+ throw new CliError("This working copy belongs to a BarnDog Cloud Workspace, but this machine now uses a Git repo.", "barndog init --server <url>");
189
+ }
190
+ return gitWorkspaceSchema.parse(value);
191
+ });
192
+ };
193
+ /**
194
+ * A working-copy record read from disk. A record that isn't JSON or doesn't
195
+ * match its schema was damaged, so it says how to start the folder over; the
196
+ * errors `parse` raises itself pass through.
197
+ */
198
+ function parseRecord(text, root, runtime, parse) {
121
199
  try {
122
- await mkdir(lock);
200
+ return parse(JSON.parse(text));
123
201
  }
124
202
  catch (error) {
125
- if (error.code !== "EEXIST")
203
+ if (error instanceof CliError) {
126
204
  throw error;
127
- const pid = Number(await readFile(join(lock, "pid"), "utf8").catch(() => "0"));
128
- if (!pid)
129
- throw new Error("Another BarnDog workspace operation is starting; retry shortly", { cause: error });
130
- try {
131
- process.kill(pid, 0);
132
205
  }
133
- catch (failure) {
134
- if (failure.code !== "ESRCH")
135
- throw failure;
136
- await rm(lock, { recursive: true });
137
- return locked(home, run);
138
- }
139
- throw new Error("Another BarnDog workspace operation is running", {
206
+ throw new CliError(`The working-copy record for ${root} is damaged.`, "Save any edits in the folder elsewhere, then remove its working-copy record and pull it again", {
140
207
  cause: error,
208
+ command: removeCommand(recordPath(root, runtime), runtime.platform),
141
209
  });
142
210
  }
143
- await writeFile(join(lock, "pid"), String(process.pid));
144
- try {
145
- return await run();
146
- }
147
- finally {
148
- await rm(lock, { recursive: true, force: true });
149
- }
150
- }
151
- /** Root working-copy commands only make sense inside a pulled or created folder. */
152
- export class NoWorkingCopyError extends CliError {
153
211
  }
154
- export const find = (cwd, home) => findRecord(cwd, home, (value) => {
155
- if (value && typeof value === "object" && "git" in value)
156
- throw new CliError("This working copy belongs to a Git repo workspace, but this machine no longer uses one.", "barndog init");
157
- return workspaceSchema.parse(value);
158
- });
159
- export const findGit = (cwd, home) => findRecord(cwd, home, (value) => {
160
- if (!value || typeof value !== "object" || !("git" in value))
161
- throw new CliError("This working copy belongs to a BarnDog Cloud Workspace, but this machine now uses a Git repo.", "barndog init --server <url>");
162
- return gitWorkspaceSchema.parse(value);
163
- });
164
- async function findRecord(cwd, home, parse) {
165
- let path = await realpath(cwd);
212
+ async function findRecord(runtime, parse) {
213
+ let path = await realpath(runtime.cwd);
166
214
  while (true) {
167
- try {
168
- const work = parse(JSON.parse(await readFile(recordPath(path, home), "utf8")));
169
- if (work.root !== path)
170
- throw new Error("Invalid workspace identity");
215
+ const text = await readIfExists(recordPath(path, runtime));
216
+ if (text !== null) {
217
+ const work = parseRecord(text, path, runtime, parse);
218
+ if (work.root !== path) {
219
+ throw new Error(`The working-copy record for ${path} names a different folder`);
220
+ }
171
221
  if (work.pendingWrite) {
172
- if (!work.pendingSnapshot?.startsWith(join(directory(home), "snapshots") + "/"))
173
- throw new Error("Interrupted workspace update has no recovery snapshot");
174
- const snapshot = JSON.parse(await readFile(work.pendingSnapshot, "utf8"));
222
+ const snapshot = await recoverySnapshot(work, runtime);
175
223
  const allowed = [
176
224
  ...decodeFiles(snapshot.files),
177
225
  ...decodeFiles(work.pendingWrite),
178
226
  ];
179
- for (const file of await readDirectory(work.root))
227
+ for (const file of await readDirectory(work.root, runtime, allowed)) {
180
228
  if (!allowed.some((old) => old.path === file.path &&
181
229
  old.data.equals(file.data) &&
182
- old.executable === file.executable))
183
- throw new Error(`Interrupted update contains additional local edits: ${file.path}. Preserve them before retrying; recovery snapshot: ${work.pendingSnapshot}`);
184
- await replaceFiles(work.root, decodeFiles(work.pendingWrite));
230
+ old.executable === file.executable)) {
231
+ throw new CliError(`An interrupted update left edits it didn't make in ${file.path}. Save them elsewhere, then retry. The recovery snapshot is ${work.pendingSnapshot}.`);
232
+ }
233
+ }
234
+ await replaceFiles(work.root, decodeFiles(work.pendingWrite), runtime);
185
235
  delete work.pendingWrite;
186
236
  delete work.pendingSnapshot;
187
- await save(work, home);
237
+ await save(work, runtime);
188
238
  }
189
239
  return work;
190
240
  }
191
- catch (error) {
192
- if (error.code !== "ENOENT")
193
- throw error;
194
- }
195
- if (dirname(path) === path)
241
+ if (dirname(path) === path) {
196
242
  break;
243
+ }
197
244
  path = dirname(path);
198
245
  }
199
246
  throw new NoWorkingCopyError("This folder isn't an editable Skill or Hook. Working-copy commands run inside a folder made by barndog skills pull, barndog hooks pull or barndog skills create.", "barndog skills pull <name>");
200
247
  }
201
- async function replaceFiles(root, entries) {
248
+ async function replaceFiles(root, entries, runtime) {
249
+ assertPackagePaths(entries, runtime.platform);
202
250
  // Validate paths and directory topology before touching local files.
203
251
  const paths = new Set(entries.map((e) => e.path));
204
252
  for (const path of paths) {
205
253
  if (path.startsWith("/") ||
254
+ path.includes(":") ||
206
255
  path
207
256
  .split("/")
208
257
  .some((p) => !p || p === "." || p === ".." || p.toLowerCase() === ".git") ||
209
- path.includes("\\"))
210
- throw new Error("UNSAFE_PACKAGE_ENTRY");
258
+ path.includes("\\")) {
259
+ throw new PackageError("UNSAFE_PACKAGE_ENTRY", path);
260
+ }
211
261
  for (const parent of path
212
262
  .split("/")
213
263
  .slice(0, -1)
214
- .map((_, i, a) => a.slice(0, i + 1).join("/")))
215
- if (paths.has(parent))
216
- throw new Error("Resolve the file/directory collision before updating this working copy");
264
+ .map((_, i, a) => a.slice(0, i + 1).join("/"))) {
265
+ if (paths.has(parent)) {
266
+ throw new CliError(`A file and a folder share the path ${parent}. Keep one, then retry.`);
267
+ }
268
+ }
217
269
  }
218
- const old = await readDirectory(root);
219
- for (const entry of old)
270
+ const old = await readDirectory(root, runtime);
271
+ for (const entry of old) {
220
272
  await rm(join(root, entry.path));
273
+ }
221
274
  // Remove empty directories bottom-up while preserving local .git directories.
222
275
  async function empty(path) {
223
- for (const name of await readdir(path))
276
+ for (const name of await readdir(path)) {
224
277
  if (name.toLowerCase() !== ".git") {
225
278
  const child = join(path, name);
226
279
  if ((await lstat(child)).isDirectory()) {
227
280
  await empty(child);
228
- if (!(await readdir(child)).length)
281
+ if (!(await readdir(child)).length) {
229
282
  await rm(child, { recursive: true });
283
+ }
230
284
  }
231
285
  }
286
+ }
232
287
  }
233
288
  await empty(root);
234
- await writePackage(root, entries);
289
+ await writePackage(root, entries, runtime);
235
290
  }
236
- export async function applyFiles(work, entries, home, previous = work) {
237
- const local = await readDirectory(work.root);
291
+ /**
292
+ * Replaces working files and saves the record. Saves the prior files and record
293
+ * in a recovery snapshot first; the next working-copy lookup finishes an
294
+ * interrupted write unless it detects additional local edits.
295
+ */
296
+ export async function applyFiles(work, entries, runtime, previous = work) {
297
+ const { home } = runtime;
298
+ const local = await readDirectory(work.root, runtime, entries);
238
299
  if (packageFingerprint(local) === packageFingerprint(entries)) {
239
- await save(work, home);
300
+ await save(work, runtime);
240
301
  return;
241
302
  }
242
- const snapshot = join(directory(home), "snapshots", `${Date.now()}-${randomUUID()}.json`);
243
- await mkdir(dirname(snapshot), { recursive: true, mode: 0o700 });
244
- await writeFile(snapshot, JSON.stringify({
303
+ const snapshot = join(barndogPaths(home).workingCopySnapshots, `${Date.now()}-${randomUUID()}.json`);
304
+ await writeAtomic(snapshot, JSON.stringify({
245
305
  root: work.root,
246
306
  files: encodeFiles(local),
247
307
  workspace: previous,
248
- }), { mode: 0o600 });
308
+ }));
249
309
  work.pendingWrite = encodeFiles(entries);
250
310
  work.pendingSnapshot = snapshot;
251
- await save(work, home);
252
- await replaceFiles(work.root, entries);
311
+ await save(work, runtime);
312
+ await replaceFiles(work.root, entries, runtime);
253
313
  delete work.pendingWrite;
254
314
  delete work.pendingSnapshot;
255
- await save(work, home);
315
+ await save(work, runtime);
256
316
  }