barndog 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +24 -11
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,34 +1,54 @@
1
+ import { HTTP_STATUS } from "../../shared/constants.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { z } from "zod";
3
- import { ApiError, gitConnectionSchema, gitPullSchema, gitPullDetailsSchema, } from "@barndog-ai/api-contract";
4
+ import { ApiError, gitConnectionSchema, gitPullSchema, gitPullDetailsSchema, gitProposalSchema, gitRevisionSchema, } from "@barndog-ai/api-contract";
4
5
  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)
6
+ import { mergeEntries } from "@barndog-ai/api-contract/collaboration";
7
+ import { metadata as packageMetadataFor } from "../asset-kinds/index.js";
8
+ import { downloadPull, downloadVersion } from "./remote.js";
9
+ import { getAsset } from "../server/catalog.js";
10
+ import { parsed } from "../server/client.js";
11
+ import { encodeFiles, decodeFiles, save, applyFiles, readWorkingCopy, } from "./workspace-store.js";
12
+ import { defined } from "../../shared/lookup.js";
13
+ import { CliError } from "../../errors.js";
14
+ import { apiClient } from "../auth/transport.js";
15
+ const publishedId = (work) => defined(work.assetId, "This working copy isn't published yet");
16
+ /**
17
+ * The GitHub connection that is authoritative for this working copy's asset, if
18
+ * any. Throws when the authority changed since the copy was made, when the
19
+ * connection needs attention, or when an internal upload is still pending.
20
+ */
21
+ export async function externalSource(work, runtime) {
22
+ if (!work.assetId) {
12
23
  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 &&
24
+ }
25
+ const connections = await parsed(z.array(gitConnectionSchema), apiClient(work.connection.server, runtime).GET("/v1/git-connections"));
26
+ const source = connections.find((c) => c.assetId === work.assetId &&
15
27
  c.kind === work.kind &&
16
28
  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");
29
+ if (work.external && (!source || source.id !== work.external.id)) {
30
+ throw new CliError("This asset's GitHub connection changed on the server. Save your edits elsewhere, then pull a fresh working copy.", "barndog pull");
31
+ }
32
+ if (source && source.status !== "active") {
33
+ throw new CliError(`GitHub sync needs attention: ${source.lastError ?? source.status}.`, "barndog github list");
34
+ }
35
+ if (source && work.pending) {
36
+ throw new CliError("A push to BarnDog is still waiting for confirmation. Retry it before using GitHub.", "barndog push");
37
+ }
23
38
  return source;
24
39
  }
25
- export async function pullExternal(work, source, entries, previous, home) {
40
+ /**
41
+ * `pull` for a GitHub-authoritative asset: merges edits made to its pull
42
+ * request, then newly published main content, into the folder.
43
+ */
44
+ export async function pullExternal(work, { source, entries, previous, }, runtime) {
26
45
  work.external ??= { id: source.id };
27
- const conflicts = new Set(), external = work.external;
46
+ const conflicts = new Set();
47
+ const external = work.external;
28
48
  if (external.pull) {
29
- const { pull } = await request(work.connection, `/v1/git-connections/${source.id}/pulls/${external.pull.number}`, gitPullDetailsSchema, home);
49
+ 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
50
  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);
51
+ const remote = await downloadPull({ connectionId: source.id, number: pull.number, head: pull.head }, work.connection, { runtime, kind: work.kind });
32
52
  const merged = await mergeEntries(decodeFiles(external.pull.files), entries, remote);
33
53
  entries = merged.entries;
34
54
  merged.conflicts.forEach((p) => conflicts.add(p));
@@ -38,14 +58,20 @@ export async function pullExternal(work, source, entries, previous, home) {
38
58
  files: encodeFiles(remote),
39
59
  };
40
60
  }
41
- if (pull.merged)
61
+ if (pull.merged) {
42
62
  delete external.pull;
63
+ }
64
+ }
65
+ const asset = await getAsset(work.kind, publishedId(work), work.connection, runtime);
66
+ if (!("commit" in asset.version)) {
67
+ throw new Error("The server returned a GitHub-connected version without its Git commit");
43
68
  }
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
69
  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);
70
+ const latest = await downloadVersion({
71
+ id: publishedId(work),
72
+ number: asset.version.number,
73
+ commit: asset.version.commit,
74
+ }, work.connection, { runtime, kind: work.kind });
49
75
  const merged = await mergeEntries(decodeFiles(work.base), entries, latest);
50
76
  entries = merged.entries;
51
77
  merged.conflicts.forEach((p) => conflicts.add(p));
@@ -54,7 +80,7 @@ export async function pullExternal(work, source, entries, previous, home) {
54
80
  work.baseNumber = asset.version.number;
55
81
  }
56
82
  work.conflicts = [...conflicts];
