forge-workflow 0.1.0-beta.3 → 0.1.0-beta.5

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 (196) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +43 -1
  3. package/README.md +6 -2
  4. package/bin/forge-cmd.js +21 -1
  5. package/bin/forge.js +16 -369
  6. package/docs/INDEX.md +1 -1
  7. package/docs/guides/BEADS_GITHUB_SYNC.md +2 -31
  8. package/docs/guides/MIGRATION.md +4 -4
  9. package/docs/guides/SETUP.md +16 -16
  10. package/docs/reference/COMMANDS.md +9 -4
  11. package/docs/reference/INSIGHTS_RECAP.md +9 -20
  12. package/docs/reference/RELEASE.md +5 -3
  13. package/docs/reference/TOOLCHAIN.md +8 -0
  14. package/docs/reference/protected-state-surfaces.md +4 -4
  15. package/docs/reference/shepherd.md +117 -17
  16. package/lefthook.yml +12 -0
  17. package/lib/activation/ensure-forge-home.js +33 -15
  18. package/lib/adapters/greptile-review-adapter.js +1 -1
  19. package/lib/adapters/pr-state-adapter.js +397 -100
  20. package/lib/agents-config.js +5 -0
  21. package/lib/audit-evidence.js +71 -110
  22. package/lib/capped-jsonl-log.js +236 -0
  23. package/lib/commands/_issue.js +31 -46
  24. package/lib/commands/_manifest.js +1 -1
  25. package/lib/commands/_registry.js +2 -2
  26. package/lib/commands/_resolve-command-opts.js +36 -29
  27. package/lib/commands/claim.js +2 -4
  28. package/lib/commands/clean.js +196 -32
  29. package/lib/commands/dev.js +4 -33
  30. package/lib/commands/hooks.js +358 -13
  31. package/lib/commands/insights.js +8 -3
  32. package/lib/commands/merge.js +600 -40
  33. package/lib/commands/plan.js +23 -115
  34. package/lib/commands/pr.js +1 -1
  35. package/lib/commands/preflight.js +11 -2
  36. package/lib/commands/prime.js +23 -3
  37. package/lib/commands/push.js +41 -51
  38. package/lib/commands/recall.js +60 -16
  39. package/lib/commands/recap.js +6 -1
  40. package/lib/commands/release.js +18 -4
  41. package/lib/commands/serve.js +5 -2
  42. package/lib/commands/setup.js +191 -95
  43. package/lib/commands/shepherd.js +49 -4
  44. package/lib/commands/ship.js +22 -23
  45. package/lib/commands/skill.js +383 -0
  46. package/lib/commands/status.js +54 -33
  47. package/lib/commands/test.js +56 -34
  48. package/lib/commands/worktree.js +247 -43
  49. package/lib/core/runtime-graph.js +89 -15
  50. package/lib/doc-assertions.js +297 -0
  51. package/lib/existing-tdd-gate.js +253 -0
  52. package/lib/forge-context.js +1 -4
  53. package/lib/forge-issues.js +64 -491
  54. package/lib/git-defaults.js +56 -0
  55. package/lib/harness-capability-matrix.js +5 -5
  56. package/lib/hook-renderer.js +147 -16
  57. package/lib/insights.js +96 -80
  58. package/lib/issue-backend.js +42 -3
  59. package/lib/kernel/backing-issue.js +14 -2
  60. package/lib/kernel/broker.js +44 -0
  61. package/lib/kernel/cli-broker-factory.js +12 -1
  62. package/lib/kernel/close-on-merge.js +154 -0
  63. package/lib/kernel/fs-class.js +42 -25
  64. package/lib/kernel/migrations.js +30 -2
  65. package/lib/kernel/schema.js +35 -0
  66. package/lib/kernel/sqlite-driver.js +292 -18
  67. package/lib/lefthook-wiring.js +21 -1
  68. package/lib/memory/router.js +16 -1
  69. package/lib/memory-digest.js +47 -15
  70. package/lib/memory-recall-events.js +145 -0
  71. package/lib/memory-recall.js +212 -0
  72. package/lib/merge-rules.js +8 -4
  73. package/lib/npm-publish-workflow.js +272 -0
  74. package/lib/orientation.js +371 -49
  75. package/lib/plugin-catalog.js +14 -4
  76. package/lib/pr-bundle.js +9 -6
  77. package/lib/pr-monitor/journal.js +18 -2
  78. package/lib/pr-monitor/reconcile-executor.js +842 -0
  79. package/lib/pr-monitor/reconcile-tick.js +138 -0
  80. package/lib/pr-monitor/reconcile.js +0 -0
  81. package/lib/pr-monitor/render-summary.js +196 -0
  82. package/lib/pr-monitor/shepherd-lease.js +252 -0
  83. package/lib/pr-monitor/watch-lifecycle.js +14 -2
  84. package/lib/pr-pull.js +98 -24
  85. package/lib/pr-shepherd.js +34 -8
  86. package/lib/preflight/gates.js +65 -18
  87. package/lib/preflight/runner.js +5 -0
  88. package/lib/project-memory.js +40 -0
  89. package/lib/protected-state-authority.js +305 -0
  90. package/lib/protected-state-surfaces.js +64 -44
  91. package/lib/release-readiness.js +51 -4
  92. package/lib/rules-sync.js +4 -0
  93. package/lib/runtime-health.js +15 -46
  94. package/lib/shell-utils.js +1 -1
  95. package/lib/skill-eval.js +750 -0
  96. package/lib/skills-sync.js +6 -3
  97. package/lib/smart-merge.js +28 -4
  98. package/lib/status/identity.js +46 -0
  99. package/lib/status/presenter.js +0 -35
  100. package/lib/status/snapshot.js +11 -16
  101. package/lib/symlink-utils.js +74 -26
  102. package/lib/upgrade-safety.js +47 -9
  103. package/lib/using-forge.js +328 -0
  104. package/lib/workflow/enforce-stage.js +5 -5
  105. package/lib/workflow/state-manager.js +23 -23
  106. package/package.json +6 -7
  107. package/rules/using-forge.md +24 -0
  108. package/scripts/doc-asserting-tests.js +158 -0
  109. package/scripts/forge-team/index.sh +0 -5
  110. package/scripts/forge-team/tests/dispatcher.test.sh +1 -1
  111. package/scripts/forge-team/tests/workflow-integration.test.sh +0 -1
  112. package/scripts/lib/behavioral-eval-runner.js +310 -0
  113. package/scripts/lib/behavioral-eval-runtime.js +456 -0
  114. package/scripts/lib/eval-evidence.js +328 -0
  115. package/scripts/lib/eval-runner.js +81 -41
  116. package/scripts/lib/immutable-eval-corpus.js +309 -0
  117. package/scripts/lib/promotion-evidence-loader.js +94 -0
  118. package/scripts/lib/promotion-scorecard.js +314 -0
  119. package/scripts/npm-release-receipt.js +134 -0
  120. package/scripts/process-tree.js +761 -0
  121. package/scripts/protected-state-check.js +47 -22
  122. package/scripts/run-command-eval.js +29 -1
  123. package/scripts/sync-d20-audit.js +172 -0
  124. package/scripts/test-full-suite.js +249 -37
  125. package/scripts/test.js +184 -44
  126. package/skills/claim-safety/SKILL.md +4 -0
  127. package/skills/claim-safety/evals/scorecard.json +41 -0
  128. package/skills/coverage.json +83 -0
  129. package/skills/dev/SKILL.md +4 -0
  130. package/skills/dev/evals/scorecard.json +41 -0
  131. package/skills/gates/SKILL.md +80 -0
  132. package/skills/gates/evals/evals.json +38 -0
  133. package/skills/gates/evals/scorecard.json +41 -0
  134. package/skills/hermes-forge/SKILL.md +1 -0
  135. package/skills/hermes-forge/evals/scorecard.json +41 -0
  136. package/skills/issue-basics/SKILL.md +1 -0
  137. package/skills/issue-basics/evals/scorecard.json +41 -0
  138. package/skills/kernel/SKILL.md +38 -0
  139. package/skills/kernel/evals/scorecard.json +41 -0
  140. package/skills/memory/SKILL.md +16 -1
  141. package/skills/memory/evals/scorecard.json +41 -0
  142. package/skills/parallel-deep-research/SKILL.md +1 -0
  143. package/skills/parallel-deep-research/evals/scorecard.json +41 -0
  144. package/skills/plan/SKILL.md +6 -0
  145. package/skills/plan/evals/scorecard.json +41 -0
  146. package/skills/portability/SKILL.md +47 -0
  147. package/skills/portability/evals/evals.json +34 -0
  148. package/skills/portability/evals/scorecard.json +41 -0
  149. package/skills/research/SKILL.md +1 -0
  150. package/skills/research/evals/scorecard.json +41 -0
  151. package/skills/review/SKILL.md +10 -11
  152. package/skills/review/evals/scorecard.json +41 -0
  153. package/skills/rollback/SKILL.md +5 -11
  154. package/skills/rollback/evals/scorecard.json +41 -0
  155. package/skills/setup/SKILL.md +91 -0
  156. package/skills/setup/evals/evals.json +42 -0
  157. package/skills/setup/evals/scorecard.json +41 -0
  158. package/skills/shepherd/SKILL.md +84 -38
  159. package/skills/shepherd/evals/evals.json +21 -9
  160. package/skills/shepherd/evals/scorecard.json +41 -0
  161. package/skills/ship/SKILL.md +10 -12
  162. package/skills/ship/evals/scorecard.json +41 -0
  163. package/skills/smith/SKILL.md +8 -0
  164. package/skills/smith/evals/scorecard.json +41 -0
  165. package/skills/sonarcloud/SKILL.md +1 -0
  166. package/skills/sonarcloud/evals/scorecard.json +41 -0
  167. package/skills/sonarcloud-analysis/SKILL.md +1 -0
  168. package/skills/sonarcloud-analysis/evals/scorecard.json +41 -0
  169. package/skills/status/SKILL.md +3 -0
  170. package/skills/status/evals/scorecard.json +41 -0
  171. package/skills/triage-ready/SKILL.md +2 -0
  172. package/skills/triage-ready/evals/scorecard.json +41 -0
  173. package/skills/using-forge/SKILL.md +104 -0
  174. package/skills/using-forge/evals/scorecard.json +41 -0
  175. package/skills/validate/SKILL.md +4 -0
  176. package/skills/validate/evals/scorecard.json +41 -0
  177. package/skills/verify/SKILL.md +4 -0
  178. package/skills/verify/evals/scorecard.json +41 -0
  179. package/skills/worktree/SKILL.md +92 -0
  180. package/skills/worktree/evals/evals.json +38 -0
  181. package/skills/worktree/evals/scorecard.json +41 -0
  182. package/lib/adapters/beads-issue-adapter.js +0 -127
  183. package/lib/beads-nudge.js +0 -91
  184. package/lib/beads-setup.js +0 -538
  185. package/lib/beads-sync-scaffold.js +0 -189
  186. package/lib/commands/board.js +0 -64
  187. package/lib/pat-setup.js +0 -207
  188. package/lib/pr-monitor/render-sticky.js +0 -192
  189. package/lib/pr-monitor/upsert-sticky.js +0 -169
  190. package/lib/status/beads-snapshot.js +0 -145
  191. package/scripts/beads-context.sh +0 -577
  192. package/scripts/beads-migrate-to-dolt.sh +0 -7
  193. package/scripts/beads-upgrade-smoke.sh +0 -284
  194. package/scripts/forge-team/lib/dashboard.sh +0 -316
  195. package/scripts/forge-team/tests/dashboard.test.sh +0 -155
  196. package/scripts/lib/beads-migrate-to-dolt.mjs +0 -503
