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,16 +1,21 @@
1
+ import { directoryLinkType } from "../../platform.js";
2
+ import { POSIX_MODE } from "../../shared/constants.js";
1
3
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { createHash, randomUUID } from "node:crypto";
4
+ import { createHash } from "node:crypto";
3
5
  import { rmSync } from "node:fs";
4
- import { lstat, mkdir, readFile, readlink, rename, rm, symlink, unlink, writeFile, } from "node:fs/promises";
6
+ import { lstat, mkdir, readlink, rm, symlink, unlink } from "node:fs/promises";
5
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
6
8
  import { packageFingerprint } from "@barndog-ai/api-contract/package";
7
- import { settingsPath } from "../../config/settings.js";
8
- import { skillDirectory, harnesses } from "../../harnesses/registry.js";
9
- import { nativeFile } from "../native/configuration.js";
9
+ import { skillDirectory, harnesses, nativeFile, } from "../../harnesses/registry.js";
10
10
  import { z } from "zod";
11
- import { connectionContext } from "../skills/remote.js";
12
- import { skillName } from "../skills/validation.js";
13
- import { desiredEntries, installedRoot, mirrorTree, treeFingerprint, } from "./installed.js";
11
+ import { connectionContext } from "../auth/session.js";
12
+ import { NAME } from "../../shared/patterns.js";
13
+ import { desiredEntries, mirrorTree } from "../workspace/installed.js";
14
+ import { treeFingerprint } from "../workspace/tree.js";
15
+ import { fileText, ifExists, writeAtomic } from "../../shared/files.js";
16
+ import { withPidLock } from "../../shared/lock.js";
17
+ import { CliError } from "../../errors.js";
18
+ import { barndogPaths } from "../../config/paths.js";
14
19
  const writeSchema = z.union([
15
20
  z
16
21
  .object({
@@ -46,47 +51,26 @@ const journalSchema = z
46
51
  })
47
52
  .strict();
48
53
  const locks = new AsyncLocalStorage();
49
- export async function fileText(path) {
50
- try {
51
- const info = await lstat(path);
52
- if (!info.isFile() || info.isSymbolicLink())
53
- throw new Error(`Refusing non-regular configuration file: ${path}`);
54
- return await readFile(path, "utf8");
55
- }
56
- catch (error) {
57
- if (error.code === "ENOENT")
58
- return null;
59
- throw error;
60
- }
61
- }
54
+ /**
55
+ * Where the Skill link at `path` points, or null when nothing is there. Throws
56
+ * when something other than a symbolic link sits at `path`: BarnDog never takes
57
+ * over a folder it didn't create.
58
+ */
62
59
  export async function linkTarget(path) {
63
- try {
64
- const info = await lstat(path);
65
- if (!info.isSymbolicLink())
66
- throw new Error(`Existing unmanaged or externally changed Skill: ${path}`);
67
- return resolve(dirname(path), await readlink(path));
60
+ const info = await ifExists(lstat(path));
61
+ if (!info) {
62
+ return null;
68
63
  }
69
- catch (error) {
70
- if (error.code === "ENOENT")
71
- return null;
72
- throw error;
73
- }
74
- }
75
- export async function atomicFile(path, text) {
76
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
77
- const temp = `${path}.${randomUUID()}.tmp`;
78
- try {
79
- await writeFile(temp, text, { mode: 0o600, flag: "wx" });
80
- await rename(temp, path);
81
- }
82
- finally {
83
- await rm(temp, { force: true });
64
+ if (!info.isSymbolicLink()) {
65
+ throw new CliError(`${path} is a Skill folder BarnDog didn't install, so it won't replace it. Move or rename it, then sync again.`, "barndog sync");
84
66
  }
67
+ return resolve(dirname(path), await readlink(path));
85
68
  }
86
- function validateWrites(writes, home) {
69
+ function validateWrites(writes, runtime) {
70
+ const { home } = runtime;
87
71
  const files = new Set([
88
- settingsPath(home),
89
- join(home, ".barndog/state.json"),
72
+ barndogPaths(home).settings,
73
+ barndogPaths(home).state,
90
74
  ...harnesses.flatMap((h) => [
91
75
  nativeFile(h, "mcp", home),
92
76
  nativeFile(h, "hook", home),
@@ -94,69 +78,83 @@ function validateWrites(writes, home) {
94
78
  ]);
95
79
  const paths = new Set();
96
80
  for (const write of writes) {
97
- if (paths.has(write.path) || resolve(write.path) !== write.path)
98
- throw new Error("Invalid or duplicate sync destination");
81
+ if (paths.has(write.path) || resolve(write.path) !== write.path) {
82
+ throw new Error("A sync planned an invalid or duplicate destination");
83
+ }
99
84
  paths.add(write.path);
100
85
  if (write.kind === "tree") {
101
- if (![installedRoot(home, "skill"), installedRoot(home, "hook")].includes(dirname(write.path)) ||
102
- !skillName.test(basename(write.path)) ||
86
+ if (![
87
+ barndogPaths(home).installed("skill"),
88
+ barndogPaths(home).installed("hook"),
89
+ ].includes(dirname(write.path)) ||
90
+ !NAME.test(basename(write.path)) ||
103
91
  (write.source !== null && !isAbsolute(write.source)) ||
104
92
  (write.after !== null) !== (write.source !== null) ||
105
- (write.rename !== null && !skillName.test(write.rename)))
106
- throw new Error("Invalid sync journal destination; refusing recovery");
93
+ (write.rename !== null && !NAME.test(write.rename))) {
94
+ throw new Error("A sync planned an invalid destination");
95
+ }
107
96
  continue;
108
97
  }
109
98
  if (write.kind === "file"
110
99
  ? !files.has(write.path)
111
100
  : !harnesses.some((h) => dirname(write.path) === skillDirectory(h, home)) ||
112
- [write.before, write.after].some((v) => v !== null && !isAbsolute(v)))
113
- throw new Error("Invalid sync journal destination; refusing recovery");
101
+ [write.before, write.after].some((v) => v !== null && !isAbsolute(v))) {
102
+ throw new Error("A sync planned an invalid destination");
103
+ }
114
104
  }
115
105
  }
116
- async function current(write) {
117
- return write.kind === "file"
118
- ? fileText(write.path)
119
- : write.kind === "link"
120
- ? linkTarget(write.path)
121
- : treeFingerprint(write.path);
106
+ async function current(write, runtime) {
107
+ if (write.kind === "file") {
108
+ return fileText(write.path);
109
+ }
110
+ if (write.kind === "link") {
111
+ return linkTarget(write.path);
112
+ }
113
+ return treeFingerprint(write.path, runtime);
122
114
  }
123
- async function applyTree(write) {
115
+ async function applyTree(write, runtime) {
124
116
  if (write.source === null) {
125
117
  await rm(write.path, { recursive: true, force: true });
126
118
  return;
127
119
  }
128
120
  // A folder kept in place has no other copy to restore; the next sync reinstalls it.
129
- if (write.source === write.path)
121
+ if (write.source === write.path) {
130
122
  return;
131
- const entries = await desiredEntries(write.source, write.rename);
132
- if (packageFingerprint(entries) !== write.after)
133
- throw new Error(`Cached package changed before installation: ${write.source}`);
134
- await mirrorTree(write.path, entries);
123
+ }
124
+ const entries = await desiredEntries(write.source, write.rename, runtime);
125
+ if (packageFingerprint(entries) !== write.after) {
126
+ throw new CliError(`The downloaded copy in ${write.source} changed before it was installed.`, "barndog sync");
127
+ }
128
+ await mirrorTree(write.path, entries, runtime);
135
129
  }
136
- async function apply(writes, home, checkpoint, recovering = false) {
137
- validateWrites(writes, home);
130
+ async function apply(writes, runtime, checkpoint, recovering = false) {
131
+ validateWrites(writes, runtime);
138
132
  // Check the entire recovery plan before writing any remaining destination.
139
133
  for (const write of writes) {
140
134
  // An interrupted in-place copy leaves a BarnDog-owned folder half written.
141
- if (write.kind === "tree" && recovering)
135
+ if (write.kind === "tree" && recovering) {
142
136
  continue;
143
- const value = await current(write);
137
+ }
138
+ const value = await current(write, runtime);
144
139
  if (value !== write.before &&
145
140
  value !== write.after &&
146
141
  !(write.kind === "link" &&
147
142
  value === null &&
148
143
  write.before !== null &&
149
- write.after !== null))
150
- throw new Error(`Sync destination changed; preserve your edits before recovery: ${write.path}`);
144
+ write.after !== null)) {
145
+ throw new CliError(`${write.path} changed after a sync was interrupted. Save your edits elsewhere, then sync again.`, "barndog sync");
146
+ }
151
147
  }
152
148
  for (const [index, write] of writes.entries()) {
153
- const value = await current(write);
154
- if (value === write.after)
149
+ const value = await current(write, runtime);
150
+ if (value === write.after) {
155
151
  continue;
152
+ }
156
153
  if (write.kind === "tree") {
157
- if (value !== write.before && !recovering)
158
- throw new Error(`Sync destination changed: ${write.path}`);
159
- await applyTree(write);
154
+ if (value !== write.before && !recovering) {
155
+ throw new CliError(`${write.path} changed while syncing.`, "barndog sync");
156
+ }
157
+ await applyTree(write, runtime);
160
158
  await checkpoint?.(index);
161
159
  continue;
162
160
  }
@@ -164,121 +162,155 @@ async function apply(writes, home, checkpoint, recovering = false) {
164
162
  !(write.kind === "link" &&
165
163
  value === null &&
166
164
  write.before !== null &&
167
- write.after !== null))
168
- throw new Error(`Sync destination changed: ${write.path}`);
169
- await mkdir(dirname(write.path), { recursive: true, mode: 0o700 });
165
+ write.after !== null)) {
166
+ throw new CliError(`${write.path} changed while syncing.`, "barndog sync");
167
+ }
168
+ await mkdir(dirname(write.path), {
169
+ recursive: true,
170
+ mode: POSIX_MODE.privateDirectory,
171
+ });
170
172
  if (write.kind === "file") {
171
- if (write.after === null)
173
+ if (write.after === null) {
172
174
  await unlink(write.path);
173
- else
174
- await atomicFile(write.path, write.after);
175
+ }
176
+ else {
177
+ await writeAtomic(write.path, write.after);
178
+ }
175
179
  }
176
180
  else {
177
- if (value !== null)
181
+ if (value !== null) {
178
182
  await unlink(write.path);
179
- if (write.after !== null)
180
- await symlink(write.after, write.path, "dir");
183
+ }
184
+ if (write.after !== null) {
185
+ await symlink(write.after, write.path, directoryLinkType(runtime.platform));
186
+ }
181
187
  }
182
188
  await checkpoint?.(index);
183
189
  }
184
190
  }
185
- export async function recover(home) {
186
- const path = join(home, ".barndog/pending-sync.json"), text = await fileText(path);
187
- if (text === null)
188
- return false;
189
- const journal = journalSchema.parse(JSON.parse(text));
191
+ /**
192
+ * The journal an interrupted sync left. One that doesn't parse or names a
193
+ * destination BarnDog never writes was changed by hand or damaged, so it is
194
+ * kept and nothing is applied.
195
+ */
196
+ function readJournal(text, runtime) {
197
+ try {
198
+ const journal = journalSchema.parse(JSON.parse(text));
199
+ validateWrites(journal.writes, runtime);
200
+ return journal;
201
+ }
202
+ catch (error) {
203
+ throw new CliError(`${barndogPaths(runtime.home).pendingSync} is damaged, so BarnDog can't safely finish the interrupted sync.`, "Move that file aside (keep it), check the files it lists, then run barndog sync", { cause: error });
204
+ }
205
+ }
206
+ /**
207
+ * Rolls forward an interrupted sync from ~/.barndog/pending-sync.json.
208
+ * Rejects a cloud journal when its authenticated organization or developer
209
+ * has changed.
210
+ */
211
+ async function recover(runtime) {
212
+ const { home } = runtime;
213
+ const path = barndogPaths(home).pendingSync;
214
+ const text = await fileText(path);
215
+ if (text === null) {
216
+ return;
217
+ }
218
+ const journal = readJournal(text, runtime);
190
219
  if (journal.connection) {
191
- const actual = await connectionContext(journal.connection.server, home);
220
+ const actual = await connectionContext(journal.connection.server, runtime);
192
221
  if (actual.organizationId !== journal.connection.organizationId ||
193
- actual.developerId !== journal.connection.developerId)
194
- throw new Error("Sync recovery belongs to another identity");
222
+ actual.developerId !== journal.connection.developerId) {
223
+ throw new CliError("An interrupted sync belongs to another organization or developer. Sign in as them to finish it.", "barndog login");
224
+ }
195
225
  }
196
- await apply(journal.writes, home, undefined, true);
226
+ await apply(journal.writes, runtime, undefined, true);
197
227
  await unlink(path);
198
- return true;
199
228
  }
200
- export async function transact(home, writes, identity, checkpoint) {
229
+ /**
230
+ * Applies `writes` as one journaled operation: records them in
231
+ * `~/.barndog/pending-sync.json`, applies them in order and removes the
232
+ * journal, so `recover()` can finish the job after a crash. Backs up the
233
+ * previous `config.yaml` under `~/.barndog/migrations/` before changing it.
234
+ * `checkpoint` runs after each write is applied. Call it inside `locked()`.
235
+ */
236
+ export async function transact(runtime, writes, identity, checkpoint) {
237
+ const { home } = runtime;
201
238
  writes = writes.filter((w) => w.before !== w.after);
202
- if (!writes.length)
239
+ if (!writes.length) {
203
240
  return;
204
- validateWrites(writes, home);
205
- const config = writes.find((w) => w.path === settingsPath(home));
241
+ }
242
+ validateWrites(writes, runtime);
243
+ const config = writes.find((w) => w.path === barndogPaths(home).settings);
206
244
  if (config?.before) {
207
- const backup = join(home, ".barndog/migrations", `config-${createHash("sha256").update(config.before).digest("hex")}.yaml`);
245
+ const backup = join(barndogPaths(home).migrations, `config-${createHash("sha256").update(config.before).digest("hex")}.yaml`);
208
246
  const previous = await fileText(backup);
209
- if (previous === null)
210
- await atomicFile(backup, config.before);
211
- else if (previous !== config.before)
212
- throw new Error("Configuration migration backup was changed");
247
+ if (previous === null) {
248
+ await writeAtomic(backup, config.before);
249
+ }
250
+ else if (previous !== config.before) {
251
+ throw new CliError(`${backup} was changed after BarnDog saved it, so ${barndogPaths(home).settings} was left as it is.`, "Move that backup aside (keep it), then run the command again");
252
+ }
213
253
  }
214
- const path = join(home, ".barndog/pending-sync.json");
215
- await atomicFile(path, JSON.stringify(identity && "workspaceId" in identity
254
+ const path = barndogPaths(home).pendingSync;
255
+ await writeAtomic(path, JSON.stringify(identity && "workspaceId" in identity
216
256
  ? { version: 1, writes, workspaceId: identity.workspaceId }
217
257
  : { version: 1, writes, connection: identity }));
218
- await apply(writes, home, checkpoint);
258
+ await apply(writes, runtime, checkpoint);
219
259
  await unlink(path);
220
260
  }
221
261
  const INTERRUPTS = ["SIGINT", "SIGTERM", "SIGHUP"];
222
262
  const interruptions = new Set();
223
263
  function interrupted(signal) {
224
- for (const cleanup of interruptions)
264
+ for (const cleanup of interruptions) {
225
265
  cleanup();
266
+ }
226
267
  interruptions.clear();
227
- for (const name of INTERRUPTS)
268
+ for (const name of INTERRUPTS) {
228
269
  process.removeListener(name, interrupted);
270
+ }
229
271
  process.kill(process.pid, signal);
230
272
  }
231
273
  /** Runs `cleanup` if the process is told to stop; call the result once it's no longer needed. */
232
274
  export function cleanUpIfInterrupted(cleanup) {
233
- if (!interruptions.size)
234
- for (const name of INTERRUPTS)
275
+ if (!interruptions.size) {
276
+ for (const name of INTERRUPTS) {
235
277
  process.on(name, interrupted);
278
+ }
279
+ }
236
280
  interruptions.add(cleanup);
237
281
  return () => {
238
282
  interruptions.delete(cleanup);
239
- if (!interruptions.size)
240
- for (const name of INTERRUPTS)
283
+ if (!interruptions.size) {
284
+ for (const name of INTERRUPTS) {
241
285
  process.removeListener(name, interrupted);
286
+ }
287
+ }
242
288
  };
243
289
  }
244
- export async function locked(home, run) {
245
- home = resolve(home);
246
- if (locks.getStore()?.has(home))
290
+ /**
291
+ * Runs `run` holding the user-level sync lock, after rolling forward any
292
+ * interrupted operation. Nested calls for the same home reuse the lock.
293
+ */
294
+ export async function locked(runtime, run) {
295
+ runtime = { ...runtime, home: resolve(runtime.cwd, runtime.home) };
296
+ const { home } = runtime;
297
+ if (locks.getStore()?.has(home)) {
247
298
  return run();
248
- const path = join(home, ".barndog/sync.lock");
249
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
250
- try {
251
- await mkdir(path);
252
299
  }
253
- catch (error) {
254
- if (error.code !== "EEXIST")
255
- throw error;
256
- const pid = Number(await readFile(join(path, "pid"), "utf8").catch(() => "0"));
257
- if (!pid)
258
- throw new Error(`Another sync is starting. If an old process crashed, check and remove ${path}`, { cause: error });
300
+ const path = barndogPaths(home).syncLock;
301
+ return withPidLock(path, {
302
+ starting: `Another sync is starting. If an old process crashed, check and remove ${path}`,
303
+ running: "Another BarnDog environment operation is running",
304
+ }, async () => {
305
+ const release = cleanUpIfInterrupted(() => rmSync(path, { recursive: true, force: true }));
259
306
  try {
260
- process.kill(pid, 0);
307
+ return await locks.run(new Set([...(locks.getStore() ?? []), home]), async () => {
308
+ await recover(runtime);
309
+ return run();
310
+ });
261
311
  }
262
- catch (failure) {
263
- if (failure.code !== "ESRCH")
264
- throw failure;
265
- await rm(path, { recursive: true });
266
- return locked(home, run);
312
+ finally {
313
+ release();
267
314
  }
268
- throw new Error("Another BarnDog environment operation is running", {
269
- cause: error,
270
- });
271
- }
272
- const release = cleanUpIfInterrupted(() => rmSync(path, { recursive: true, force: true }));
273
- try {
274
- await writeFile(join(path, "pid"), String(process.pid), { mode: 0o600 });
275
- return await locks.run(new Set([...(locks.getStore() ?? []), home]), async () => {
276
- await recover(home);
277
- return run();
278
- });
279
- }
280
- finally {
281
- release();
282
- await rm(path, { recursive: true, force: true });
283
- }
315
+ });
284
316
  }