57
- await applyFiles(work, entries, home, previous);
83
+ await applyFiles(work, entries, runtime, previous);
58
84
  return {
59
85
  root: work.root,
60
86
  conflicts: work.conflicts,
@@ -62,58 +88,94 @@ export async function pullExternal(work, source, entries, previous, home) {
62
88
  external: { connectionId: source.id, pull: external.pull?.number },
63
89
  };
64
90
  }
65
- export async function pushExternal(work, source, options, home) {
91
+ /**
92
+ * `push` for a GitHub-authoritative asset: opens or revises its pull request
93
+ * with the complete package and, with `publish`, merges it. The request and
94
+ * retry key are saved first so an ambiguous failure retries exactly; a
95
+ * definitive refusal (400, 403, 404, 409, 413) drops it so local edits can be
96
+ * reconciled.
97
+ */
98
+ export async function pushExternal(work, source, options, runtime) {
66
99
  work.external ??= { id: source.id };
67
- const external = work.external, path = `/v1/git-connections/${source.id}`;
100
+ const external = work.external;
101
+ const client = apiClient(work.connection.server, runtime);
102
+ const merge = (number, expectedCommit) => parsed(gitConnectionSchema, client.PUT("/v1/git-connections/{id}/pulls/{number}/merge", {
103
+ params: { path: { id: source.id, number } },
104
+ body: { expectedCommit },
105
+ }));
68
106
  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");
107
+ const asset = await getAsset(work.kind, publishedId(work), work.connection, runtime);
108
+ if (asset.version.id !== work.baseVersionId) {
109
+ throw new CliError("The published content on GitHub changed since your last pull.", "barndog pull");
110
+ }
72
111
  let pull = external.pull
73
- ? (await request(work.connection, `${path}/pulls/${external.pull.number}`, gitPullDetailsSchema, home)).pull
112
+ ? (await parsed(gitPullDetailsSchema, client.GET("/v1/git-connections/{id}/pulls/{number}", {
113
+ params: {
114
+ path: { id: source.id, number: external.pull.number },
115
+ },
116
+ }))).pull
74
117
  : 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)
118
+ if (pull?.state === "closed" && !options.new) {
119
+ throw new CliError("The pull request is closed. Pull, then push a new one.", "barndog pull && barndog push --new");
120
+ }
121
+ if (pull && pull.head !== external.pull?.head) {
122
+ throw new CliError("The pull request changed on GitHub since your last pull.", "barndog pull");
123
+ }
124
+ if (options.new) {
80
125
  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;
126
+ }
127
+ const files = await readWorkingCopy(work, runtime);
128
+ if (packageMetadataFor(files, work.kind).name !== work.name) {
129
+ throw new CliError(`This working copy's name must stay ${work.name}. Change it back, then push again.`);
130
+ }
131
+ const previous = (pull && external.pull?.files) || work.base;
85
132
  if (packageFingerprint(files) === packageFingerprint(decodeFiles(previous)) &&
86
133
  !options.title) {
87
- if (options.publish && pull)
88
- return request(work.connection, `${path}/pulls/${pull.number}/merge`, gitConnectionSchema, home, "PUT", { expectedCommit: pull.head });
134
+ if (options.publish && pull) {
135
+ return merge(pull.number, pull.head);
136
+ }
89
137
  return { unchanged: true, pull: pull?.number };
90
138
  }
91
139
  external.pending = {
92
140
  number: pull?.number,
93
- expectedCommit: pull?.head ?? source.syncedCommit,
141
+ expectedCommit: pull?.head ??
142
+ defined(source.syncedCommit, "This connection hasn't synced yet"),
94
143
  files: encodeFiles(files),
95
144
  title: options.title ?? `Update ${work.name}`,
96
145
  idempotencyKey: randomUUID(),
97
146
  };
98
- await save(work, home);
147
+ await save(work, runtime);
99
148
  }
100
149
  const pending = external.pending;
101
150
  let pull;
102
151
  try {
103
- pull = await request(work.connection, pending.number
104
- ? `${path}/pulls/${pending.number}/revisions`
105
- : `${path}/pulls`, gitPullSchema, home, pending.number ? "PUT" : "POST", {
152
+ const body = {
106
153
  expectedCommit: pending.expectedCommit,
107
154
  files: pending.files,
108
155
  title: pending.title,
109
156
  idempotencyKey: pending.idempotencyKey,
110
- });
157
+ };
158
+ pull = await parsed(gitPullSchema, pending.number
159
+ ? client.PUT("/v1/git-connections/{id}/pulls/{number}/revisions", {
160
+ params: { path: { id: source.id, number: pending.number } },
161
+ body: gitRevisionSchema.parse(body),
162
+ })
163
+ : client.POST("/v1/git-connections/{id}/pulls", {
164
+ params: { path: { id: source.id } },
165
+ body: gitProposalSchema.parse(body),
166
+ }));
111
167
  }