@@ -1,538 +0,0 @@
1
- /**
2
- * Utilities for configuring Beads during `forge setup`.
3
- *
4
- * Handles prefix sanitization, config/gitignore generation,
5
- * initialization detection, and legacy JSONL compatibility shims.
6
- *
7
- * @module beads-setup
8
- */
9
-
10
- const fs = require('node:fs');
11
- const path = require('node:path');
12
- const { spawnSync } = require('node:child_process');
13
- const { secureExecFileSync } = require('./shell-utils');
14
-
15
- const BEADS_LOCAL_EXCLUDE_LINES = [
16
- '# Forge local Beads state',
17
- '.beads/',
18
- '.dolt/',
19
- '.beads-credential-key'
20
- ];
21
-
22
- function isIgnorableFsError(error) {
23
- return ['EACCES', 'ENOENT', 'ENOTDIR', 'EPERM'].includes(error?.code);
24
- }
25
-
26
- function isRecoverableCommandError(error) {
27
- return error?.code === 'ENOENT' || typeof error?.status === 'number';
28
- }
29
-
30
- /**
31
- * Resolve a command to its full path to avoid relying on inherited PATH.
32
- * Falls back to the command name if resolution fails.
33
- * @param {string} command
34
- * @returns {string}
35
- */
36
- function resolveCommand(command) {
37
- const resolver = process.platform === 'win32' ? 'where.exe' : 'which';
38
- try {
39
- const result = spawnSync(resolver, [command], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
40
- if (result.status === 0 && result.stdout) {
41
- return result.stdout.trim().split(/\r?\n/)[0].trim();
42
- }
43
- } catch (error) {
44
- if (!isRecoverableCommandError(error)) {
45
- throw error;
46
- }
47
- // Expected: command resolution may fail if 'which'/'where.exe' is unavailable — fall back to bare command name
48
- }
49
- return command;
50
- }
51
-
52
- /**
53
- * Sanitize a repository name into a valid Beads issue prefix.
54
- *
55
- * Lowercases, replaces non-alphanumeric characters (except hyphens) with
56
- * hyphens, collapses consecutive hyphens, and trims leading/trailing hyphens.
57
- *
58
- * @param {string} repoName - Raw repository or project name
59
- * @returns {string} Sanitized prefix suitable for `issue-prefix`
60
- *
61
- * @example
62
- * sanitizePrefix('My-Project_v2!') // => 'my-project-v2'
63
- * sanitizePrefix(' Spaces ') // => 'spaces'
64
- */
65
- function sanitizePrefix(repoName) {
66
- return repoName
67
- .trim()
68
- .toLowerCase()
69
- .replaceAll(/[^a-z0-9-]/g, '-')
70
- .replaceAll(/-{2,}/g, '-')
71
- .replace(/^-/, '')
72
- .replace(/-$/, '');
73
- }
74
-
75
- /**
76
- * Write `.beads/config.yaml` with the given options.
77
- *
78
- * Creates the `.beads/` directory if it doesn't already exist.
79
- * The prefix is sanitized before writing.
80
- *
81
- * @param {string} projectRoot - Absolute path to the project root
82
- * @param {object} options - Configuration options
83
- * @param {string} options.prefix - Project prefix (will be sanitized)
84
- */
85
- function writeBeadsConfig(projectRoot, options) {
86
- const beadsDir = path.join(projectRoot, '.beads');
87
- fs.mkdirSync(beadsDir, { recursive: true });
88
-
89
- const prefix = sanitizePrefix(options.prefix);
90
- const configContent = [
91
- `issue-prefix: ${prefix}`,
92
- '',
93
- 'database:',
94
- ' backend: dolt',
95
- ''
96
- ].join('\n');
97
-
98
- fs.writeFileSync(path.join(beadsDir, 'config.yaml'), configContent, 'utf8');
99
- }
100
-
101
- /**
102
- * Write `.beads/.gitignore` with entries for Dolt binary files.
103
- *
104
- * Creates the `.beads/` directory if it doesn't already exist.
105
- *
106
- * @param {string} projectRoot - Absolute path to the project root
107
- */
108
- function writeBeadsGitignore(projectRoot) {
109
- const beadsDir = path.join(projectRoot, '.beads');
110
- fs.mkdirSync(beadsDir, { recursive: true });
111
-
112
- const gitignoreContent = [
113
- '# Beads runtime, export, and backup state is local',
114
- '*',
115
- '!.gitignore',
116
- '',
117
- '# Dolt database files (binary, not suitable for git)',
118
- 'dolt/',
119
- '*.db',
120
- '*.lock',
121
- ''
122
- ].join('\n');
123
-
124
- fs.writeFileSync(
125
- path.join(beadsDir, '.gitignore'),
126
- gitignoreContent,
127
- 'utf8'
128
- );
129
- }
130
-
131
- function resolveGitInfoExcludePath(projectRoot) {
132
- try {
133
- const gitExcludePath = secureExecFileSync(resolveCommand('git'), ['rev-parse', '--git-path', 'info/exclude'], {
134
- cwd: projectRoot,
135
- encoding: 'utf8',
136
- stdio: 'pipe'
137
- }).trim();
138
-
139
- if (gitExcludePath) {
140
- return path.isAbsolute(gitExcludePath)
141
- ? gitExcludePath
142
- : path.resolve(projectRoot, gitExcludePath);
143
- }
144
- } catch (error) {
145
- if (!isRecoverableCommandError(error)) {
146
- throw error;
147
- }
148
- }
149
-
150
- return path.join(projectRoot, '.git', 'info', 'exclude');
151
- }
152
-
153
- function untrackExistingBeadsState(projectRoot) {
154
- let tracked;
155
- try {
156
- tracked = secureExecFileSync(resolveCommand('git'), [
157
- 'ls-files',
158
- '-z',
159
- '--',
160
- '.beads',
161
- '.dolt',
162
- '.beads-credential-key'
163
- ], {
164
- cwd: projectRoot,
165
- encoding: 'utf8',
166
- stdio: 'pipe'
167
- });
168
- } catch (error) {
169
- if (!isRecoverableCommandError(error)) {
170
- throw error;
171
- }
172
- return;
173
- }
174
-
175
- if (!tracked) {
176
- return;
177
- }
178
-
179
- try {
180
- secureExecFileSync(resolveCommand('git'), [
181
- 'rm',
182
- '--cached',
183
- '-r',
184
- '-f',
185
- '--ignore-unmatch',
186
- '--',
187
- '.beads',
188
- '.dolt',
189
- '.beads-credential-key'
190
- ], {
191
- cwd: projectRoot,
192
- encoding: 'utf8',
193
- stdio: 'pipe'
194
- });
195
- } catch (error) {
196
- if (!isRecoverableCommandError(error)) {
197
- throw error;
198
- }
199
- }
200
- }
201
-
202
- /**
203
- * Add local-only Git exclude rules for Beads state.
204
- *
205
- * Uses `.git/info/exclude` instead of the tracked `.gitignore` so `forge setup`
206
- * does not dirty downstream repositories just to keep Beads runtime files local.
207
- * Existing tracked Beads state is removed from the Git index only, leaving local
208
- * files in place for the Beads runtime.
209
- *
210
- * @param {string} projectRoot - Absolute path to the project root
211
- */
212
- function ensureBeadsGitExclude(projectRoot) {
213
- const excludePath = resolveGitInfoExcludePath(projectRoot);
214
- fs.mkdirSync(path.dirname(excludePath), { recursive: true });
215
-
216
- const existing = fs.existsSync(excludePath)
217
- ? fs.readFileSync(excludePath, 'utf8')
218
- : '';
219
- const existingLines = new Set(existing.split(/\r?\n/));
220
- const missingLines = BEADS_LOCAL_EXCLUDE_LINES.filter((line) => !existingLines.has(line));
221
-
222
- if (missingLines.length === 0) {
223
- untrackExistingBeadsState(projectRoot);
224
- return;
225
- }
226
-
227
- const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
228
- const spacer = existing.trim() ? '\n' : '';
229
- fs.appendFileSync(excludePath, `${prefix}${spacer}${missingLines.join('\n')}\n`, 'utf8');
230
- untrackExistingBeadsState(projectRoot);
231
- }
232
-
233
- /**
234
- * Check whether Beads is properly initialized in a project.
235
- *
236
- * Returns `true` when all of the following are present:
237
- * - `.beads/` directory exists
238
- * - `.beads/config.yaml` exists and contains an `issue-prefix` key
239
- * - the config points to either:
240
- * - a legacy SQLite tracker with legacy data markers present, or
241
- * - a Dolt-backed tracker with at least one post-`bd init` marker present
242
- *
243
- * Legacy SQLite-backed Beads installs also count as initialized so `forge setup`
244
- * does not run `bd init` over an existing tracker before migration.
245
- *
246
- * @param {string} projectRoot - Absolute path to the project root
247
- * @returns {boolean} `true` if Beads is fully initialized
248
- */
249
- function isBeadsInitialized(projectRoot) {
250
- const beadsDir = path.join(projectRoot, '.beads');
251
- const configPath = path.join(beadsDir, 'config.yaml');
252
-
253
- if (!fs.existsSync(beadsDir)) return false;
254
- if (!fs.existsSync(configPath)) return false;
255
-
256
- const configContent = fs.readFileSync(configPath, 'utf8');
257
- if (!configContent.includes('issue-prefix:')) return false;
258
-
259
- const hasLegacyState = [
260
- 'issues.jsonl',
261
- 'backup',
262
- 'bd.db',
263
- 'beads.db',
264
- 'db.sqlite'
265
- ].some((entry) => fs.existsSync(path.join(beadsDir, entry)));
266
- const hasDoltMetadata = fs.existsSync(path.join(beadsDir, 'metadata.json'));
267
- const hasDoltCompanionState = [
268
- 'README.md',
269
- 'hooks',
270
- 'redirect'
271
- ].some((entry) => fs.existsSync(path.join(beadsDir, entry)));
272
- const hasDoltState = hasDoltMetadata && hasDoltCompanionState;
273
-
274
- if (configContent.includes('backend: sqlite')) {
275
- return hasLegacyState;
276
- }
277
-
278
- if (configContent.includes('backend: dolt')) {
279
- return hasDoltState;
280
- }
281
-
282
- return hasLegacyState || hasDoltState;
283
- }
284
-
285
- function readBeadsDatabaseName(projectRoot) {
286
- const metadataPath = path.join(projectRoot, '.beads', 'metadata.json');
287
- if (!fs.existsSync(metadataPath)) {
288
- return null;
289
- }
290
-
291
- try {
292
- const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
293
- if (typeof metadata.dolt_database === 'string' && metadata.dolt_database.trim()) {
294
- return metadata.dolt_database.trim();
295
- }
296
- if (typeof metadata.database === 'string' && metadata.database.trim()) {
297
- return metadata.database.trim();
298
- }
299
- } catch (error) {
300
- if (error instanceof SyntaxError || isIgnorableFsError(error)) {
301
- return null;
302
- }
303
- throw error;
304
- }
305
-
306
- return null;
307
- }
308
-
309
- /**
310
- * Legacy compatibility shim for the removed JSONL pre-seed workaround.
311
- *
312
- * Beads latest no longer requires `.beads/issues.jsonl` during init, so
313
- * this helper intentionally does nothing. It remains exported because some
314
- * older tests and setup paths still import it.
315
- *
316
- * @param {string} _projectRoot - Absolute path to the project root
317
- */
318
- function preSeedJsonl(_projectRoot) {
319
- // Legacy no-op: Dolt-backed Beads no longer requires JSONL pre-seeding.
320
- }
321
-
322
- // ---------------------------------------------------------------------------
323
- // Task 11: Defensive bd init wrapper
324
- // ---------------------------------------------------------------------------
325
-
326
- /**
327
- * Snapshot all files in a directory — returns a Map of filename to content (Buffer).
328
- * Returns an empty Map if the directory does not exist.
329
- *
330
- * @param {string} dirPath - Absolute path to the directory to snapshot
331
- * @returns {Map<string, Buffer>} Map of filename to raw file contents
332
- */
333
- function snapshotDirectory(dirPath) {
334
- const snapshot = new Map();
335
-
336
- if (!fs.existsSync(dirPath)) {
337
- return snapshot;
338
- }
339
-
340
- const entries = fs.readdirSync(dirPath);
341
- for (const entry of entries) {
342
- const fullPath = path.join(dirPath, entry);
343
- try {
344
- const stat = fs.statSync(fullPath);
345
- if (stat.isFile()) {
346
- snapshot.set(entry, fs.readFileSync(fullPath));
347
- }
348
- } catch (_err) {
349
- // Expected: file may be locked or permission-denied — skip unreadable files during snapshot
350
- }
351
- }
352
-
353
- return snapshot;
354
- }
355
-
356
- /**
357
- * Restore a directory to exactly match a snapshot — overwrite changed files,
358
- * remove files not in the snapshot, recreate deleted files.
359
- *
360
- * @param {string} dirPath - Absolute path to the directory to restore
361
- * @param {Map<string, Buffer>} snapshot - Snapshot from snapshotDirectory()
362
- */
363
- function restoreDirectory(dirPath, snapshot) {
364
- fs.mkdirSync(dirPath, { recursive: true });
365
-
366
- // Remove files that were not in the original snapshot
367
- const currentFiles = fs.readdirSync(dirPath);
368
- for (const file of currentFiles) {
369
- const fullPath = path.join(dirPath, file);
370
- try {
371
- if (fs.statSync(fullPath).isFile() && !snapshot.has(file)) {
372
- fs.unlinkSync(fullPath);
373
- }
374
- } catch (_err) {
375
- // Expected: file may be locked or already removed — skip files we cannot stat or remove during restore
376
- }
377
- }
378
-
379
- // Write all files from the snapshot
380
- for (const [name, content] of snapshot) {
381
- fs.writeFileSync(path.join(dirPath, name), content, { mode: 0o755 });
382
- }
383
- }
384
-
385
- function resolveHooksDir(projectRoot) {
386
- const fallbackHooksDir = path.join(projectRoot, '.git', 'hooks');
387
-
388
- try {
389
- const gitHooksPath = secureExecFileSync(resolveCommand('git'), ['rev-parse', '--git-path', 'hooks'], {
390
- cwd: projectRoot,
391
- encoding: 'utf8',
392
- stdio: 'pipe'
393
- }).trim();
394
-
395
- if (!gitHooksPath) {
396
- return fallbackHooksDir;
397
- }
398
-
399
- return path.isAbsolute(gitHooksPath)
400
- ? gitHooksPath
401
- : path.resolve(projectRoot, gitHooksPath);
402
- } catch (error) {
403
- if (isRecoverableCommandError(error)) {
404
- return fallbackHooksDir;
405
- }
406
- throw error;
407
- }
408
- }
409
-
410
- /**
411
- * Default bd init executor — calls `execFileSync('bd', ['init'])`.
412
- *
413
- * @param {string} projectRoot - Absolute path to the project root
414
- */
415
- function defaultExecBdInit(projectRoot) {
416
- const { execFileSync } = require('node:child_process');
417
- execFileSync(resolveCommand('bd'), ['init'], {
418
- cwd: projectRoot,
419
- stdio: 'pipe'
420
- });
421
- }
422
-
423
- /**
424
- * Defensive wrapper for `bd init` — orchestrates Beads initialization
425
- * with hook snapshot/restore to prevent bd from overwriting git hooks.
426
- *
427
- * Flow:
428
- * a. Check if already initialized (idempotent skip)
429
- * b. Write config.yaml with correct prefix
430
- * c. Write .beads/.gitignore for Dolt files
431
- * d. Snapshot .git/hooks/
432
- * e. Run bd init (via execBdInit callback or default execFileSync)
433
- * f. Restore .git/hooks/ from snapshot
434
- * g. Restore lefthook hooks if callback provided
435
- * h. Skip the removed issues.jsonl pre-seed workaround
436
- *
437
- * @param {string} projectRoot - Absolute path to the project root
438
- * @param {Object} [options={}] - Configuration options
439
- * @param {string} [options.prefix] - Issue prefix (repo name), sanitized before use
440
- * @param {Function} [options.execBdInit] - Custom bd init executor. Receives (projectRoot).
441
- * Defaults to calling execFileSync('bd', ['init']).
442
- * @param {Function} [options.restoreLefthook] - Optional callback to restore lefthook hooks
443
- * (e.g., running `npx lefthook install`). Non-fatal if it throws.
444
- * @returns {{ success: boolean, skipped: boolean, reason?: string, warnings: string[], errors: string[] }}
445
- */
446
- function safeBeadsInit(projectRoot, options = {}) {
447
- const warnings = [];
448
- const errors = [];
449
-
450
- // Keep Beads runtime/export state local even when the tracker already exists.
451
- try {
452
- ensureBeadsGitExclude(projectRoot);
453
- } catch (err) {
454
- warnings.push(`Failed to write local Beads git exclude rules: ${err.message}`);
455
- }
456
-
457
- // (a) Check if already initialized — idempotent skip
458
- if (isBeadsInitialized(projectRoot)) {
459
- return {
460
- success: true,
461
- skipped: true,
462
- reason: 'already initialized',
463
- warnings,
464
- errors
465
- };
466
- }
467
-
468
- // (b) Write config.yaml with correct prefix
469
- const prefix = options.prefix || '';
470
- try {
471
- writeBeadsConfig(projectRoot, { prefix });
472
- } catch (err) {
473
- warnings.push(`Failed to write config.yaml: ${err.message}`);
474
- }
475
-
476
- // (c) Write .beads/.gitignore for Dolt files
477
- try {
478
- writeBeadsGitignore(projectRoot);
479
- } catch (err) {
480
- warnings.push(`Failed to write .beads/.gitignore: ${err.message}`);
481
- }
482
-
483
- // (d) Snapshot current .git/hooks/ directory
484
- const hooksDir = resolveHooksDir(projectRoot);
485
- const hooksSnapshot = snapshotDirectory(hooksDir);
486
-
487
- // (e) Run bd init — wrapped in try/catch
488
- const execBdInit = options.execBdInit || defaultExecBdInit;
489
- try {
490
- execBdInit(projectRoot);
491
- } catch (err) {
492
- // Always restore hooks, even on failure
493
- restoreDirectory(hooksDir, hooksSnapshot);
494
-
495
- if (err.code === 'ENOENT') {
496
- errors.push('bd CLI not installed');
497
- } else {
498
- errors.push(err.message);
499
- }
500
-
501
- return {
502
- success: false,
503
- skipped: false,
504
- warnings,
505
- errors
506
- };
507
- }
508
-
509
- // (f) Restore .git/hooks/ from snapshot
510
- restoreDirectory(hooksDir, hooksSnapshot);
511
-
512
- // (g) Restore lefthook hooks if callback provided
513
- if (typeof options.restoreLefthook === 'function') {
514
- try {
515
- options.restoreLefthook(projectRoot);
516
- } catch (err) {
517
- warnings.push(`Failed to restore lefthook hooks: ${err.message}`);
518
- }
519
- }
520
-
521
- return {
522
- success: true,
523
- skipped: false,
524
- warnings,
525
- errors
526
- };
527
- }
528
-
529
- module.exports = {
530
- sanitizePrefix,
531
- writeBeadsConfig,
532
- writeBeadsGitignore,
533
- ensureBeadsGitExclude,
534
- isBeadsInitialized,
535
- readBeadsDatabaseName,
536
- preSeedJsonl,
537
- safeBeadsInit
538
- };