@lumenflow/cli 2.4.0 → 2.5.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 (147) hide show
  1. package/README.md +11 -8
  2. package/dist/__tests__/init-config-lanes.test.js +131 -0
  3. package/dist/__tests__/init-docs-structure.test.js +119 -0
  4. package/dist/__tests__/init-lane-inference.test.js +125 -0
  5. package/dist/__tests__/init-onboarding-docs.test.js +132 -0
  6. package/dist/__tests__/init-quick-ref.test.js +145 -0
  7. package/dist/__tests__/init-scripts.test.js +207 -0
  8. package/dist/__tests__/init-template-portability.test.js +97 -0
  9. package/dist/__tests__/init.test.js +7 -2
  10. package/dist/__tests__/initiative-add-wu.test.js +420 -0
  11. package/dist/__tests__/initiative-plan-replacement.test.js +162 -0
  12. package/dist/__tests__/initiative-remove-wu.test.js +458 -0
  13. package/dist/__tests__/onboarding-smoke-test.test.js +211 -0
  14. package/dist/__tests__/path-centralization-cli.test.js +234 -0
  15. package/dist/__tests__/plan-create.test.js +126 -0
  16. package/dist/__tests__/plan-edit.test.js +157 -0
  17. package/dist/__tests__/plan-link.test.js +239 -0
  18. package/dist/__tests__/plan-promote.test.js +181 -0
  19. package/dist/__tests__/templates-sync.test.js +219 -0
  20. package/dist/__tests__/wu-create-strict.test.js +118 -0
  21. package/dist/__tests__/wu-edit-strict.test.js +109 -0
  22. package/dist/__tests__/wu-validate-strict.test.js +113 -0
  23. package/dist/flow-bottlenecks.js +4 -2
  24. package/dist/gates.js +22 -0
  25. package/dist/init.js +670 -87
  26. package/dist/initiative-add-wu.js +112 -16
  27. package/dist/initiative-remove-wu.js +248 -0
  28. package/dist/onboarding-smoke-test.js +400 -0
  29. package/dist/orchestrate-init-status.js +37 -9
  30. package/dist/orchestrate-initiative.js +10 -4
  31. package/dist/plan-create.js +199 -0
  32. package/dist/plan-edit.js +235 -0
  33. package/dist/plan-link.js +233 -0
  34. package/dist/plan-promote.js +231 -0
  35. package/dist/sync-templates.js +137 -5
  36. package/dist/wu-block.js +16 -5
  37. package/dist/wu-claim.js +15 -9
  38. package/dist/wu-create.js +50 -2
  39. package/dist/wu-deps.js +3 -1
  40. package/dist/wu-done.js +14 -5
  41. package/dist/wu-edit.js +35 -0
  42. package/dist/wu-prep.js +131 -8
  43. package/dist/wu-spawn.js +14 -1
  44. package/dist/wu-unblock.js +34 -2
  45. package/dist/wu-validate.js +25 -17
  46. package/package.json +11 -7
  47. package/templates/core/.lumenflow/constraints.md.template +61 -3
  48. package/templates/core/AGENTS.md.template +2 -2
  49. package/templates/core/LUMENFLOW.md.template +85 -23
  50. package/templates/core/ai/onboarding/agent-invocation-guide.md.template +157 -0
  51. package/templates/core/ai/onboarding/agent-safety-card.md.template +227 -0
  52. package/templates/core/ai/onboarding/docs-generation.md.template +277 -0
  53. package/templates/core/ai/onboarding/first-wu-mistakes.md.template +49 -7
  54. package/templates/core/ai/onboarding/quick-ref-commands.md.template +343 -110
  55. package/templates/core/ai/onboarding/release-process.md.template +8 -2
  56. package/templates/core/ai/onboarding/starting-prompt.md.template +407 -0
  57. package/templates/core/ai/onboarding/test-ratchet.md.template +131 -0
  58. package/templates/core/ai/onboarding/troubleshooting-wu-done.md.template +91 -38
  59. package/templates/core/ai/onboarding/vendor-support.md.template +219 -0
  60. package/templates/vendors/claude/.claude/skills/context-management/SKILL.md.template +13 -1
  61. package/templates/vendors/claude/.claude/skills/execution-memory/SKILL.md.template +14 -16
  62. package/templates/vendors/claude/.claude/skills/orchestration/SKILL.md.template +48 -4
  63. package/templates/vendors/claude/.claude/skills/worktree-discipline/SKILL.md.template +5 -1
  64. package/templates/vendors/claude/.claude/skills/wu-lifecycle/SKILL.md.template +19 -8
  65. package/dist/__tests__/init-plan.test.js +0 -340
  66. package/dist/agent-issues-query.d.ts +0 -16
  67. package/dist/agent-log-issue.d.ts +0 -10
  68. package/dist/agent-session-end.d.ts +0 -10
  69. package/dist/agent-session.d.ts +0 -10
  70. package/dist/backlog-prune.d.ts +0 -84
  71. package/dist/cli-entry-point.d.ts +0 -8
  72. package/dist/deps-add.d.ts +0 -91
  73. package/dist/deps-remove.d.ts +0 -17
  74. package/dist/docs-sync.d.ts +0 -50
  75. package/dist/file-delete.d.ts +0 -84
  76. package/dist/file-edit.d.ts +0 -82
  77. package/dist/file-read.d.ts +0 -92
  78. package/dist/file-write.d.ts +0 -90
  79. package/dist/flow-bottlenecks.d.ts +0 -16
  80. package/dist/flow-report.d.ts +0 -16
  81. package/dist/gates.d.ts +0 -94
  82. package/dist/git-branch.d.ts +0 -65
  83. package/dist/git-diff.d.ts +0 -58
  84. package/dist/git-log.d.ts +0 -69
  85. package/dist/git-status.d.ts +0 -58
  86. package/dist/guard-locked.d.ts +0 -62
  87. package/dist/guard-main-branch.d.ts +0 -50
  88. package/dist/guard-worktree-commit.d.ts +0 -59
  89. package/dist/index.d.ts +0 -10
  90. package/dist/init-plan.d.ts +0 -80
  91. package/dist/init-plan.js +0 -337
  92. package/dist/init.d.ts +0 -46
  93. package/dist/initiative-add-wu.d.ts +0 -22
  94. package/dist/initiative-bulk-assign-wus.d.ts +0 -16
  95. package/dist/initiative-create.d.ts +0 -28
  96. package/dist/initiative-edit.d.ts +0 -34
  97. package/dist/initiative-list.d.ts +0 -12
  98. package/dist/initiative-status.d.ts +0 -11
  99. package/dist/lumenflow-upgrade.d.ts +0 -103
  100. package/dist/mem-checkpoint.d.ts +0 -16
  101. package/dist/mem-cleanup.d.ts +0 -29
  102. package/dist/mem-create.d.ts +0 -17
  103. package/dist/mem-export.d.ts +0 -10
  104. package/dist/mem-inbox.d.ts +0 -35
  105. package/dist/mem-init.d.ts +0 -15
  106. package/dist/mem-ready.d.ts +0 -16
  107. package/dist/mem-signal.d.ts +0 -16
  108. package/dist/mem-start.d.ts +0 -16
  109. package/dist/mem-summarize.d.ts +0 -22
  110. package/dist/mem-triage.d.ts +0 -22
  111. package/dist/metrics-cli.d.ts +0 -90
  112. package/dist/metrics-snapshot.d.ts +0 -18
  113. package/dist/orchestrate-init-status.d.ts +0 -11
  114. package/dist/orchestrate-initiative.d.ts +0 -12
  115. package/dist/orchestrate-monitor.d.ts +0 -11
  116. package/dist/release.d.ts +0 -117
  117. package/dist/rotate-progress.d.ts +0 -48
  118. package/dist/session-coordinator.d.ts +0 -74
  119. package/dist/spawn-list.d.ts +0 -16
  120. package/dist/state-bootstrap.d.ts +0 -92
  121. package/dist/sync-templates.d.ts +0 -52
  122. package/dist/trace-gen.d.ts +0 -84
  123. package/dist/validate-agent-skills.d.ts +0 -50
  124. package/dist/validate-agent-sync.d.ts +0 -36
  125. package/dist/validate-backlog-sync.d.ts +0 -37
  126. package/dist/validate-skills-spec.d.ts +0 -40
  127. package/dist/validate.d.ts +0 -60
  128. package/dist/wu-block.d.ts +0 -16
  129. package/dist/wu-claim.d.ts +0 -74
  130. package/dist/wu-cleanup.d.ts +0 -35
  131. package/dist/wu-create.d.ts +0 -69
  132. package/dist/wu-delete.d.ts +0 -21
  133. package/dist/wu-deps.d.ts +0 -13
  134. package/dist/wu-done.d.ts +0 -225
  135. package/dist/wu-edit.d.ts +0 -63
  136. package/dist/wu-infer-lane.d.ts +0 -17
  137. package/dist/wu-preflight.d.ts +0 -47
  138. package/dist/wu-prune.d.ts +0 -16
  139. package/dist/wu-recover.d.ts +0 -37
  140. package/dist/wu-release.d.ts +0 -19
  141. package/dist/wu-repair.d.ts +0 -60
  142. package/dist/wu-spawn-completion.d.ts +0 -10
  143. package/dist/wu-spawn.d.ts +0 -192
  144. package/dist/wu-status.d.ts +0 -25
  145. package/dist/wu-unblock.d.ts +0 -16
  146. package/dist/wu-unlock-lane.d.ts +0 -19
  147. package/dist/wu-validate.d.ts +0 -16