112
168
  catch (error) {
113
169
  if (error instanceof ApiError &&
114
- [400, 403, 404, 409, 413].includes(error.status)) {
170
+ [
171
+ HTTP_STATUS.badRequest,
172
+ HTTP_STATUS.forbidden,
173
+ HTTP_STATUS.notFound,
174
+ HTTP_STATUS.conflict,
175
+ HTTP_STATUS.payloadTooLarge,
176
+ ].includes(error.status)) {
115
177
  delete external.pending;
116
- await save(work, home);
178
+ await save(work, runtime);
117
179
  }
118
180
  throw error;
119
181
  }
@@ -123,8 +185,9 @@ export async function pushExternal(work, source, options, home) {
123
185
  files: pending.files,
124
186
  };
125
187
  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 });
188
+ await save(work, runtime);
189
+ if (options.publish) {
190
+ return merge(pull.number, external.pull.head);
191
+ }
129
192
  return pull;
130
193
  }
@@ -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 { 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,180 @@ 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");
107
- }
108
- function recordPath(root, home) {
109
- return join(directory(home), createHash("sha256").update(root).digest("hex") + ".json");
110
- }
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);
116
- }
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 });
121
- try {
122
- await mkdir(lock);
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
+ if (!path?.startsWith(barndogPaths(runtime.home).workingCopySnapshots + "/")) {
138
+ throw damaged("its record doesn't point at a recovery snapshot");
123
139
  }
124
- catch (error) {
125
- if (error.code !== "EEXIST")
126
- 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
- }
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", {
140
- cause: error,
141
- });
140
+ const text = await readIfExists(path);
141
+ if (text === null) {
142
+ throw damaged(`its recovery snapshot ${path} is gone`);
142
143
  }
143
- await writeFile(join(lock, "pid"), String(process.pid));
144
144
  try {
145
- return await run();
145
+ return z.object({ files: filesSchema }).parse(JSON.parse(text));
146
146
  }
147
- finally {
148
- await rm(lock, { recursive: true, force: true });
147
+ catch (error) {
148
+ throw damaged(`its recovery snapshot ${path} is damaged`, error);
149
149
  }
150
150
  }
151
+ function recordPath(root, runtime) {
152
+ const { home } = runtime;
153
+ return join(barndogPaths(home).workingCopies, createHash("sha256").update(root).digest("hex") + ".json");
154
+ }
155
+ /** Writes a working-copy record atomically, replacing the previous one. */
156
+ export async function save(work, runtime) {
157
+ await writeAtomic(recordPath(work.root, runtime), JSON.stringify(work));
158
+ }
159
+ /** Serializes working-copy changes across processes. */
160
+ export function locked(runtime, run) {
161
+ const { home } = runtime;
162
+ return withPidLock(barndogPaths(home).workingCopiesLock, {
163
+ starting: "Another BarnDog workspace operation is starting; retry shortly",
164
+ running: "Another BarnDog workspace operation is running",
165
+ }, run);
166
+ }
151
167
  /** Root working-copy commands only make sense inside a pulled or created folder. */
