forge-workflow 0.0.4 → 0.0.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 (209) hide show
  1. package/.claude/commands/dev.md +340 -340
  2. package/.claude/commands/plan.md +521 -521
  3. package/.claude/commands/premerge.md +176 -176
  4. package/.claude/commands/research.md +42 -42
  5. package/.claude/commands/review.md +442 -442
  6. package/.claude/commands/rollback.md +721 -721
  7. package/.claude/commands/ship.md +164 -164
  8. package/.claude/commands/sonarcloud.md +152 -152
  9. package/.claude/commands/status.md +48 -48
  10. package/.claude/commands/validate.md +282 -282
  11. package/.claude/commands/verify.md +221 -221
  12. package/.claude/rules/greptile-review-process.md +285 -285
  13. package/.claude/rules/workflow.md +105 -105
  14. package/.claude/scripts/greptile-resolve.sh +526 -526
  15. package/.claude/scripts/load-env.sh +32 -32
  16. package/.cline/workflows/dev.md +337 -337
  17. package/.cline/workflows/plan.md +518 -518
  18. package/.cline/workflows/premerge.md +173 -173
  19. package/.cline/workflows/research.md +39 -39
  20. package/.cline/workflows/review.md +439 -439
  21. package/.cline/workflows/rollback.md +718 -718
  22. package/.cline/workflows/ship.md +161 -161
  23. package/.cline/workflows/sonarcloud.md +146 -146
  24. package/.cline/workflows/status.md +45 -45
  25. package/.cline/workflows/validate.md +279 -279
  26. package/.cline/workflows/verify.md +218 -218
  27. package/.codex/config.toml +11 -11
  28. package/.codex/skills/dev/SKILL.md +340 -340
  29. package/.codex/skills/plan/SKILL.md +521 -521
  30. package/.codex/skills/premerge/SKILL.md +176 -176
  31. package/.codex/skills/research/SKILL.md +42 -42
  32. package/.codex/skills/review/SKILL.md +442 -442
  33. package/.codex/skills/rollback/SKILL.md +721 -721
  34. package/.codex/skills/ship/SKILL.md +164 -164
  35. package/.codex/skills/sonarcloud/SKILL.md +149 -149
  36. package/.codex/skills/status/SKILL.md +48 -48
  37. package/.codex/skills/validate/SKILL.md +282 -282
  38. package/.codex/skills/verify/SKILL.md +221 -221
  39. package/.cursor/commands/dev.md +337 -337
  40. package/.cursor/commands/plan.md +518 -518
  41. package/.cursor/commands/premerge.md +173 -173
  42. package/.cursor/commands/research.md +39 -39
  43. package/.cursor/commands/review.md +439 -439
  44. package/.cursor/commands/rollback.md +718 -718
  45. package/.cursor/commands/ship.md +161 -161
  46. package/.cursor/commands/sonarcloud.md +146 -146
  47. package/.cursor/commands/status.md +45 -45
  48. package/.cursor/commands/validate.md +279 -279
  49. package/.cursor/commands/verify.md +218 -218
  50. package/.cursor/rules/permissions-guidance.mdc +37 -37
  51. package/.forge/hooks/check-tdd.js +240 -240
  52. package/.github/PLUGIN_TEMPLATE.json +32 -32
  53. package/.github/prompts/dev.prompt.md +342 -342
  54. package/.github/prompts/plan.prompt.md +523 -523
  55. package/.github/prompts/premerge.prompt.md +178 -178
  56. package/.github/prompts/research.prompt.md +44 -44
  57. package/.github/prompts/review.prompt.md +444 -444
  58. package/.github/prompts/rollback.prompt.md +723 -723
  59. package/.github/prompts/ship.prompt.md +166 -166
  60. package/.github/prompts/sonarcloud.prompt.md +151 -151
  61. package/.github/prompts/status.prompt.md +50 -50
  62. package/.github/prompts/validate.prompt.md +284 -284
  63. package/.github/prompts/verify.prompt.md +223 -223
  64. package/.github/workflows/beads-to-github.yml +56 -0
  65. package/.github/workflows/github-to-beads.yml +97 -0
  66. package/.kilocode/workflows/dev.md +341 -341
  67. package/.kilocode/workflows/plan.md +522 -522
  68. package/.kilocode/workflows/premerge.md +177 -177
  69. package/.kilocode/workflows/research.md +43 -43
  70. package/.kilocode/workflows/review.md +443 -443
  71. package/.kilocode/workflows/rollback.md +722 -722
  72. package/.kilocode/workflows/ship.md +165 -165
  73. package/.kilocode/workflows/sonarcloud.md +150 -150
  74. package/.kilocode/workflows/status.md +49 -49
  75. package/.kilocode/workflows/validate.md +283 -283
  76. package/.kilocode/workflows/verify.md +222 -222
  77. package/.mcp.json.example +12 -12
  78. package/.opencode/commands/dev.md +340 -340
  79. package/.opencode/commands/plan.md +521 -521
  80. package/.opencode/commands/premerge.md +176 -176
  81. package/.opencode/commands/research.md +42 -42
  82. package/.opencode/commands/review.md +442 -442
  83. package/.opencode/commands/rollback.md +721 -721
  84. package/.opencode/commands/ship.md +164 -164
  85. package/.opencode/commands/sonarcloud.md +149 -149
  86. package/.opencode/commands/status.md +48 -48
  87. package/.opencode/commands/validate.md +282 -282
  88. package/.opencode/commands/verify.md +221 -221
  89. package/.roo/commands/dev.md +341 -341
  90. package/.roo/commands/plan.md +522 -522
  91. package/.roo/commands/premerge.md +177 -177
  92. package/.roo/commands/research.md +43 -43
  93. package/.roo/commands/review.md +443 -443
  94. package/.roo/commands/rollback.md +722 -722
  95. package/.roo/commands/ship.md +165 -165
  96. package/.roo/commands/sonarcloud.md +150 -150
  97. package/.roo/commands/status.md +49 -49
  98. package/.roo/commands/validate.md +283 -283
  99. package/.roo/commands/verify.md +222 -222
  100. package/AGENTS.md +175 -175
  101. package/CLAUDE.md +100 -100
  102. package/README.md +429 -416
  103. package/bin/forge-cmd.js +313 -313
  104. package/bin/forge-preflight.js +309 -309
  105. package/bin/forge.js +4596 -4303
  106. package/docs/AGENT_INSTALL_PROMPT.md +342 -342
  107. package/docs/BEADS_GITHUB_SYNC.md +251 -251
  108. package/docs/ENHANCED_ONBOARDING.md +602 -602
  109. package/docs/EXAMPLES.md +482 -482
  110. package/docs/GREPTILE_SETUP.md +400 -400
  111. package/docs/MANUAL_REVIEW_GUIDE.md +106 -106
  112. package/docs/ROADMAP.md +359 -359
  113. package/docs/SETUP.md +663 -631
  114. package/docs/TOOLCHAIN.md +630 -630
  115. package/docs/VALIDATION.md +363 -363
  116. package/install.sh +40 -1056
  117. package/lefthook.yml +39 -39
  118. package/lib/agents/README.md +198 -198
  119. package/lib/agents/claude.plugin.json +28 -28
  120. package/lib/agents/cline.plugin.json +22 -22
  121. package/lib/agents/codex.plugin.json +19 -19
  122. package/lib/agents/copilot.plugin.json +24 -24
  123. package/lib/agents/cursor.plugin.json +25 -25
  124. package/lib/agents/kilocode.plugin.json +22 -22
  125. package/lib/agents/opencode.plugin.json +20 -20
  126. package/lib/agents/roo.plugin.json +23 -23
  127. package/lib/agents-config.js +2112 -2112
  128. package/lib/beads-health-check.js +143 -0
  129. package/lib/beads-setup.js +341 -0
  130. package/lib/beads-sync-scaffold.js +260 -0
  131. package/lib/commands/dev.js +513 -513
  132. package/lib/commands/plan.js +692 -692
  133. package/lib/commands/recommend.js +119 -119
  134. package/lib/commands/ship.js +377 -377
  135. package/lib/commands/status.js +378 -378
  136. package/lib/commands/validate.js +602 -602
  137. package/lib/context-merge.js +359 -359
  138. package/lib/dep-guard/analyzer.js +294 -294
  139. package/lib/dep-guard/behavior-detector.js +98 -98
  140. package/lib/dep-guard/contract-detector.js +162 -162
  141. package/lib/dep-guard/import-detector.js +498 -498
  142. package/lib/dep-guard/path-utils.js +13 -13
  143. package/lib/dep-guard/rubric.js +120 -120
  144. package/lib/dep-guard/task-parser.js +318 -318
  145. package/lib/detect-agent.js +191 -191
  146. package/lib/detect-worktree.js +47 -47
  147. package/lib/file-hash.js +26 -26
  148. package/lib/husky-migration.js +450 -0
  149. package/lib/lefthook-check.js +65 -0
  150. package/lib/pat-setup.js +207 -0
  151. package/lib/plugin-catalog.js +350 -350
  152. package/lib/plugin-manager.js +166 -166
  153. package/lib/plugin-recommender.js +141 -141
  154. package/lib/project-discovery.js +491 -491
  155. package/lib/setup-action-log.js +139 -139
  156. package/lib/setup-summary-renderer.js +106 -106
  157. package/lib/setup-utils.js +96 -0
  158. package/lib/setup.js +192 -192
  159. package/lib/smart-merge.js +64 -0
  160. package/lib/symlink-utils.js +81 -0
  161. package/lib/workflow-profiles.js +197 -197
  162. package/package.json +131 -128
  163. package/scripts/beads-context.sh +291 -0
  164. package/scripts/beads-context.test.js +563 -0
  165. package/scripts/behavioral-judge.sh +378 -0
  166. package/scripts/benchmark.js +85 -0
  167. package/scripts/branch-protection.js +183 -0
  168. package/scripts/check-agents.js +172 -0
  169. package/scripts/commitlint.js +42 -0
  170. package/scripts/conflict-detect.sh +323 -0
  171. package/scripts/dep-guard-analyze.js +71 -0
  172. package/scripts/dep-guard.sh +811 -0
  173. package/scripts/eval_win.py +249 -0
  174. package/scripts/file-index.sh +399 -0
  175. package/scripts/github-beads-sync/comment.mjs +64 -0
  176. package/scripts/github-beads-sync/config.mjs +148 -0
  177. package/scripts/github-beads-sync/github-api.mjs +131 -0
  178. package/scripts/github-beads-sync/index.mjs +332 -0
  179. package/scripts/github-beads-sync/label-mapper.mjs +54 -0
  180. package/scripts/github-beads-sync/mapping.mjs +78 -0
  181. package/scripts/github-beads-sync/reverse-sync-cli.mjs +31 -0
  182. package/scripts/github-beads-sync/reverse-sync.mjs +138 -0
  183. package/scripts/github-beads-sync/run-bd.mjs +159 -0
  184. package/scripts/github-beads-sync/sanitize.mjs +121 -0
  185. package/scripts/github-beads-sync.config.json +26 -0
  186. package/scripts/improve-command.js +375 -0
  187. package/scripts/lib/eval-runner.js +229 -0
  188. package/scripts/lib/eval-schema.js +135 -0
  189. package/scripts/lib/eval-storage.js +78 -0
  190. package/scripts/lib/grading.js +203 -0
  191. package/scripts/lib/transcript-parser.js +63 -0
  192. package/scripts/lint.js +47 -0
  193. package/scripts/migrate-to-bun-test.js +412 -0
  194. package/scripts/run-command-eval.js +236 -0
  195. package/scripts/smart-status.sh +782 -0
  196. package/scripts/sync-commands.js +571 -0
  197. package/scripts/sync-utils.sh +460 -0
  198. package/scripts/test-dashboard.js +123 -0
  199. package/scripts/test.js +44 -0
  200. package/scripts/validate.sh +94 -0
  201. package/skills/parallel-deep-research/SKILL.md +108 -108
  202. package/skills/parallel-deep-research/evals/README.md +27 -27
  203. package/skills/parallel-deep-research/evals/evals.json +62 -62
  204. package/skills/sonarcloud-analysis/SKILL.md +171 -171
  205. package/skills/sonarcloud-analysis/evals/README.md +27 -27
  206. package/skills/sonarcloud-analysis/evals/evals.json +50 -50
  207. package/skills/sonarcloud-analysis/references/api-reference.md +466 -466
  208. package/.cursor/hooks/state/continual-learning-index.json +0 -19
  209. package/.cursor/hooks/state/continual-learning.json +0 -8
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Beads health check smoke test.
3
+ *
4
+ * After Beads init, runs a quick create/close/sync/cleanup cycle to verify
5
+ * the installation is functional.
6
+ *
7
+ * @module beads-health-check
8
+ */
9
+
10
+ const { execFileSync } = require('node:child_process');
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+
14
+ /**
15
+ * @typedef {Object} HealthCheckResult
16
+ * @property {boolean} healthy - Whether Beads is operational
17
+ * @property {string|null} failedStep - Which step failed: 'create'|'close'|'sync'|'cleanup', or null
18
+ * @property {string|null} error - Error message if unhealthy, null otherwise
19
+ * @property {string} [warning] - Non-fatal warning message (e.g. sync or cleanup issues)
20
+ */
21
+
22
+ /**
23
+ * Parse the issue ID from `bd create` stdout.
24
+ *
25
+ * Expects output like "Created issue: forge-xxxx".
26
+ *
27
+ * @param {string} output - stdout from `bd create`
28
+ * @returns {string|null} The issue ID, or null if not found
29
+ */
30
+ function parseIssueId(output) {
31
+ const match = /Created\s+issue:\s*([\w-]+)/i.exec(output);
32
+ return match ? match[1].trim() : null;
33
+ }
34
+
35
+ /**
36
+ * Remove a test issue from the JSONL file by its ID.
37
+ * Silently ignores errors (file missing, locked, malformed lines).
38
+ *
39
+ * @param {string} jsonlPath - Absolute path to the issues.jsonl file
40
+ * @param {string|null} issueId - The issue ID to remove
41
+ */
42
+ function cleanupTestIssue(jsonlPath, issueId) {
43
+ if (!issueId) return;
44
+ const raw = fs.readFileSync(jsonlPath, 'utf8');
45
+ const lines = raw.split('\n').filter(Boolean);
46
+ const filtered = lines.filter((line) => {
47
+ try { return JSON.parse(line).id !== issueId; } catch (_e) { /* Expected: malformed JSONL line — keep it as-is */ return true; }
48
+ });
49
+ fs.writeFileSync(jsonlPath, filtered.length > 0 ? filtered.join('\n') + '\n' : '');
50
+ }
51
+
52
+ /**
53
+ * Run a Beads health check smoke test.
54
+ *
55
+ * Creates a temporary issue, closes it, syncs, then cleans up the JSONL file.
56
+ * Uses dependency injection for the exec function to support testing.
57
+ *
58
+ * @param {string} projectRoot - Absolute path to the project root
59
+ * @param {Object} [options={}] - Options
60
+ * @param {Function} [options._exec] - Injectable exec function (defaults to execFileSync)
61
+ * @returns {HealthCheckResult}
62
+ */
63
+ function beadsHealthCheck(projectRoot, options = {}) {
64
+ const exec = options._exec || execFileSync;
65
+ const execOpts = { cwd: projectRoot, encoding: 'utf8' };
66
+
67
+ /** @type {string|undefined} */
68
+ let warning;
69
+
70
+ // Step a: Create a test issue
71
+ /** @type {string|null} */
72
+ let issueId;
73
+ try {
74
+ const createOutput = exec('bd', [
75
+ 'create',
76
+ '--title=Setup verification',
77
+ '--type=task',
78
+ '--priority=4'
79
+ ], execOpts);
80
+
81
+ issueId = parseIssueId(createOutput);
82
+ if (!issueId) {
83
+ return {
84
+ healthy: false,
85
+ failedStep: 'create',
86
+ error: 'Could not parse issue ID from bd create output'
87
+ };
88
+ }
89
+ } catch (err) {
90
+ return {
91
+ healthy: false,
92
+ failedStep: 'create',
93
+ error: err.message
94
+ };
95
+ }
96
+
97
+ // Step b: Close the test issue
98
+ try {
99
+ exec('bd', [
100
+ 'close',
101
+ issueId,
102
+ '--reason=Setup smoke test'
103
+ ], execOpts);
104
+ } catch (err) {
105
+ // Best-effort cleanup: remove the test issue from JSONL so it doesn't leak
106
+ try {
107
+ cleanupTestIssue(path.join(projectRoot, '.beads', 'issues.jsonl'), issueId);
108
+ } catch (_cleanupErr) {
109
+ // Expected: JSONL cleanup may fail if file is locked or missing — nothing more we can do
110
+ }
111
+ return {
112
+ healthy: false,
113
+ failedStep: 'close',
114
+ error: err.message
115
+ };
116
+ }
117
+
118
+ // Step c: Sync (may fail without a remote -- that's OK)
119
+ try {
120
+ exec('bd', ['sync'], execOpts);
121
+ } catch (syncErr) {
122
+ // Sync failure is non-fatal (no remote configured is common)
123
+ warning = `bd sync warning: ${syncErr.message}`;
124
+ }
125
+
126
+ // Step d: Remove the test issue from JSONL
127
+ try {
128
+ cleanupTestIssue(path.join(projectRoot, '.beads', 'issues.jsonl'), issueId);
129
+ } catch (cleanupErr) {
130
+ // Cleanup failure is non-fatal
131
+ const cleanupWarning = `cleanup warning: ${cleanupErr.message}`;
132
+ warning = warning ? `${warning}; ${cleanupWarning}` : cleanupWarning;
133
+ }
134
+
135
+ return {
136
+ healthy: true,
137
+ failedStep: null,
138
+ error: null,
139
+ ...(warning ? { warning } : {})
140
+ };
141
+ }
142
+
143
+ module.exports = { beadsHealthCheck, parseIssueId };
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Utilities for configuring Beads during `forge setup`.
3
+ *
4
+ * Handles prefix sanitization, config/gitignore generation,
5
+ * initialization detection, and issues.jsonl pre-seeding.
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
+
14
+ /**
15
+ * Resolve a command to its full path to avoid relying on inherited PATH.
16
+ * Falls back to the command name if resolution fails.
17
+ * @param {string} command
18
+ * @returns {string}
19
+ */
20
+ function resolveCommand(command) {
21
+ const resolver = process.platform === 'win32' ? 'where.exe' : 'which';
22
+ try {
23
+ const result = spawnSync(resolver, [command], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
24
+ if (result.status === 0 && result.stdout) {
25
+ return result.stdout.trim().split(/\r?\n/)[0].trim();
26
+ }
27
+ } catch (_e) {
28
+ // Expected: command resolution may fail if 'which'/'where.exe' is unavailable — fall back to bare command name
29
+ }
30
+ return command;
31
+ }
32
+
33
+ /**
34
+ * Sanitize a repository name into a valid Beads issue prefix.
35
+ *
36
+ * Lowercases, replaces non-alphanumeric characters (except hyphens) with
37
+ * hyphens, collapses consecutive hyphens, and trims leading/trailing hyphens.
38
+ *
39
+ * @param {string} repoName - Raw repository or project name
40
+ * @returns {string} Sanitized prefix suitable for `issue-prefix`
41
+ *
42
+ * @example
43
+ * sanitizePrefix('My-Project_v2!') // => 'my-project-v2'
44
+ * sanitizePrefix(' Spaces ') // => 'spaces'
45
+ */
46
+ function sanitizePrefix(repoName) {
47
+ return repoName
48
+ .trim()
49
+ .toLowerCase()
50
+ .replaceAll(/[^a-z0-9-]/g, '-')
51
+ .replaceAll(/-{2,}/g, '-')
52
+ .replace(/^-/, '')
53
+ .replace(/-$/, '');
54
+ }
55
+
56
+ /**
57
+ * Write `.beads/config.yaml` with the given options.
58
+ *
59
+ * Creates the `.beads/` directory if it doesn't already exist.
60
+ * The prefix is sanitized before writing.
61
+ *
62
+ * @param {string} projectRoot - Absolute path to the project root
63
+ * @param {object} options - Configuration options
64
+ * @param {string} options.prefix - Project prefix (will be sanitized)
65
+ */
66
+ function writeBeadsConfig(projectRoot, options) {
67
+ const beadsDir = path.join(projectRoot, '.beads');
68
+ fs.mkdirSync(beadsDir, { recursive: true });
69
+
70
+ const prefix = sanitizePrefix(options.prefix);
71
+ const configContent = [
72
+ `issue-prefix: ${prefix}`,
73
+ '',
74
+ 'database:',
75
+ ' backend: dolt',
76
+ ''
77
+ ].join('\n');
78
+
79
+ fs.writeFileSync(path.join(beadsDir, 'config.yaml'), configContent, 'utf8');
80
+ }
81
+
82
+ /**
83
+ * Write `.beads/.gitignore` with entries for Dolt binary files.
84
+ *
85
+ * Creates the `.beads/` directory if it doesn't already exist.
86
+ *
87
+ * @param {string} projectRoot - Absolute path to the project root
88
+ */
89
+ function writeBeadsGitignore(projectRoot) {
90
+ const beadsDir = path.join(projectRoot, '.beads');
91
+ fs.mkdirSync(beadsDir, { recursive: true });
92
+
93
+ const gitignoreContent = [
94
+ '# Dolt database files (binary, not suitable for git)',
95
+ 'dolt/',
96
+ '*.db',
97
+ '*.lock',
98
+ ''
99
+ ].join('\n');
100
+
101
+ fs.writeFileSync(
102
+ path.join(beadsDir, '.gitignore'),
103
+ gitignoreContent,
104
+ 'utf8'
105
+ );
106
+ }
107
+
108
+ /**
109
+ * Check whether Beads is properly initialized in a project.
110
+ *
111
+ * Returns `true` only when all of the following are present:
112
+ * - `.beads/` directory exists
113
+ * - `.beads/config.yaml` exists and contains an `issue-prefix` key
114
+ * - `.beads/issues.jsonl` exists
115
+ *
116
+ * @param {string} projectRoot - Absolute path to the project root
117
+ * @returns {boolean} `true` if Beads is fully initialized
118
+ */
119
+ function isBeadsInitialized(projectRoot) {
120
+ const beadsDir = path.join(projectRoot, '.beads');
121
+ const configPath = path.join(beadsDir, 'config.yaml');
122
+ const jsonlPath = path.join(beadsDir, 'issues.jsonl');
123
+
124
+ if (!fs.existsSync(beadsDir)) return false;
125
+ if (!fs.existsSync(configPath)) return false;
126
+ if (!fs.existsSync(jsonlPath)) return false;
127
+
128
+ const configContent = fs.readFileSync(configPath, 'utf8');
129
+ if (!configContent.includes('issue-prefix:')) return false;
130
+
131
+ return true;
132
+ }
133
+
134
+ /**
135
+ * Ensure `issues.jsonl` exists inside `.beads/`.
136
+ *
137
+ * Creates the `.beads/` directory and an empty `issues.jsonl` if either
138
+ * is missing. Leaves an existing `issues.jsonl` untouched.
139
+ *
140
+ * @param {string} projectRoot - Absolute path to the project root
141
+ */
142
+ function preSeedJsonl(projectRoot) {
143
+ const beadsDir = path.join(projectRoot, '.beads');
144
+ fs.mkdirSync(beadsDir, { recursive: true });
145
+
146
+ const jsonlPath = path.join(beadsDir, 'issues.jsonl');
147
+ if (!fs.existsSync(jsonlPath)) {
148
+ fs.writeFileSync(jsonlPath, '', 'utf8');
149
+ }
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // Task 11: Defensive bd init wrapper
154
+ // ---------------------------------------------------------------------------
155
+
156
+ /**
157
+ * Snapshot all files in a directory — returns a Map of filename to content (Buffer).
158
+ * Returns an empty Map if the directory does not exist.
159
+ *
160
+ * @param {string} dirPath - Absolute path to the directory to snapshot
161
+ * @returns {Map<string, Buffer>} Map of filename to raw file contents
162
+ */
163
+ function snapshotDirectory(dirPath) {
164
+ const snapshot = new Map();
165
+
166
+ if (!fs.existsSync(dirPath)) {
167
+ return snapshot;
168
+ }
169
+
170
+ const entries = fs.readdirSync(dirPath);
171
+ for (const entry of entries) {
172
+ const fullPath = path.join(dirPath, entry);
173
+ try {
174
+ const stat = fs.statSync(fullPath);
175
+ if (stat.isFile()) {
176
+ snapshot.set(entry, fs.readFileSync(fullPath));
177
+ }
178
+ } catch (_err) {
179
+ // Expected: file may be locked or permission-denied — skip unreadable files during snapshot
180
+ }
181
+ }
182
+
183
+ return snapshot;
184
+ }
185
+
186
+ /**
187
+ * Restore a directory to exactly match a snapshot — overwrite changed files,
188
+ * remove files not in the snapshot, recreate deleted files.
189
+ *
190
+ * @param {string} dirPath - Absolute path to the directory to restore
191
+ * @param {Map<string, Buffer>} snapshot - Snapshot from snapshotDirectory()
192
+ */
193
+ function restoreDirectory(dirPath, snapshot) {
194
+ fs.mkdirSync(dirPath, { recursive: true });
195
+
196
+ // Remove files that were not in the original snapshot
197
+ const currentFiles = fs.readdirSync(dirPath);
198
+ for (const file of currentFiles) {
199
+ const fullPath = path.join(dirPath, file);
200
+ try {
201
+ if (fs.statSync(fullPath).isFile() && !snapshot.has(file)) {
202
+ fs.unlinkSync(fullPath);
203
+ }
204
+ } catch (_err) {
205
+ // Expected: file may be locked or already removed — skip files we cannot stat or remove during restore
206
+ }
207
+ }
208
+
209
+ // Write all files from the snapshot
210
+ for (const [name, content] of snapshot) {
211
+ fs.writeFileSync(path.join(dirPath, name), content, { mode: 0o755 });
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Default bd init executor — calls `execFileSync('bd', ['init'])`.
217
+ *
218
+ * @param {string} projectRoot - Absolute path to the project root
219
+ */
220
+ function defaultExecBdInit(projectRoot) {
221
+ const { execFileSync } = require('node:child_process');
222
+ execFileSync(resolveCommand('bd'), ['init'], {
223
+ cwd: projectRoot,
224
+ stdio: 'pipe'
225
+ });
226
+ }
227
+
228
+ /**
229
+ * Defensive wrapper for `bd init` — orchestrates Beads initialization
230
+ * with hook snapshot/restore to prevent bd from overwriting git hooks.
231
+ *
232
+ * Flow:
233
+ * a. Check if already initialized (idempotent skip)
234
+ * b. Write config.yaml with correct prefix
235
+ * c. Write .beads/.gitignore for Dolt files
236
+ * d. Snapshot .git/hooks/
237
+ * e. Run bd init (via execBdInit callback or default execFileSync)
238
+ * f. Restore .git/hooks/ from snapshot
239
+ * g. Restore lefthook hooks if callback provided
240
+ * h. Pre-seed issues.jsonl
241
+ *
242
+ * @param {string} projectRoot - Absolute path to the project root
243
+ * @param {Object} [options={}] - Configuration options
244
+ * @param {string} [options.prefix] - Issue prefix (repo name), sanitized before use
245
+ * @param {Function} [options.execBdInit] - Custom bd init executor. Receives (projectRoot).
246
+ * Defaults to calling execFileSync('bd', ['init']).
247
+ * @param {Function} [options.restoreLefthook] - Optional callback to restore lefthook hooks
248
+ * (e.g., running `npx lefthook install`). Non-fatal if it throws.
249
+ * @returns {{ success: boolean, skipped: boolean, reason?: string, warnings: string[], errors: string[] }}
250
+ */
251
+ function safeBeadsInit(projectRoot, options = {}) {
252
+ const warnings = [];
253
+ const errors = [];
254
+
255
+ // (a) Check if already initialized — idempotent skip
256
+ if (isBeadsInitialized(projectRoot)) {
257
+ return {
258
+ success: true,
259
+ skipped: true,
260
+ reason: 'already initialized',
261
+ warnings,
262
+ errors
263
+ };
264
+ }
265
+
266
+ // (b) Write config.yaml with correct prefix
267
+ const prefix = options.prefix || '';
268
+ try {
269
+ writeBeadsConfig(projectRoot, { prefix });
270
+ } catch (err) {
271
+ warnings.push(`Failed to write config.yaml: ${err.message}`);
272
+ }
273
+
274
+ // (c) Write .beads/.gitignore for Dolt files
275
+ try {
276
+ writeBeadsGitignore(projectRoot);
277
+ } catch (err) {
278
+ warnings.push(`Failed to write .beads/.gitignore: ${err.message}`);
279
+ }
280
+
281
+ // (d) Snapshot current .git/hooks/ directory
282
+ const hooksDir = path.join(projectRoot, '.git', 'hooks');
283
+ const hooksSnapshot = snapshotDirectory(hooksDir);
284
+
285
+ // (e) Run bd init — wrapped in try/catch
286
+ const execBdInit = options.execBdInit || defaultExecBdInit;
287
+ try {
288
+ execBdInit(projectRoot);
289
+ } catch (err) {
290
+ // Always restore hooks, even on failure
291
+ restoreDirectory(hooksDir, hooksSnapshot);
292
+
293
+ if (err.code === 'ENOENT') {
294
+ errors.push('bd CLI not installed');
295
+ } else {
296
+ errors.push(err.message);
297
+ }
298
+
299
+ return {
300
+ success: false,
301
+ skipped: false,
302
+ warnings,
303
+ errors
304
+ };
305
+ }
306
+
307
+ // (f) Restore .git/hooks/ from snapshot
308
+ restoreDirectory(hooksDir, hooksSnapshot);
309
+
310
+ // (g) Restore lefthook hooks if callback provided
311
+ if (typeof options.restoreLefthook === 'function') {
312
+ try {
313
+ options.restoreLefthook(projectRoot);
314
+ } catch (err) {
315
+ warnings.push(`Failed to restore lefthook hooks: ${err.message}`);
316
+ }
317
+ }
318
+
319
+ // (h) Pre-seed JSONL if empty
320
+ try {
321
+ preSeedJsonl(projectRoot);
322
+ } catch (err) {
323
+ warnings.push(`Failed to pre-seed issues.jsonl: ${err.message}`);
324
+ }
325
+
326
+ return {
327
+ success: true,
328
+ skipped: false,
329
+ warnings,
330
+ errors
331
+ };
332
+ }
333
+
334
+ module.exports = {
335
+ sanitizePrefix,
336
+ writeBeadsConfig,
337
+ writeBeadsGitignore,
338
+ isBeadsInitialized,
339
+ preSeedJsonl,
340
+ safeBeadsInit
341
+ };