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,571 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * @module sync-commands
5
+ *
6
+ * Utility for parsing and rebuilding YAML frontmatter in
7
+ * `.claude/commands/*.md` files.
8
+ *
9
+ * Exports:
10
+ * parseFrontmatter(content) -> { frontmatter: object, body: string }
11
+ * buildFile(frontmatter, body) -> string
12
+ */
13
+
14
+ const YAML = require('yaml');
15
+
16
+ /**
17
+ * Parse YAML frontmatter from a markdown string.
18
+ *
19
+ * Frontmatter is the YAML block between two `---` markers at the very start
20
+ * of the file. If no valid frontmatter block is found, returns an empty object
21
+ * with the full content as the body.
22
+ *
23
+ * @param {string} content - The raw file content
24
+ * @returns {{ frontmatter: Record<string, unknown>, body: string }}
25
+ */
26
+ function parseFrontmatter(content) {
27
+ // Frontmatter must start at the very beginning with ---
28
+ if (!content.startsWith('---\n') && !content.startsWith('---\r\n')) {
29
+ return { frontmatter: {}, body: content };
30
+ }
31
+
32
+ // Find the closing --- marker (skip the opening one)
33
+ const openLen = content.startsWith('---\r\n') ? 5 : 4; // '---\n' or '---\r\n'
34
+ const closeIndex = content.indexOf('\n---\n', openLen - 1);
35
+ const closeIndexCRLF = content.indexOf('\r\n---\r\n', openLen - 1);
36
+
37
+ let yamlStr;
38
+ let bodyStart;
39
+
40
+ if (closeIndex === -1 && closeIndexCRLF === -1) {
41
+ // Check for --- at end of file (no trailing newline after closing ---)
42
+ const closeAtEnd = content.indexOf('\n---', openLen - 1);
43
+ if (closeAtEnd !== -1 && closeAtEnd + 4 === content.length) {
44
+ yamlStr = content.slice(openLen, closeAtEnd + 1);
45
+ bodyStart = content.length;
46
+ } else {
47
+ // No closing --- found — no valid frontmatter
48
+ return { frontmatter: {}, body: content };
49
+ }
50
+ } else if (closeIndex !== -1 && (closeIndexCRLF === -1 || closeIndex < closeIndexCRLF)) {
51
+ // LF line endings
52
+ yamlStr = content.slice(openLen, closeIndex + 1);
53
+ bodyStart = closeIndex + 5; // skip '\n---\n'
54
+ } else {
55
+ // CRLF line endings
56
+ yamlStr = content.slice(openLen, closeIndexCRLF + 2);
57
+ bodyStart = closeIndexCRLF + 7; // skip '\r\n---\r\n'
58
+ }
59
+
60
+ // Parse the YAML string
61
+ const trimmed = yamlStr.trim();
62
+ if (trimmed === '') {
63
+ return { frontmatter: {}, body: content.slice(bodyStart) };
64
+ }
65
+
66
+ /** @type {Record<string, unknown>} */
67
+ let frontmatter;
68
+ try {
69
+ frontmatter = YAML.parse(trimmed);
70
+ } catch (_err) {
71
+ // If YAML parsing fails, treat as no frontmatter
72
+ return { frontmatter: {}, body: content };
73
+ }
74
+
75
+ // YAML.parse can return null for empty docs or a scalar for non-object input
76
+ if (frontmatter === null || typeof frontmatter !== 'object') {
77
+ return { frontmatter: {}, body: content };
78
+ }
79
+
80
+ return { frontmatter, body: content.slice(bodyStart) };
81
+ }
82
+
83
+ /**
84
+ * Build a file string from frontmatter and body.
85
+ *
86
+ * Produces output in the format:
87
+ * ```
88
+ * ---
89
+ * key: value
90
+ * ---
91
+ * body content
92
+ * ```
93
+ *
94
+ * @param {Record<string, unknown>} frontmatter - Key-value pairs for the YAML block
95
+ * @param {string} body - The markdown body content
96
+ * @returns {string} The reconstructed file content
97
+ */
98
+ function buildFile(frontmatter, body) {
99
+ const keys = Object.keys(frontmatter);
100
+
101
+ let yamlBlock;
102
+ if (keys.length === 0) {
103
+ yamlBlock = '';
104
+ } else {
105
+ yamlBlock = YAML.stringify(frontmatter, {
106
+ lineWidth: 0, // Prevent line wrapping
107
+ defaultKeyType: 'PLAIN',
108
+ defaultStringType: 'PLAIN',
109
+ }).trimEnd();
110
+ yamlBlock += '\n';
111
+ }
112
+
113
+ return `---\n${yamlBlock}---\n${body}`;
114
+ }
115
+
116
+ // ---- Agent adapters -------------------------------------------------------------
117
+
118
+ /**
119
+ * @typedef {Object} AgentAdapter
120
+ * @property {(commandName: string) => string} dir - Target directory path for a specific command
121
+ * @property {string} baseDir - Base output directory for this agent (no sentinel needed)
122
+ * @property {string} extension - File extension (e.g. '.md', '.prompt.md')
123
+ * @property {(fm: Record<string, unknown>, commandName: string) => Record<string, unknown>} transformFrontmatter
124
+ * @property {boolean} [skip] - If true, agent is canonical source (no sync needed)
125
+ */
126
+
127
+ /**
128
+ * Strip all frontmatter — return empty object.
129
+ *
130
+ * @param {Record<string, unknown>} _fm
131
+ * @param {string} _commandName
132
+ * @returns {Record<string, unknown>}
133
+ */
134
+ function stripAllFrontmatter(_fm, _commandName) {
135
+ return {};
136
+ }
137
+
138
+ /**
139
+ * Keep only `description` from frontmatter.
140
+ *
141
+ * @param {Record<string, unknown>} fm
142
+ * @param {string} _commandName
143
+ * @returns {Record<string, unknown>}
144
+ */
145
+ function keepDescription(fm, _commandName) {
146
+ /** @type {Record<string, unknown>} */
147
+ const result = {};
148
+ if (fm.description !== undefined) {
149
+ result.description = fm.description;
150
+ }
151
+ return result;
152
+ }
153
+
154
+ /**
155
+ * Keep `description`, add `mode: code`.
156
+ *
157
+ * @param {Record<string, unknown>} fm
158
+ * @param {string} _commandName
159
+ * @returns {Record<string, unknown>}
160
+ */
161
+ function keepDescriptionAddMode(fm, _commandName) {
162
+ /** @type {Record<string, unknown>} */
163
+ const result = {};
164
+ if (fm.description !== undefined) {
165
+ result.description = fm.description;
166
+ }
167
+ result.mode = 'code';
168
+ return result;
169
+ }
170
+
171
+ /**
172
+ * GitHub Copilot transform: add `name`, keep `description`, add `tools`.
173
+ *
174
+ * @param {Record<string, unknown>} fm
175
+ * @param {string} commandName
176
+ * @returns {Record<string, unknown>}
177
+ */
178
+ function copilotTransform(fm, commandName) {
179
+ /** @type {Record<string, unknown>} */
180
+ const result = {};
181
+ result.name = commandName;
182
+ if (fm.description !== undefined) {
183
+ result.description = fm.description;
184
+ }
185
+ result.tools = Array.isArray(fm.tools) ? fm.tools : [];
186
+ return result;
187
+ }
188
+
189
+ /**
190
+ * Agent adapter configuration for command sync.
191
+ *
192
+ * Each entry maps an agent slug to its target directory, file extension,
193
+ * and frontmatter transform function.
194
+ *
195
+ * @type {Record<string, AgentAdapter>}
196
+ */
197
+ const AGENT_ADAPTERS = {
198
+ 'claude-code': {
199
+ dir: () => '.claude/commands/',
200
+ baseDir: '.claude/commands/',
201
+ extension: '.md',
202
+ transformFrontmatter: (fm) => ({ ...fm }),
203
+ skip: true,
204
+ },
205
+ cursor: {
206
+ dir: () => '.cursor/commands/',
207
+ baseDir: '.cursor/commands/',
208
+ extension: '.md',
209
+ transformFrontmatter: stripAllFrontmatter,
210
+ },
211
+ cline: {
212
+ dir: () => '.cline/workflows/',
213
+ baseDir: '.cline/workflows/',
214
+ extension: '.md',
215
+ transformFrontmatter: stripAllFrontmatter,
216
+ },
217
+ opencode: {
218
+ dir: () => '.opencode/commands/',
219
+ baseDir: '.opencode/commands/',
220
+ extension: '.md',
221
+ transformFrontmatter: keepDescription,
222
+ },
223
+ 'github-copilot': {
224
+ dir: () => '.github/prompts/',
225
+ baseDir: '.github/prompts/',
226
+ extension: '.prompt.md',
227
+ transformFrontmatter: copilotTransform,
228
+ },
229
+ 'kilo-code': {
230
+ dir: () => '.kilocode/workflows/',
231
+ baseDir: '.kilocode/workflows/',
232
+ extension: '.md',
233
+ transformFrontmatter: keepDescriptionAddMode,
234
+ },
235
+ 'roo-code': {
236
+ dir: () => '.roo/commands/',
237
+ baseDir: '.roo/commands/',
238
+ extension: '.md',
239
+ transformFrontmatter: keepDescriptionAddMode,
240
+ },
241
+ codex: {
242
+ dir: (commandName) => `.codex/skills/${commandName}/`,
243
+ baseDir: '.codex/skills/',
244
+ extension: '.md',
245
+ transformFrontmatter: keepDescription,
246
+ },
247
+ };
248
+
249
+ /**
250
+ * Adapt a command file for a specific agent.
251
+ *
252
+ * Applies the agent's frontmatter transform and returns the target
253
+ * filename, directory, and rebuilt file content.
254
+ *
255
+ * @param {string} agentName - Agent slug (e.g. 'cursor', 'claude-code')
256
+ * @param {Record<string, unknown>} frontmatter - Parsed frontmatter object
257
+ * @param {string} body - Markdown body content (after frontmatter)
258
+ * @param {string} commandName - Command name (e.g. 'plan', 'dev', 'status')
259
+ * @returns {{ content: string, filename: string, dir: string } | null}
260
+ * null if the agent is skipped (canonical source)
261
+ * @throws {Error} If agentName is not a known agent
262
+ */
263
+ function adaptForAgent(agentName, frontmatter, body, commandName) {
264
+ const adapter = AGENT_ADAPTERS[agentName];
265
+ if (!adapter) {
266
+ throw new Error(`Unknown agent: "${agentName}". Known agents: ${Object.keys(AGENT_ADAPTERS).join(', ')}`);
267
+ }
268
+
269
+ if (adapter.skip) {
270
+ return null;
271
+ }
272
+
273
+ const transformed = adapter.transformFrontmatter(frontmatter, commandName);
274
+ const hasKeys = Object.keys(transformed).length > 0;
275
+
276
+ // Build content: if frontmatter is empty, output body only (no --- markers)
277
+ const content = hasKeys ? buildFile(transformed, body) : body;
278
+
279
+ // Determine filename — Codex uses SKILL.md, others use <commandName>.<ext>
280
+ let filename;
281
+ if (agentName === 'codex') {
282
+ filename = `SKILL${adapter.extension}`;
283
+ } else {
284
+ filename = `${commandName}${adapter.extension}`;
285
+ }
286
+
287
+ return {
288
+ content,
289
+ filename,
290
+ dir: adapter.dir(commandName),
291
+ };
292
+ }
293
+
294
+ // ---- Sync logic -----------------------------------------------------------------
295
+
296
+ const fs = require('fs');
297
+ const path = require('path');
298
+ const crypto = require('crypto');
299
+
300
+ /**
301
+ * Compute a content hash for change detection.
302
+ * Normalizes line endings to LF before hashing to avoid CRLF/LF mismatches
303
+ * on Windows (git checkout converts LF to CRLF on Windows).
304
+ *
305
+ * @param {string} content
306
+ * @returns {string} hex digest
307
+ */
308
+ function contentHash(content) {
309
+ const normalized = content.replace(/\r\n/g, '\n');
310
+ return crypto.createHash('sha256').update(normalized).digest('hex');
311
+ }
312
+
313
+ /**
314
+ * @typedef {Object} SyncEntry
315
+ * @property {string} agent - Agent slug
316
+ * @property {string} dir - Relative directory path
317
+ * @property {string} filename - Output filename
318
+ * @property {string} content - Generated file content
319
+ * @property {string} filePath - Full absolute path to the output file
320
+ */
321
+
322
+ /**
323
+ * @typedef {Object} SyncResult
324
+ * @property {SyncEntry[]} [planned] - (dry-run) entries that would be written
325
+ * @property {SyncEntry[]} [written] - (write mode) entries that were written
326
+ * @property {SyncEntry[]} [overwritten] - (write mode) entries that overwrote manually modified files
327
+ * @property {boolean} [inSync] - (check mode) whether all files match
328
+ * @property {SyncEntry[]} [outOfSync] - (check mode) entries that differ from expected
329
+ * @property {string[]} [staleFiles] - (check mode) files on disk that are no longer generated
330
+ * @property {boolean} [empty] - (check mode) true when no commands found in canonical source
331
+ * @property {boolean} [manifestMissing] - (check mode) true when sync manifest not found
332
+ */
333
+
334
+ /**
335
+ * Sync .claude/commands/*.md files to all non-skip agent directories.
336
+ *
337
+ * Modes:
338
+ * - `dryRun: true` — returns planned writes without touching the filesystem
339
+ * - `check: true` — compares generated content with existing files, reports mismatches
340
+ * - default (both false) — writes files, creating directories as needed
341
+ *
342
+ * @param {{ dryRun: boolean, check: boolean, repoRoot: string }} options
343
+ * @returns {SyncResult}
344
+ */
345
+ function syncCommands({ dryRun, check, repoRoot }) {
346
+ const commandsDir = path.join(repoRoot, '.claude', 'commands');
347
+
348
+ // Read all .md files from the commands directory
349
+ /** @type {string[]} */
350
+ let commandFiles = [];
351
+ if (fs.existsSync(commandsDir)) {
352
+ commandFiles = fs.readdirSync(commandsDir)
353
+ .filter((f) => f.endsWith('.md'))
354
+ .sort();
355
+ }
356
+
357
+ // Build the list of all files to generate
358
+ /** @type {SyncEntry[]} */
359
+ const entries = [];
360
+
361
+ for (const file of commandFiles) {
362
+ const commandName = file.replace(/\.md$/, '');
363
+ const filePath = path.join(commandsDir, file);
364
+ const raw = fs.readFileSync(filePath, 'utf8');
365
+ const { frontmatter, body } = parseFrontmatter(raw);
366
+
367
+ for (const agentName of Object.keys(AGENT_ADAPTERS)) {
368
+ const adapted = adaptForAgent(agentName, frontmatter, body, commandName);
369
+ if (adapted === null) {
370
+ continue; // skip canonical agent
371
+ }
372
+
373
+ const targetDir = path.join(repoRoot, adapted.dir);
374
+ const targetPath = path.join(targetDir, adapted.filename);
375
+
376
+ entries.push({
377
+ agent: agentName,
378
+ dir: adapted.dir,
379
+ filename: adapted.filename,
380
+ content: adapted.content,
381
+ filePath: targetPath,
382
+ });
383
+ }
384
+ }
385
+
386
+ // ---- dry-run mode ----
387
+ if (dryRun) {
388
+ return { planned: entries };
389
+ }
390
+
391
+ // ---- check mode ----
392
+ if (check) {
393
+ // Warn when no commands exist (could mask a misconfigured path)
394
+ if (commandFiles.length === 0) {
395
+ return { inSync: false, outOfSync: [], empty: true };
396
+ }
397
+
398
+ /** @type {SyncEntry[]} */
399
+ const outOfSync = [];
400
+
401
+ for (const entry of entries) {
402
+ if (!fs.existsSync(entry.filePath)) {
403
+ outOfSync.push(entry);
404
+ continue;
405
+ }
406
+ const existing = fs.readFileSync(entry.filePath, 'utf8');
407
+ if (contentHash(existing) !== contentHash(entry.content)) {
408
+ outOfSync.push(entry);
409
+ }
410
+ }
411
+
412
+ // Detect stale files using the sync manifest (.forge/sync-manifest.json).
413
+ // The manifest records every file path the sync script generated on the last
414
+ // write run. Stale = in manifest but NOT in current expected set.
415
+ // This avoids false positives on custom files — only files sync created are tracked.
416
+ const expectedPaths = new Set(entries.map((e) => e.filePath));
417
+ /** @type {string[]} */
418
+ const staleFiles = [];
419
+
420
+ const manifestPath = path.join(repoRoot, '.forge', 'sync-manifest.json');
421
+ let manifestMissing = !fs.existsSync(manifestPath);
422
+ if (!manifestMissing) {
423
+ try {
424
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
425
+ const previousPaths = manifest.files || [];
426
+ for (const prevPath of previousPaths) {
427
+ const absPath = path.resolve(repoRoot, prevPath);
428
+ if (!expectedPaths.has(absPath) && fs.existsSync(absPath)) {
429
+ staleFiles.push(absPath);
430
+ }
431
+ }
432
+ } catch (_err) {
433
+ // Corrupt manifest — flag as missing so CLI warns
434
+ manifestMissing = true;
435
+ }
436
+ }
437
+
438
+ return {
439
+ inSync: manifestMissing ? false : outOfSync.length === 0 && staleFiles.length === 0,
440
+ outOfSync,
441
+ staleFiles,
442
+ manifestMissing,
443
+ };
444
+ }
445
+
446
+ // ---- write mode (default) ----
447
+
448
+ // Note: .clinerules flat-file migration was removed — Cline workflows
449
+ // now go to .cline/workflows/, so .clinerules stays as Cline's root config file.
450
+
451
+ /** @type {SyncEntry[]} */
452
+ const written = [];
453
+ /** @type {SyncEntry[]} */
454
+ const overwritten = [];
455
+
456
+ for (const entry of entries) {
457
+ const targetDir = path.dirname(entry.filePath);
458
+
459
+ // Check if existing file has been manually modified
460
+ if (fs.existsSync(entry.filePath)) {
461
+ const existing = fs.readFileSync(entry.filePath, 'utf8');
462
+ if (contentHash(existing) !== contentHash(entry.content)) {
463
+ overwritten.push(entry);
464
+ }
465
+ }
466
+
467
+ // Create directory if needed
468
+ fs.mkdirSync(targetDir, { recursive: true });
469
+
470
+ // Write the file
471
+ fs.writeFileSync(entry.filePath, entry.content);
472
+ written.push(entry);
473
+ }
474
+
475
+ // Write sync manifest — records every file generated so stale detection
476
+ // can identify orphaned files without false-flagging custom files.
477
+ const manifestDir = path.join(repoRoot, '.forge');
478
+ fs.mkdirSync(manifestDir, { recursive: true });
479
+ const manifestData = {
480
+ generatedAt: new Date().toISOString(),
481
+ files: written.map((e) => path.relative(repoRoot, e.filePath).replace(/\\/g, '/')),
482
+ };
483
+ fs.writeFileSync(
484
+ path.join(manifestDir, 'sync-manifest.json'),
485
+ JSON.stringify(manifestData, null, 2) + '\n'
486
+ );
487
+
488
+ return { written, overwritten };
489
+ }
490
+
491
+ // ---- CLI entry point -------------------------------------------------------------
492
+
493
+ if (require.main === module) {
494
+ const args = process.argv.slice(2);
495
+ const dryRun = args.includes('--dry-run');
496
+ const check = args.includes('--check');
497
+
498
+ if (dryRun && check) {
499
+ console.error('Error: --dry-run and --check cannot be used together.');
500
+ process.exit(1);
501
+ }
502
+
503
+ const repoRoot = path.resolve(__dirname, '..');
504
+
505
+ const result = syncCommands({ dryRun, check, repoRoot });
506
+
507
+ if (dryRun) {
508
+ if (result.planned.length === 0) {
509
+ console.log('No command files found in .claude/commands/');
510
+ } else {
511
+ console.log('Dry run — files that would be generated:\n');
512
+ for (const entry of result.planned) {
513
+ console.log(` [${entry.agent}] ${path.join(entry.dir, entry.filename)}`);
514
+ }
515
+ console.log(`\nTotal: ${result.planned.length} files`);
516
+ }
517
+ } else if (check) {
518
+ if (result.empty) {
519
+ console.error('Error: no command files found in .claude/commands/ — cannot verify sync.');
520
+ process.exit(1);
521
+ }
522
+ if (result.manifestMissing) {
523
+ console.warn('Warning: .forge/sync-manifest.json not found — stale file detection skipped.');
524
+ console.warn('Run "node scripts/sync-commands.js" to generate the manifest.\n');
525
+ }
526
+ if (result.inSync) {
527
+ console.log('All agent command files are in sync.');
528
+ process.exit(0);
529
+ } else if (result.manifestMissing && result.outOfSync.length === 0) {
530
+ // Files are content-sync'd but manifest is missing — not a content error,
531
+ // just needs a write run to generate the manifest.
532
+ console.error('Run "node scripts/sync-commands.js" to generate the manifest, then commit .forge/sync-manifest.json.');
533
+ process.exit(1);
534
+ } else {
535
+ if (result.outOfSync.length > 0) {
536
+ console.log('Out of sync — the following files differ from expected:\n');
537
+ for (const entry of result.outOfSync) {
538
+ const exists = fs.existsSync(entry.filePath);
539
+ const status = exists ? 'modified' : 'missing';
540
+ console.log(` [${entry.agent}] ${path.join(entry.dir, entry.filename)} (${status})`);
541
+ }
542
+ }
543
+ if (result.staleFiles && result.staleFiles.length > 0) {
544
+ console.log('\nStale files (no longer generated, should be removed):\n');
545
+ for (const f of result.staleFiles) {
546
+ console.log(` ${path.relative(repoRoot, f)}`);
547
+ }
548
+ }
549
+ const total = result.outOfSync.length + (result.staleFiles ? result.staleFiles.length : 0);
550
+ console.log(`\n${total} issue(s) found.`);
551
+ process.exit(1);
552
+ }
553
+ } else {
554
+ // Write mode
555
+ if (result.overwritten.length > 0) {
556
+ console.log('Warning — overwriting manually modified files:\n');
557
+ for (const entry of result.overwritten) {
558
+ console.log(` [${entry.agent}] ${path.join(entry.dir, entry.filename)}`);
559
+ }
560
+ console.log('');
561
+ }
562
+
563
+ if (result.written.length === 0) {
564
+ console.log('No command files found in .claude/commands/');
565
+ } else {
566
+ console.log(`Synced ${result.written.length} file(s) across agents.`);
567
+ }
568
+ }
569
+ }
570
+
571
+ module.exports = { parseFrontmatter, buildFile, AGENT_ADAPTERS, adaptForAgent, syncCommands };