152
168
  export class NoWorkingCopyError extends CliError {
153
169
  }
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);
170
+ /**
171
+ * The Cloud working copy containing `cwd`, searching up from it. Finishes an
172
+ * interrupted write first; throws `NoWorkingCopyError` when no folder above
173
+ * `cwd` is registered, and a fix when the record belongs to a Git workspace.
174
+ */
175
+ export const find = (runtime) => {
176
+ return findRecord(runtime, (value) => {
177
+ if (value && typeof value === "object" && "git" in value) {
178
+ throw new CliError("This working copy belongs to a Git repo workspace, but this machine no longer uses one.", "barndog init");
179
+ }
180
+ return workspaceSchema.parse(value);
181
+ });
182
+ };
183
+ /** The Git working copy containing `cwd`; `find()` for Git workspaces. */
184
+ export const findGit = (runtime) => {
185
+ return findRecord(runtime, (value) => {
186
+ if (!value || typeof value !== "object" || !("git" in value)) {
187
+ throw new CliError("This working copy belongs to a BarnDog Cloud Workspace, but this machine now uses a Git repo.", "barndog init --server <url>");
188
+ }
189
+ return gitWorkspaceSchema.parse(value);
190
+ });
191
+ };
192
+ async function findRecord(runtime, parse) {
193
+ let path = await realpath(runtime.cwd);
166
194
  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");
195
+ const text = await readIfExists(recordPath(path, runtime));
196
+ if (text !== null) {
197
+ const work = parse(JSON.parse(text));
198
+ if (work.root !== path) {
199
+ throw new Error(`The working-copy record for ${path} names a different folder`);
200
+ }
171
201
  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"));
202
+ const snapshot = await recoverySnapshot(work, runtime);
175
203
  const allowed = [
176
204
  ...decodeFiles(snapshot.files),
177
205
  ...decodeFiles(work.pendingWrite),
178
206
  ];
179
- for (const file of await readDirectory(work.root))
207
+ for (const file of await readDirectory(work.root, runtime, allowed)) {
180
208
  if (!allowed.some((old) => old.path === file.path &&
181
209
  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));
210
+ old.executable === file.executable)) {
211
+ 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}.`);
212
+ }
213
+ }
214
+ await replaceFiles(work.root, decodeFiles(work.pendingWrite), runtime);
185
215
  delete work.pendingWrite;
186
216
  delete work.pendingSnapshot;
187
- await save(work, home);
217
+ await save(work, runtime);
188
218
  }
189
219
  return work;
190
220
  }
191
- catch (error) {
192
- if (error.code !== "ENOENT")
193
- throw error;
194
- }
195
- if (dirname(path) === path)
221
+ if (dirname(path) === path) {
196
222
  break;
223
+ }
197
224
  path = dirname(path);
198
225
  }
199
226
  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
227
  }
201
- async function replaceFiles(root, entries) {
228
+ async function replaceFiles(root, entries, runtime) {
229
+ assertPackagePaths(entries, runtime.platform);
202
230
  // Validate paths and directory topology before touching local files.
203
231
  const paths = new Set(entries.map((e) => e.path));
204
232
  for (const path of paths) {
205
233
  if (path.startsWith("/") ||
234
+ path.includes(":") ||
206
235
  path
207
236
  .split("/")
208
237
  .some((p) => !p || p === "." || p === ".." || p.toLowerCase() === ".git") ||
209
- path.includes("\\"))
210
- throw new Error("UNSAFE_PACKAGE_ENTRY");
238
+ path.includes("\\")) {
239
+ throw new PackageError("UNSAFE_PACKAGE_ENTRY", path);
240
+ }
211
241
  for (const parent of path
212
242
  .split("/")
213
243
  .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");
244
+ .map((_, i, a) => a.slice(0, i + 1).join("/"))) {
245
+ if (paths.has(parent)) {
246
+ throw new CliError(`A file and a folder share the path ${parent}. Keep one, then retry.`);
247
+ }
248
+ }
217
249
  }
218
- const old = await readDirectory(root);
219
- for (const entry of old)
250
+ const old = await readDirectory(root, runtime);
251
+ for (const entry of old) {
220
252
  await rm(join(root, entry.path));
253
+ }
221
254
  // Remove empty directories bottom-up while preserving local .git directories.
222
255
  async function empty(path) {
223
- for (const name of await readdir(path))
256
+ for (const name of await readdir(path)) {
224
257
  if (name.toLowerCase() !== ".git") {
225
258
  const child = join(path, name);
226
259
  if ((await lstat(child)).isDirectory()) {
227
260
  await empty(child);
228
- if (!(await readdir(child)).length)
261
+ if (!(await readdir(child)).length) {
229
262
  await rm(child, { recursive: true });
263
+ }
230
264
  }
231
265
  }
266
+ }
232
267
  }
233
268
  await empty(root);
234
- await writePackage(root, entries);
269
+ await writePackage(root, entries, runtime);
235
270
  }
236
- export async function applyFiles(work, entries, home, previous = work) {
237
- const local = await readDirectory(work.root);
271
+ /**
272
+ * Replaces working files and saves the record. Saves the prior files and record
273
+ * in a recovery snapshot first; the next working-copy lookup finishes an
274
+ * interrupted write unless it detects additional local edits.
275
+ */
276
+ export async function applyFiles(work, entries, runtime, previous = work) {
277
+ const { home } = runtime;
278
+ const local = await readDirectory(work.root, runtime, entries);
238
279
  if (packageFingerprint(local) === packageFingerprint(entries)) {
239
- await save(work, home);
280
+ await save(work, runtime);
240
281
  return;
241
282
  }
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({
283
+ const snapshot = join(barndogPaths(home).workingCopySnapshots, `${Date.now()}-${randomUUID()}.json`);
284
+ await writeAtomic(snapshot, JSON.stringify({
245
285
  root: work.root,
246
286
  files: encodeFiles(local),
247
287
  workspace: previous,
248
- }), { mode: 0o600 });
288
+ }));
249
289
  work.pendingWrite = encodeFiles(entries);
250
290
  work.pendingSnapshot = snapshot;
251
- await save(work, home);
252
- await replaceFiles(work.root, entries);
291
+ await save(work, runtime);
292
+ await replaceFiles(work.root, entries, runtime);
253
293
  delete work.pendingWrite;
254
294
  delete work.pendingSnapshot;
255
- await save(work, home);
295
+ await save(work, runtime);
256
296
  }