@@ -0,0 +1,420 @@
1
+ /**
2
+ * Tests for initiative:add-wu command validation (WU-1330)
3
+ *
4
+ * The initiative:add-wu command now validates WU specs before linking.
5
+ * This ensures only valid, complete WUs can be linked to initiatives.
6
+ *
7
+ * TDD: These tests are written BEFORE the implementation.
8
+ */
9
+ import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';
10
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { tmpdir } from 'node:os';
13
+ import { stringifyYAML } from '@lumenflow/core/dist/wu-yaml.js';
14
+ // Test constants to avoid lint warnings about duplicate strings
15
+ const TEST_WU_ID = 'WU-123';
16
+ const TEST_INIT_ID = 'INIT-001';
17
+ const TEST_LANE = 'Framework: CLI';
18
+ const WU_REL_PATH = 'docs/04-operations/tasks/wu';
19
+ const INIT_REL_PATH = 'docs/04-operations/tasks/initiatives';
20
+ const TEST_INIT_SLUG = 'test-initiative';
21
+ const TEST_INIT_TITLE = 'Test Initiative';
22
+ const TEST_INIT_STATUS = 'open';
23
+ const TEST_DATE = '2026-01-25';
24
+ const MIN_DESCRIPTION_LENGTH = 50;
25
+ // Valid WU document template
26
+ const createValidWUDoc = (overrides = {}) => ({
27
+ id: TEST_WU_ID,
28
+ title: 'Test Work Unit Title',
29
+ lane: TEST_LANE,
30
+ status: 'ready',
31
+ type: 'feature',
32
+ priority: 'P2',
33
+ created: TEST_DATE,
34
+ description: 'Context: Testing WU validation. Problem: No validation on add-wu. Solution: Add strict validation before linking.',
35
+ acceptance: ['WU validates schema', 'Invalid WUs rejected', 'Valid WUs linked bidirectionally'],
36
+ code_paths: ['packages/@lumenflow/cli/src/initiative-add-wu.ts'],
37
+ tests: { unit: ['packages/@lumenflow/cli/src/__tests__/initiative-add-wu.test.ts'] },
38
+ exposure: 'backend-only',
39
+ ...overrides,
40
+ });
41
+ // Valid initiative document template
42
+ const createValidInitDoc = (overrides = {}) => ({
43
+ id: TEST_INIT_ID,
44
+ slug: TEST_INIT_SLUG,
45
+ title: TEST_INIT_TITLE,
46
+ status: TEST_INIT_STATUS,
47
+ created: TEST_DATE,
48
+ wus: [],
49
+ ...overrides,
50
+ });
51
+ // Pre-import the module to ensure coverage tracking includes the module itself
52
+ beforeAll(async () => {
53
+ await import('../initiative-add-wu.js');
54
+ });
55
+ // Mock modules before importing the module under test
56
+ const mockGit = {
57
+ branch: vi.fn().mockResolvedValue({ current: 'main' }),
58
+ status: vi.fn().mockResolvedValue({ isClean: () => true }),
59
+ };
60
+ vi.mock('@lumenflow/core/dist/git-adapter.js', () => ({
61
+ getGitForCwd: vi.fn(() => mockGit),
62
+ }));
63
+ vi.mock('@lumenflow/core/dist/wu-helpers.js', () => ({
64
+ ensureOnMain: vi.fn().mockResolvedValue(undefined),
65
+ }));
66
+ vi.mock('@lumenflow/core/dist/micro-worktree.js', async (importOriginal) => {
67
+ const actual = await importOriginal();
68
+ return {
69
+ ...actual,
70
+ withMicroWorktree: vi.fn(async ({ execute }) => {
71
+ // Simulate micro-worktree by executing in temp dir
72
+ const tempDir = join(tmpdir(), `init-add-wu-test-${Date.now()}`);
73
+ mkdirSync(tempDir, { recursive: true });
74
+ try {
75
+ await execute({ worktreePath: tempDir });
76
+ }
77
+ finally {
78
+ // Cleanup handled by test
79
+ }
80
+ }),
81
+ };
82
+ });
83
+ describe('initiative:add-wu WU validation (WU-1330)', () => {
84
+ let tempDir;
85
+ let originalCwd;
86
+ beforeEach(() => {
87
+ tempDir = join(tmpdir(), `init-add-wu-validation-test-${Date.now()}`);
88
+ mkdirSync(tempDir, { recursive: true });
89
+ originalCwd = process.cwd();
90
+ });
91
+ afterEach(() => {
92
+ process.chdir(originalCwd);
93
+ if (existsSync(tempDir)) {
94
+ rmSync(tempDir, { recursive: true, force: true });
95
+ }
96
+ vi.clearAllMocks();
97
+ });
98
+ describe('validateWUForLinking', () => {
99
+ it('should return valid for a well-formed WU', async () => {
100
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
101
+ // Create a valid WU file
102
+ const wuDir = join(tempDir, WU_REL_PATH);
103
+ mkdirSync(wuDir, { recursive: true });
104
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
105
+ writeFileSync(wuPath, stringifyYAML(createValidWUDoc()));
106
+ process.chdir(tempDir);
107
+ const result = validateWUForLinking(TEST_WU_ID);
108
+ expect(result.valid).toBe(true);
109
+ expect(result.errors).toHaveLength(0);
110
+ });
111
+ it('should reject WU with missing required fields', async () => {
112
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
113
+ // Create a WU missing required fields (no description)
114
+ const wuDir = join(tempDir, WU_REL_PATH);
115
+ mkdirSync(wuDir, { recursive: true });
116
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
117
+ writeFileSync(wuPath, stringifyYAML({
118
+ id: TEST_WU_ID,
119
+ title: 'Test',
120
+ lane: TEST_LANE,
121
+ status: 'ready',
122
+ created: TEST_DATE,
123
+ // Missing: description, acceptance, code_paths
124
+ }));
125
+ process.chdir(tempDir);
126
+ const result = validateWUForLinking(TEST_WU_ID);
127
+ expect(result.valid).toBe(false);
128
+ expect(result.errors.length).toBeGreaterThan(0);
129
+ expect(result.errors.some((e) => e.toLowerCase().includes('description'))).toBe(true);
130
+ });
131
+ it('should reject WU with invalid schema', async () => {
132
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
133
+ // Create a WU with invalid status
134
+ const wuDir = join(tempDir, WU_REL_PATH);
135
+ mkdirSync(wuDir, { recursive: true });
136
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
137
+ writeFileSync(wuPath, stringifyYAML({
138
+ ...createValidWUDoc(),
139
+ status: 'invalid_status', // Invalid status value
140
+ }));
141
+ process.chdir(tempDir);
142
+ const result = validateWUForLinking(TEST_WU_ID);
143
+ expect(result.valid).toBe(false);
144
+ expect(result.errors.some((e) => e.toLowerCase().includes('status'))).toBe(true);
145
+ });
146
+ it('should reject WU with description containing placeholder marker', async () => {
147
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
148
+ // Create a WU with placeholder in description
149
+ const wuDir = join(tempDir, WU_REL_PATH);
150
+ mkdirSync(wuDir, { recursive: true });
151
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
152
+ writeFileSync(wuPath, stringifyYAML({
153
+ ...createValidWUDoc(),
154
+ description: '[PLACEHOLDER] This is a placeholder description that is long enough.',
155
+ }));
156
+ process.chdir(tempDir);
157
+ const result = validateWUForLinking(TEST_WU_ID);
158
+ expect(result.valid).toBe(false);
159
+ expect(result.errors.some((e) => e.includes('PLACEHOLDER'))).toBe(true);
160
+ });
161
+ it('should reject WU with too short description', async () => {
162
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
163
+ // Create a WU with short description
164
+ const wuDir = join(tempDir, WU_REL_PATH);
165
+ mkdirSync(wuDir, { recursive: true });
166
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
167
+ writeFileSync(wuPath, stringifyYAML({
168
+ ...createValidWUDoc(),
169
+ description: 'Too short', // Less than MIN_DESCRIPTION_LENGTH
170
+ }));
171
+ process.chdir(tempDir);
172
+ const result = validateWUForLinking(TEST_WU_ID);
173
+ expect(result.valid).toBe(false);
174
+ expect(result.errors.some((e) => e.includes(`${MIN_DESCRIPTION_LENGTH}`))).toBe(true);
175
+ });
176
+ it('should reject WU with invalid ID format', async () => {
177
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
178
+ // Create a WU with invalid ID
179
+ const invalidId = 'INVALID-123';
180
+ const wuDir = join(tempDir, WU_REL_PATH);
181
+ mkdirSync(wuDir, { recursive: true });
182
+ const wuPath = join(wuDir, `${invalidId}.yaml`);
183
+ writeFileSync(wuPath, stringifyYAML({
184
+ ...createValidWUDoc(),
185
+ id: invalidId,
186
+ }));
187
+ process.chdir(tempDir);
188
+ const result = validateWUForLinking(invalidId);
189
+ expect(result.valid).toBe(false);
190
+ expect(result.errors.some((e) => e.toLowerCase().includes('id'))).toBe(true);
191
+ });
192
+ it('should reject WU that does not exist', async () => {
193
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
194
+ process.chdir(tempDir);
195
+ const result = validateWUForLinking('WU-999');
196
+ expect(result.valid).toBe(false);
197
+ expect(result.errors.some((e) => e.toLowerCase().includes('not found'))).toBe(true);
198
+ });
199
+ it('should reject WU with empty acceptance criteria', async () => {
200
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
201
+ // Create a WU with empty acceptance
202
+ const wuDir = join(tempDir, WU_REL_PATH);
203
+ mkdirSync(wuDir, { recursive: true });
204
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
205
+ writeFileSync(wuPath, stringifyYAML({
206
+ ...createValidWUDoc(),
207
+ acceptance: [], // Empty array
208
+ }));
209
+ process.chdir(tempDir);
210
+ const result = validateWUForLinking(TEST_WU_ID);
211
+ expect(result.valid).toBe(false);
212
+ expect(result.errors.some((e) => e.toLowerCase().includes('acceptance'))).toBe(true);
213
+ });
214
+ it('should aggregate multiple errors', async () => {
215
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
216
+ // Create a WU with multiple issues
217
+ const wuDir = join(tempDir, WU_REL_PATH);
218
+ mkdirSync(wuDir, { recursive: true });
219
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
220
+ writeFileSync(wuPath, stringifyYAML({
221
+ id: TEST_WU_ID,
222
+ title: '', // Empty title
223
+ lane: TEST_LANE,
224
+ status: 'invalid_status', // Invalid status
225
+ created: TEST_DATE,
226
+ description: 'short', // Too short
227
+ acceptance: [], // Empty
228
+ }));
229
+ process.chdir(tempDir);
230
+ const result = validateWUForLinking(TEST_WU_ID);
231
+ expect(result.valid).toBe(false);
232
+ // Should have multiple errors aggregated
233
+ expect(result.errors.length).toBeGreaterThanOrEqual(2);
234
+ });
235
+ it('should include warnings but still be valid', async () => {
236
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
237
+ // Create a valid WU that might have warnings (missing optional recommended fields)
238
+ const wuDir = join(tempDir, WU_REL_PATH);
239
+ mkdirSync(wuDir, { recursive: true });
240
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
241
+ writeFileSync(wuPath, stringifyYAML({
242
+ ...createValidWUDoc(),
243
+ notes: '', // Empty notes - should produce warning
244
+ spec_refs: [], // Empty spec_refs for feature - should produce warning
245
+ }));
246
+ process.chdir(tempDir);
247
+ const result = validateWUForLinking(TEST_WU_ID);
248
+ // Should be valid (warnings don't block)
249
+ expect(result.valid).toBe(true);
250
+ // But should have warnings
251
+ expect(result.warnings.length).toBeGreaterThan(0);
252
+ });
253
+ });
254
+ describe('checkWUExists with validation', () => {
255
+ it('should throw for invalid WU when strict validation enabled', async () => {
256
+ const { checkWUExistsAndValidate } = await import('../initiative-add-wu.js');
257
+ // Create an invalid WU file
258
+ const wuDir = join(tempDir, WU_REL_PATH);
259
+ mkdirSync(wuDir, { recursive: true });
260
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
261
+ writeFileSync(wuPath, stringifyYAML({
262
+ id: TEST_WU_ID,
263
+ title: 'Test',
264
+ lane: TEST_LANE,
265
+ status: 'ready',
266
+ created: TEST_DATE,
267
+ description: 'short', // Too short
268
+ }));
269
+ process.chdir(tempDir);
270
+ // Should throw with aggregated validation errors
271
+ expect(() => checkWUExistsAndValidate(TEST_WU_ID)).toThrow();
272
+ });
273
+ it('should return WU doc when validation passes', async () => {
274
+ const { checkWUExistsAndValidate } = await import('../initiative-add-wu.js');
275
+ // Create a valid WU file
276
+ const wuDir = join(tempDir, WU_REL_PATH);
277
+ mkdirSync(wuDir, { recursive: true });
278
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
279
+ writeFileSync(wuPath, stringifyYAML(createValidWUDoc()));
280
+ process.chdir(tempDir);
281
+ const result = checkWUExistsAndValidate(TEST_WU_ID);
282
+ expect(result.id).toBe(TEST_WU_ID);
283
+ });
284
+ });
285
+ describe('initiative:add-wu integration', () => {
286
+ it('should reject linking invalid WU with clear error message', async () => {
287
+ // This is an integration test scenario - main() calls validation before linking
288
+ // The main() function should call validateWUForLinking and die() with aggregated errors
289
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
290
+ // Setup invalid WU
291
+ const wuDir = join(tempDir, WU_REL_PATH);
292
+ mkdirSync(wuDir, { recursive: true });
293
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
294
+ writeFileSync(wuPath, stringifyYAML({
295
+ id: TEST_WU_ID,
296
+ title: 'Test',
297
+ lane: TEST_LANE,
298
+ status: 'ready',
299
+ created: TEST_DATE,
300
+ description: 'Too short',
301
+ }));
302
+ process.chdir(tempDir);
303
+ const result = validateWUForLinking(TEST_WU_ID);
304
+ // The error message should be suitable for display to user
305
+ expect(result.valid).toBe(false);
306
+ expect(result.errors.join('\n')).toContain('50'); // Should mention minimum length
307
+ });
308
+ it('should successfully link valid WU bidirectionally', async () => {
309
+ // This test verifies that after validation passes, bidirectional linking works
310
+ // The existing functionality should still work for valid WUs
311
+ const { validateWUForLinking } = await import('../initiative-add-wu.js');
312
+ // Setup valid WU and initiative
313
+ const wuDir = join(tempDir, WU_REL_PATH);
314
+ const initDir = join(tempDir, INIT_REL_PATH);
315
+ mkdirSync(wuDir, { recursive: true });
316
+ mkdirSync(initDir, { recursive: true });
317
+ const wuPath = join(wuDir, `${TEST_WU_ID}.yaml`);
318
+ const initPath = join(initDir, `${TEST_INIT_ID}.yaml`);
319
+ writeFileSync(wuPath, stringifyYAML(createValidWUDoc()));
320
+ writeFileSync(initPath, stringifyYAML(createValidInitDoc()));
321
+ process.chdir(tempDir);
322
+ // Validation should pass
323
+ const result = validateWUForLinking(TEST_WU_ID);
324
+ expect(result.valid).toBe(true);
325
+ });
326
+ });
327
+ describe('error formatting', () => {
328
+ it('should format errors in human-readable format', async () => {
329
+ const { formatValidationErrors } = await import('../initiative-add-wu.js');
330
+ const errors = ['description: Description is required', 'acceptance: At least one criterion'];
331
+ const wuId = TEST_WU_ID;
332
+ const formatted = formatValidationErrors(wuId, errors);
333
+ expect(formatted).toContain(wuId);
334
+ expect(formatted).toContain('description');
335
+ expect(formatted).toContain('acceptance');
336
+ });
337
+ });
338
+ describe('exports', () => {
339
+ it('should export validateWUForLinking function', async () => {
340
+ const mod = await import('../initiative-add-wu.js');
341
+ expect(typeof mod.validateWUForLinking).toBe('function');
342
+ });
343
+ it('should export checkWUExistsAndValidate function', async () => {
344
+ const mod = await import('../initiative-add-wu.js');
345
+ expect(typeof mod.checkWUExistsAndValidate).toBe('function');
346
+ });
347
+ it('should export formatValidationErrors function', async () => {
348
+ const mod = await import('../initiative-add-wu.js');
349
+ expect(typeof mod.formatValidationErrors).toBe('function');
350
+ });
351
+ it('should export isRetryExhaustionError function (WU-1333)', async () => {
352
+ const mod = await import('../initiative-add-wu.js');
353
+ expect(typeof mod.isRetryExhaustionError).toBe('function');
354
+ });
355
+ it('should export formatRetryExhaustionError function (WU-1333)', async () => {
356
+ const mod = await import('../initiative-add-wu.js');
357
+ expect(typeof mod.formatRetryExhaustionError).toBe('function');
358
+ });
359
+ });
360
+ });
361
+ /**
362
+ * WU-1333: Retry handling tests for initiative:add-wu
363
+ *
364
+ * When origin/main moves during operation, the micro-worktree layer handles retry.
365
+ * When retries are exhausted, the error message should include actionable next steps.
366
+ */
367
+ describe('initiative:add-wu retry handling (WU-1333)', () => {
368
+ describe('isRetryExhaustionError', () => {
369
+ it('should detect retry exhaustion from error message', async () => {
370
+ const { isRetryExhaustionError } = await import('../initiative-add-wu.js');
371
+ // Should detect retry exhaustion error
372
+ const retryError = new Error('Push failed after 3 attempts. Origin main may have significant traffic.');
373
+ expect(isRetryExhaustionError(retryError)).toBe(true);
374
+ });
375
+ it('should detect retry exhaustion with any attempt count', async () => {
376
+ const { isRetryExhaustionError } = await import('../initiative-add-wu.js');
377
+ // Different attempt counts should still match
378
+ const error5 = new Error('Push failed after 5 attempts. Something.');
379
+ expect(isRetryExhaustionError(error5)).toBe(true);
380
+ const error1 = new Error('Push failed after 1 attempts. Something.');
381
+ expect(isRetryExhaustionError(error1)).toBe(true);
382
+ });
383
+ it('should not match other errors', async () => {
384
+ const { isRetryExhaustionError } = await import('../initiative-add-wu.js');
385
+ const otherError = new Error('Some other error');
386
+ expect(isRetryExhaustionError(otherError)).toBe(false);
387
+ const networkError = new Error('Network unreachable');
388
+ expect(isRetryExhaustionError(networkError)).toBe(false);
389
+ });
390
+ });
391
+ describe('formatRetryExhaustionError', () => {
392
+ it('should include actionable next steps', async () => {
393
+ const { formatRetryExhaustionError } = await import('../initiative-add-wu.js');
394
+ const retryError = new Error('Push failed after 3 attempts. Origin main may have significant traffic.');
395
+ const formatted = formatRetryExhaustionError(retryError, TEST_WU_ID, TEST_INIT_ID);
396
+ // Should include the original error
397
+ expect(formatted).toContain('Push failed after 3 attempts');
398
+ // Should include next steps heading
399
+ expect(formatted).toContain('Next steps:');
400
+ // Should include actionable suggestions
401
+ expect(formatted).toContain('Wait a few seconds and retry');
402
+ expect(formatted).toContain('initiative:add-wu');
403
+ });
404
+ it('should include the retry command', async () => {
405
+ const { formatRetryExhaustionError } = await import('../initiative-add-wu.js');
406
+ const retryError = new Error('Push failed after 3 attempts.');
407
+ const formatted = formatRetryExhaustionError(retryError, TEST_WU_ID, TEST_INIT_ID);
408
+ // Should include command to retry
409
+ expect(formatted).toContain(`--wu ${TEST_WU_ID}`);
410
+ expect(formatted).toContain(`--initiative ${TEST_INIT_ID}`);
411
+ });
412
+ it('should suggest checking for concurrent agents', async () => {
413
+ const { formatRetryExhaustionError } = await import('../initiative-add-wu.js');
414
+ const retryError = new Error('Push failed after 3 attempts.');
415
+ const formatted = formatRetryExhaustionError(retryError, TEST_WU_ID, TEST_INIT_ID);
416
+ // Should mention concurrent agents as possible cause
417
+ expect(formatted).toMatch(/concurrent|agent|traffic/i);
418
+ });
419
+ });
420
+ });
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Tests for initiative:plan replacement by plan:link (WU-1313)
3
+ *
4
+ * Validates that the existing initiative:plan functionality is preserved
5
+ * when replaced by plan:link --target INIT-XXX.
6
+ *
7
+ * TDD: These tests are written BEFORE the implementation.
8
+ */
9
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
10
+ import { existsSync, mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { tmpdir } from 'node:os';
13
+ import { parseYAML, stringifyYAML } from '@lumenflow/core/dist/wu-yaml.js';
14
+ /** Test constants - avoid sonarjs/no-duplicate-string */
15
+ const TEST_INIT_DIR = 'docs/04-operations/tasks/initiatives';
16
+ const TEST_INIT_ID = 'INIT-001';
17
+ const TEST_INIT_PLAN_URI = `lumenflow://plans/${TEST_INIT_ID}-plan.md`;
18
+ const TEST_PLANS_DIR = 'docs/04-operations/plans';
19
+ // eslint-disable-next-line sonarjs/publicly-writable-directories -- test constant for bad path detection
20
+ const TEST_LUMENFLOW_HOME_BAD = '/tmp/lumenflow-home-should-not-be-used';
21
+ const TEST_INIT_SLUG = 'test-initiative';
22
+ const TEST_INIT_TITLE = 'Test Initiative';
23
+ const TEST_STATUS_OPEN = 'open';
24
+ const TEST_DATE = '2026-01-25';
25
+ // Mock modules before importing
26
+ vi.mock('@lumenflow/core/dist/git-adapter.js', () => ({
27
+ getGitForCwd: vi.fn(() => ({
28
+ branch: vi.fn().mockResolvedValue({ current: 'main' }),
29
+ status: vi.fn().mockResolvedValue({ isClean: () => true }),
30
+ })),
31
+ }));
32
+ vi.mock('@lumenflow/core/dist/wu-helpers.js', () => ({
33
+ ensureOnMain: vi.fn().mockResolvedValue(undefined),
34
+ }));
35
+ vi.mock('@lumenflow/core/dist/micro-worktree.js', () => ({
36
+ withMicroWorktree: vi.fn(async ({ execute }) => {
37
+ const tempDir = join(tmpdir(), `init-plan-replace-test-${Date.now()}`);
38
+ mkdirSync(tempDir, { recursive: true });
39
+ return execute({ worktreePath: tempDir });
40
+ }),
41
+ }));
42
+ describe('initiative:plan replaced by plan:link', () => {
43
+ let tempDir;
44
+ let originalCwd;
45
+ beforeEach(() => {
46
+ tempDir = join(tmpdir(), `init-plan-replace-test-${Date.now()}`);
47
+ mkdirSync(tempDir, { recursive: true });
48
+ originalCwd = process.cwd();
49
+ });
50
+ afterEach(() => {
51
+ process.chdir(originalCwd);
52
+ if (existsSync(tempDir)) {
53
+ rmSync(tempDir, { recursive: true, force: true });
54
+ }
55
+ vi.clearAllMocks();
56
+ });
57
+ describe('plan:link for initiatives (backwards compatibility)', () => {
58
+ it('should link plan to initiative via related_plan field', async () => {
59
+ const { linkPlanToInitiative } = await import('../plan-link.js');
60
+ // Setup mock initiative file
61
+ const initDir = join(tempDir, ...TEST_INIT_DIR.split('/'));
62
+ mkdirSync(initDir, { recursive: true });
63
+ const initPath = join(initDir, `${TEST_INIT_ID}.yaml`);
64
+ const initDoc = {
65
+ id: TEST_INIT_ID,
66
+ slug: TEST_INIT_SLUG,
67
+ title: TEST_INIT_TITLE,
68
+ status: TEST_STATUS_OPEN,
69
+ created: TEST_DATE,
70
+ };
71
+ writeFileSync(initPath, stringifyYAML(initDoc));
72
+ // Link plan (same operation as initiative:plan --initiative --plan)
73
+ const changed = linkPlanToInitiative(tempDir, TEST_INIT_ID, TEST_INIT_PLAN_URI);
74
+ expect(changed).toBe(true);
75
+ // Verify the file was updated
76
+ const updated = parseYAML(readFileSync(initPath, 'utf-8'));
77
+ expect(updated.related_plan).toBe(TEST_INIT_PLAN_URI);
78
+ });
79
+ it('should create plan and link in single operation', async () => {
80
+ const { createPlan } = await import('../plan-create.js');
81
+ const { linkPlanToInitiative } = await import('../plan-link.js');
82
+ // Setup mock initiative file
83
+ const initDir = join(tempDir, ...TEST_INIT_DIR.split('/'));
84
+ mkdirSync(initDir, { recursive: true });
85
+ const initPath = join(initDir, `${TEST_INIT_ID}.yaml`);
86
+ const initDoc = {
87
+ id: TEST_INIT_ID,
88
+ slug: TEST_INIT_SLUG,
89
+ title: TEST_INIT_TITLE,
90
+ status: TEST_STATUS_OPEN,
91
+ created: TEST_DATE,
92
+ };
93
+ writeFileSync(initPath, stringifyYAML(initDoc));
94
+ // Create plan (like initiative:plan --create)
95
+ const planPath = createPlan(tempDir, TEST_INIT_ID, TEST_INIT_TITLE);
96
+ expect(existsSync(planPath)).toBe(true);
97
+ // Link plan
98
+ const changed = linkPlanToInitiative(tempDir, TEST_INIT_ID, TEST_INIT_PLAN_URI);
99
+ expect(changed).toBe(true);
100
+ // Verify both plan file and initiative were updated
101
+ const updated = parseYAML(readFileSync(initPath, 'utf-8'));
102
+ expect(updated.related_plan).toBe(TEST_INIT_PLAN_URI);
103
+ });
104
+ });
105
+ describe('initiative:plan deprecation', () => {
106
+ it('should warn when using deprecated initiative:plan command', async () => {
107
+ // The initiative:plan command should still work but warn about deprecation
108
+ // and suggest using plan:link instead
109
+ const initPlan = await import('../initiative-plan.js');
110
+ expect(typeof initPlan.main).toBe('function');
111
+ // The deprecation warning will be in the main function
112
+ });
113
+ });
114
+ describe('plan:link auto-detection', () => {
115
+ it('should auto-detect INIT target and call linkPlanToInitiative', async () => {
116
+ const { resolveTargetType } = await import('../plan-link.js');
117
+ expect(resolveTargetType(TEST_INIT_ID)).toBe('initiative');
118
+ expect(resolveTargetType('INIT-TOOLING')).toBe('initiative');
119
+ });
120
+ it('should auto-detect WU target and call linkPlanToWU', async () => {
121
+ const { resolveTargetType } = await import('../plan-link.js');
122
+ expect(resolveTargetType('WU-1313')).toBe('wu');
123
+ expect(resolveTargetType('WU-001')).toBe('wu');
124
+ });
125
+ });
126
+ });
127
+ describe('plan storage defaults to repo plansDir', () => {
128
+ let tempDir;
129
+ let originalCwd;
130
+ beforeEach(() => {
131
+ tempDir = join(tmpdir(), `plan-storage-test-${Date.now()}`);
132
+ mkdirSync(tempDir, { recursive: true });
133
+ originalCwd = process.cwd();
134
+ });
135
+ afterEach(() => {
136
+ process.chdir(originalCwd);
137
+ if (existsSync(tempDir)) {
138
+ rmSync(tempDir, { recursive: true, force: true });
139
+ }
140
+ vi.clearAllMocks();
141
+ });
142
+ it('should create plans in repo directories.plansDir, not LUMENFLOW_HOME', async () => {
143
+ const { createPlan } = await import('../plan-create.js');
144
+ // Set LUMENFLOW_HOME to a different location (should be ignored)
145
+ const oldLfHome = process.env.LUMENFLOW_HOME;
146
+ process.env.LUMENFLOW_HOME = TEST_LUMENFLOW_HOME_BAD;
147
+ try {
148
+ const planPath = createPlan(tempDir, 'WU-1313', 'Test Plan');
149
+ // Plan should be in repo plansDir, not LUMENFLOW_HOME
150
+ expect(planPath).toContain(TEST_PLANS_DIR);
151
+ expect(planPath).not.toContain(TEST_LUMENFLOW_HOME_BAD);
152
+ }
153
+ finally {
154
+ if (oldLfHome === undefined) {
155
+ delete process.env.LUMENFLOW_HOME;
156
+ }
157
+ else {
158
+ process.env.LUMENFLOW_HOME = oldLfHome;
159
+ }
160
+ }
161
+ });
162
+ });