aiwcli 0.10.2 → 0.10.3

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 (105) hide show
  1. package/dist/commands/clear.d.ts +11 -6
  2. package/dist/commands/clear.js +200 -249
  3. package/dist/commands/init/index.d.ts +1 -17
  4. package/dist/commands/init/index.js +19 -104
  5. package/dist/lib/template-installer.d.ts +7 -12
  6. package/dist/lib/template-installer.js +69 -193
  7. package/dist/lib/template-settings-reconstructor.d.ts +35 -0
  8. package/dist/lib/template-settings-reconstructor.js +130 -0
  9. package/dist/templates/_shared/hooks/__pycache__/archive_plan.cpython-313.pyc +0 -0
  10. package/dist/templates/_shared/hooks/archive_plan.py +10 -2
  11. package/dist/templates/_shared/lib/base/__pycache__/hook_utils.cpython-313.pyc +0 -0
  12. package/dist/templates/_shared/lib/base/__pycache__/inference.cpython-313.pyc +0 -0
  13. package/dist/templates/_shared/lib/base/__pycache__/logger.cpython-313.pyc +0 -0
  14. package/dist/templates/_shared/lib/base/__pycache__/stop_words.cpython-313.pyc +0 -0
  15. package/dist/templates/_shared/lib/base/__pycache__/utils.cpython-313.pyc +0 -0
  16. package/dist/templates/_shared/lib/base/hook_utils.py +8 -10
  17. package/dist/templates/_shared/lib/base/inference.py +51 -62
  18. package/dist/templates/_shared/lib/base/logger.py +35 -21
  19. package/dist/templates/_shared/lib/base/stop_words.py +8 -0
  20. package/dist/templates/_shared/lib/base/utils.py +29 -8
  21. package/dist/templates/_shared/lib/context/__pycache__/plan_manager.cpython-313.pyc +0 -0
  22. package/dist/templates/_shared/lib/context/plan_manager.py +101 -2
  23. package/dist/templates/_shared/lib-ts/base/atomic-write.ts +138 -0
  24. package/dist/templates/_shared/lib-ts/base/constants.ts +299 -0
  25. package/dist/templates/_shared/lib-ts/base/git-state.ts +58 -0
  26. package/dist/templates/_shared/lib-ts/base/hook-utils.ts +360 -0
  27. package/dist/templates/_shared/lib-ts/base/inference.ts +245 -0
  28. package/dist/templates/_shared/lib-ts/base/logger.ts +234 -0
  29. package/dist/templates/_shared/lib-ts/base/state-io.ts +114 -0
  30. package/dist/templates/_shared/lib-ts/base/stop-words.ts +184 -0
  31. package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +23 -0
  32. package/dist/templates/_shared/lib-ts/base/utils.ts +184 -0
  33. package/dist/templates/_shared/lib-ts/context/context-formatter.ts +432 -0
  34. package/dist/templates/_shared/lib-ts/context/context-selector.ts +497 -0
  35. package/dist/templates/_shared/lib-ts/context/context-store.ts +679 -0
  36. package/dist/templates/_shared/lib-ts/context/plan-manager.ts +292 -0
  37. package/dist/templates/_shared/lib-ts/context/task-tracker.ts +181 -0
  38. package/dist/templates/_shared/lib-ts/handoff/document-generator.ts +215 -0
  39. package/dist/templates/_shared/lib-ts/package.json +21 -0
  40. package/dist/templates/_shared/lib-ts/templates/formatters.ts +102 -0
  41. package/dist/templates/_shared/lib-ts/templates/plan-context.ts +65 -0
  42. package/dist/templates/_shared/lib-ts/tsconfig.json +13 -0
  43. package/dist/templates/_shared/lib-ts/types.ts +151 -0
  44. package/dist/templates/_shared/scripts/__pycache__/status_line.cpython-313.pyc +0 -0
  45. package/dist/templates/_shared/scripts/save_handoff.ts +359 -0
  46. package/dist/templates/_shared/scripts/status_line.py +17 -2
  47. package/dist/templates/cc-native/_cc-native/agents/ARCH-EVOLUTION.md +63 -0
  48. package/dist/templates/cc-native/_cc-native/agents/ARCH-PATTERNS.md +62 -0
  49. package/dist/templates/cc-native/_cc-native/agents/ARCH-STRUCTURE.md +63 -0
  50. package/dist/templates/cc-native/_cc-native/agents/{ASSUMPTION-CHAIN-TRACER.md → ASSUMPTION-TRACER.md} +6 -10
  51. package/dist/templates/cc-native/_cc-native/agents/CLARITY-AUDITOR.md +6 -10
  52. package/dist/templates/cc-native/_cc-native/agents/CLAUDE.md +74 -1
  53. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-FEASIBILITY.md +67 -0
  54. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-GAPS.md +71 -0
  55. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-ORDERING.md +63 -0
  56. package/dist/templates/cc-native/_cc-native/agents/CONSTRAINT-VALIDATOR.md +73 -0
  57. package/dist/templates/cc-native/_cc-native/agents/DESIGN-ADR-VALIDATOR.md +62 -0
  58. package/dist/templates/cc-native/_cc-native/agents/DESIGN-SCALE-MATCHER.md +65 -0
  59. package/dist/templates/cc-native/_cc-native/agents/DEVILS-ADVOCATE.md +6 -9
  60. package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-PHILOSOPHY.md +87 -0
  61. package/dist/templates/cc-native/_cc-native/agents/HANDOFF-READINESS.md +5 -9
  62. package/dist/templates/cc-native/_cc-native/agents/{HIDDEN-COMPLEXITY-DETECTOR.md → HIDDEN-COMPLEXITY.md} +6 -10
  63. package/dist/templates/cc-native/_cc-native/agents/INCREMENTAL-DELIVERY.md +67 -0
  64. package/dist/templates/cc-native/_cc-native/agents/PLAN-ORCHESTRATOR.md +91 -18
  65. package/dist/templates/cc-native/_cc-native/agents/RISK-DEPENDENCY.md +63 -0
  66. package/dist/templates/cc-native/_cc-native/agents/RISK-FMEA.md +67 -0
  67. package/dist/templates/cc-native/_cc-native/agents/RISK-PREMORTEM.md +72 -0
  68. package/dist/templates/cc-native/_cc-native/agents/RISK-REVERSIBILITY.md +75 -0
  69. package/dist/templates/cc-native/_cc-native/agents/SCOPE-BOUNDARY.md +78 -0
  70. package/dist/templates/cc-native/_cc-native/agents/SIMPLICITY-GUARDIAN.md +5 -9
  71. package/dist/templates/cc-native/_cc-native/agents/SKEPTIC.md +16 -12
  72. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-BEHAVIOR-AUDITOR.md +62 -0
  73. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-CHARACTERIZATION.md +72 -0
  74. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-FIRST-VALIDATOR.md +62 -0
  75. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-PYRAMID-ANALYZER.md +62 -0
  76. package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-COSTS.md +68 -0
  77. package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-STAKEHOLDERS.md +66 -0
  78. package/dist/templates/cc-native/_cc-native/agents/VERIFY-COVERAGE.md +75 -0
  79. package/dist/templates/cc-native/_cc-native/agents/VERIFY-STRENGTH.md +70 -0
  80. package/dist/templates/cc-native/_cc-native/hooks/__pycache__/cc-native-plan-review.cpython-313.pyc +0 -0
  81. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.py +125 -40
  82. package/dist/templates/cc-native/_cc-native/lib/__pycache__/utils.cpython-313.pyc +0 -0
  83. package/dist/templates/cc-native/_cc-native/lib/utils.py +57 -13
  84. package/dist/templates/cc-native/_cc-native/plan-review.config.json +11 -7
  85. package/oclif.manifest.json +1 -1
  86. package/package.json +1 -1
  87. package/dist/lib/template-merger.d.ts +0 -47
  88. package/dist/lib/template-merger.js +0 -162
  89. package/dist/templates/cc-native/_cc-native/agents/ACCESSIBILITY-TESTER.md +0 -79
  90. package/dist/templates/cc-native/_cc-native/agents/ARCHITECT-REVIEWER.md +0 -48
  91. package/dist/templates/cc-native/_cc-native/agents/CODE-REVIEWER.md +0 -70
  92. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-CHECKER.md +0 -59
  93. package/dist/templates/cc-native/_cc-native/agents/CONTEXT-EXTRACTOR.md +0 -92
  94. package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-REVIEWER.md +0 -51
  95. package/dist/templates/cc-native/_cc-native/agents/FEASIBILITY-ANALYST.md +0 -57
  96. package/dist/templates/cc-native/_cc-native/agents/FRESH-PERSPECTIVE.md +0 -54
  97. package/dist/templates/cc-native/_cc-native/agents/INCENTIVE-MAPPER.md +0 -61
  98. package/dist/templates/cc-native/_cc-native/agents/PENETRATION-TESTER.md +0 -79
  99. package/dist/templates/cc-native/_cc-native/agents/PERFORMANCE-ENGINEER.md +0 -75
  100. package/dist/templates/cc-native/_cc-native/agents/PRECEDENT-FINDER.md +0 -70
  101. package/dist/templates/cc-native/_cc-native/agents/REVERSIBILITY-ANALYST.md +0 -61
  102. package/dist/templates/cc-native/_cc-native/agents/RISK-ASSESSOR.md +0 -58
  103. package/dist/templates/cc-native/_cc-native/agents/SECOND-ORDER-ANALYST.md +0 -61
  104. package/dist/templates/cc-native/_cc-native/agents/STAKEHOLDER-ADVOCATE.md +0 -55
  105. package/dist/templates/cc-native/_cc-native/agents/TRADE-OFF-ILLUMINATOR.md +0 -204
@@ -4,16 +4,14 @@ import { fileURLToPath } from 'node:url';
4
4
  import { checkbox, confirm, input, select } from '@inquirer/prompts';
5
5
  import { Flags } from '@oclif/core';
6
6
  import BaseCommand from '../../lib/base-command.js';
7
- import { detectUsername } from '../../lib/user-utils.js';
8
7
  import { updateGitignore } from '../../lib/gitignore-manager.js';
9
- import { mergeClaudeSettings } from '../../lib/hooks-merger.js';
10
8
  import { IdePathResolver } from '../../lib/ide-path-resolver.js';
11
9
  import { pathExists } from '../../lib/paths.js';
12
10
  import { getTargetSettingsFile, readClaudeSettings, writeClaudeSettings } from '../../lib/settings-hierarchy.js';
13
11
  import { checkTemplateStatus, installTemplate, shouldExclude } from '../../lib/template-installer.js';
14
12
  import { getAvailableTemplates, getTemplatePath } from '../../lib/template-resolver.js';
15
- import { getTargetHooksFile, readWindsurfHooks, writeWindsurfHooks } from '../../lib/windsurf-hooks-hierarchy.js';
16
- import { mergeWindsurfHooks } from '../../lib/windsurf-hooks-merger.js';
13
+ import { reconstructIdeSettings } from '../../lib/template-settings-reconstructor.js';
14
+ import { detectUsername } from '../../lib/user-utils.js';
17
15
  import { EXIT_CODES } from '../../types/exit-codes.js';
18
16
  /**
19
17
  * Available IDEs for configuration
@@ -93,7 +91,10 @@ export default class Init extends BaseCommand {
93
91
  await fs.mkdir(containerDir, { recursive: true });
94
92
  const sharedDestPath = resolver.getSharedFolder();
95
93
  const sharedExists = await pathExists(sharedDestPath);
96
- if (!sharedExists) {
94
+ if (sharedExists) {
95
+ this.logInfo('✓ _shared folder already exists - skipping');
96
+ }
97
+ else {
97
98
  const currentFilePath = fileURLToPath(import.meta.url);
98
99
  const currentDir = dirname(currentFilePath);
99
100
  const templatesRoot = join(dirname(dirname(currentDir)), 'templates');
@@ -106,11 +107,8 @@ export default class Init extends BaseCommand {
106
107
  await this.copyDirectory(sharedSrcPath, sharedDestPath, true);
107
108
  this.logSuccess('✓ Installed _shared folder');
108
109
  }
109
- else {
110
- this.logInfo('✓ _shared folder already exists - skipping');
111
- }
112
- // Merge settings from _shared template
113
- await this.mergeMethodsSettings(targetDir, ['_shared'], ['claude']);
110
+ // Reconstruct settings from _shared template
111
+ await reconstructIdeSettings(targetDir, [], ['claude']);
114
112
  // Update .gitignore if git repository exists
115
113
  if (hasGit) {
116
114
  await updateGitignore(targetDir, ['.aiwcli']);
@@ -169,7 +167,7 @@ export default class Init extends BaseCommand {
169
167
  // Still update gitignore and merge hooks if needed
170
168
  }
171
169
  this.log('');
172
- // Install template with selective installation (skip existing items)
170
+ // Install template (always overwrites method-owned content)
173
171
  const result = await installTemplate({
174
172
  templateName: method,
175
173
  targetDir,
@@ -177,7 +175,7 @@ export default class Init extends BaseCommand {
177
175
  username,
178
176
  projectName,
179
177
  templatePath,
180
- }, true);
178
+ });
181
179
  // Collect all folders that need gitignore entries
182
180
  // The .aiwcli/ container holds all template infrastructure and runtime data
183
181
  const foldersForGitignore = ['.aiwcli'];
@@ -185,12 +183,6 @@ export default class Init extends BaseCommand {
185
183
  if (result.installedFolders.length > 0) {
186
184
  this.logSuccess(`✓ Installed: ${result.installedFolders.join(', ')}`);
187
185
  }
188
- if (result.mergedFolders.length > 0) {
189
- this.logSuccess(`✓ Merged content into: ${result.mergedFolders.join(', ')} (${result.mergedFileCount} files)`);
190
- }
191
- if (result.skippedFolders.length > 0) {
192
- this.logInfo(`✓ Skipped (already exist): ${result.skippedFolders.join(', ')}`);
193
- }
194
186
  // Perform post-installation actions (settings tracking, hook merging, gitignore updates)
195
187
  await this.performPostInstallActions({
196
188
  targetDir,
@@ -271,94 +263,12 @@ export default class Init extends BaseCommand {
271
263
  };
272
264
  return descriptions[template] || 'Custom template';
273
265
  }
274
- /**
275
- * Merge settings from multiple method templates into project settings.
276
- * Processes methods in order, allowing later methods to override earlier ones.
277
- *
278
- * @param targetDir - Project directory
279
- * @param methods - Array of method names to merge (e.g., ['_shared', 'cc-native'])
280
- * @param ides - IDEs being configured (for IDE-specific merging)
281
- */
282
- async mergeMethodsSettings(targetDir, methods, ides) {
283
- const targetSettingsPath = getTargetSettingsFile(targetDir);
284
- let projectSettings = (await readClaudeSettings(targetSettingsPath)) || {};
285
- for (const method of methods) {
286
- try {
287
- // Get template path for this method
288
- let templatePath;
289
- if (method === '_shared') {
290
- // Special case: _shared is at templates/_shared
291
- const currentFilePath = fileURLToPath(import.meta.url);
292
- const currentDir = dirname(currentFilePath);
293
- const templatesRoot = join(dirname(dirname(currentDir)), 'templates');
294
- templatePath = join(templatesRoot, '_shared');
295
- }
296
- else {
297
- // Named method templates
298
- templatePath = await getTemplatePath(method);
299
- }
300
- // Merge Claude settings if claude IDE is selected
301
- if (ides.includes('claude')) {
302
- const templateSettingsPath = join(templatePath, '.claude', 'settings.json');
303
- const templateSettings = await readClaudeSettings(templateSettingsPath);
304
- if (templateSettings) {
305
- projectSettings = mergeClaudeSettings(projectSettings, templateSettings);
306
- this.logSuccess(`✓ Merged ${method} settings into .claude/settings.json`);
307
- }
308
- }
309
- // Merge Windsurf hooks if windsurf IDE is selected
310
- if (ides.includes('windsurf')) {
311
- await this.mergeWindsurfTemplateHooks(targetDir, templatePath);
312
- }
313
- }
314
- catch (error) {
315
- const err = error;
316
- this.warn(`Failed to merge ${method} settings: ${err.message}`);
317
- }
318
- }
319
- // Write merged Claude settings
320
- if (ides.includes('claude')) {
321
- await writeClaudeSettings(targetSettingsPath, projectSettings);
322
- }
323
- }
324
- /**
325
- * Merge Windsurf template hooks into project hooks
326
- *
327
- * @param targetDir - Project directory
328
- * @param templatePath - Template source path
329
- */
330
- async mergeWindsurfTemplateHooks(targetDir, templatePath) {
331
- try {
332
- // Read template hooks
333
- const templateHooksPath = join(templatePath, '.windsurf', 'hooks.json');
334
- const templateHooks = await readWindsurfHooks(templateHooksPath);
335
- // If template has no hooks, nothing to merge
336
- if (!templateHooks || !templateHooks.hooks || Object.keys(templateHooks.hooks).length === 0) {
337
- this.logInfo('No Windsurf hooks in template to merge');
338
- return;
339
- }
340
- // Get target hooks file path
341
- const targetHooksPath = getTargetHooksFile(targetDir);
342
- // Read existing project hooks
343
- const existingHooks = await readWindsurfHooks(targetHooksPath);
344
- // Merge hooks
345
- const mergedHooks = mergeWindsurfHooks(existingHooks, templateHooks);
346
- // Write merged hooks
347
- await writeWindsurfHooks(targetHooksPath, mergedHooks);
348
- this.logSuccess('✓ Windsurf template hooks merged into project hooks');
349
- }
350
- catch (error) {
351
- const err = error;
352
- this.warn(`Failed to merge Windsurf template hooks: ${err.message}`);
353
- // Don't fail the entire installation if hook merging fails
354
- }
355
- }
356
266
  /**
357
267
  * Perform post-installation actions.
358
268
  *
359
269
  * Handles:
360
270
  * - Method tracking in settings.json
361
- * - Settings/hooks merging for all methods
271
+ * - Settings reconstruction from all active templates
362
272
  * - .gitignore updates
363
273
  *
364
274
  * @param config - Post-install configuration
@@ -370,10 +280,15 @@ export default class Init extends BaseCommand {
370
280
  */
371
281
  async performPostInstallActions(config) {
372
282
  const { targetDir, method, ides, hasGit, foldersForGitignore } = config;
373
- // Track method installation in settings.json
283
+ // Track method installation in settings.json first (so reconstructor can read methods list)
374
284
  await this.trackMethodInstallation(targetDir, method, ides);
375
- // Merge settings from _shared and method templates
376
- await this.mergeMethodsSettings(targetDir, ['_shared', method], ides);
285
+ // Read installed methods to build active templates list
286
+ const settingsPath = getTargetSettingsFile(targetDir);
287
+ const settings = await readClaudeSettings(settingsPath);
288
+ const activeTemplates = settings?.methods ? Object.keys(settings.methods) : [method];
289
+ // Reconstruct IDE settings from all active templates
290
+ await reconstructIdeSettings(targetDir, activeTemplates, ides);
291
+ this.logSuccess('✓ Reconstructed IDE settings from active templates');
377
292
  // Update .gitignore if git repository exists
378
293
  if (hasGit) {
379
294
  await updateGitignore(targetDir, foldersForGitignore);
@@ -45,14 +45,8 @@ export interface TemplateInstallationStatus {
45
45
  export interface InstallationResult {
46
46
  /** List of folder names that were installed (for gitignore) */
47
47
  installedFolders: string[];
48
- /** Number of files that were merged into existing folders */
49
- mergedFileCount: number;
50
- /** List of folder names that had content merged */
51
- mergedFolders: string[];
52
48
  /** Whether shared settings were merged into IDE settings */
53
49
  sharedSettingsMerged: boolean;
54
- /** List of folder names that were skipped (already exist) */
55
- skippedFolders: string[];
56
50
  /** Absolute path to the template that was installed */
57
51
  templatePath: string;
58
52
  }
@@ -87,15 +81,16 @@ export declare function shouldExclude(name: string): boolean;
87
81
  export declare function copyDir(src: string, dest: string, excludeIdeFolders?: boolean): Promise<void>;
88
82
  /**
89
83
  * Install template with IDE-specific folder selection.
90
- * Supports selective installation - only installs items that don't already exist.
91
84
  *
92
85
  * Template structure:
93
- * - Non-dot folders (e.g., _bmad/, GSR/) are installed if not already present
94
- * - Dot folders (e.g., .claude/, .windsurf/) are installed only if matching IDE flag and not already present
86
+ * - Non-dot folders (e.g., _bmad/, GSR/) .aiwcli/ (always overwritten)
87
+ * - _shared/ .aiwcli/_shared/ (always overwritten)
88
+ * - IDE dot folders (e.g., .claude/) → decomposed into method-owned subdirs
89
+ *
90
+ * Settings reconstruction is handled separately by the caller via reconstructIdeSettings().
95
91
  *
96
92
  * @param config - Installation configuration
97
- * @param skipExisting - If true, skip items that already exist (default: true for regeneration support)
98
- * @returns Installation result with list of installed and skipped folders
93
+ * @returns Installation result with list of installed folders
99
94
  * @throws Error if template doesn't exist or requested IDE folder not found
100
95
  */
101
- export declare function installTemplate(config: TemplateInstallConfig, skipExisting?: boolean): Promise<InstallationResult>;
96
+ export declare function installTemplate(config: TemplateInstallConfig): Promise<InstallationResult>;
@@ -2,98 +2,6 @@ import { promises as fs } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { IdePathResolver } from './ide-path-resolver.js';
4
4
  import { pathExists } from './paths.js';
5
- import { mergeTemplateContent } from './template-merger.js';
6
- /**
7
- * Deep merge two settings objects, combining hook arrays.
8
- * Used to merge _shared/settings.json into .claude/settings.json
9
- */
10
- function deepMergeSettings(target, source) {
11
- const result = { ...target };
12
- for (const key of Object.keys(source)) {
13
- // Skip comment fields
14
- if (key.startsWith('$') || key.startsWith('_')) {
15
- continue;
16
- }
17
- const sourceValue = source[key];
18
- const targetValue = result[key];
19
- if (key === 'hooks' && typeof sourceValue === 'object' && sourceValue !== null) {
20
- // Special handling for hooks - merge by event type
21
- result[key] = mergeHooks(targetValue || {}, sourceValue);
22
- }
23
- else if (Array.isArray(sourceValue) && Array.isArray(targetValue)) {
24
- // Concatenate arrays
25
- result[key] = [...targetValue, ...sourceValue];
26
- }
27
- else if (typeof sourceValue === 'object' && sourceValue !== null && typeof targetValue === 'object' && targetValue !== null) {
28
- // Recursively merge objects
29
- result[key] = deepMergeSettings(targetValue, sourceValue);
30
- }
31
- else {
32
- // Override with source value
33
- result[key] = sourceValue;
34
- }
35
- }
36
- return result;
37
- }
38
- /**
39
- * Merge hook configurations, combining arrays for each event type.
40
- */
41
- function mergeHooks(target, source) {
42
- const result = { ...target };
43
- for (const eventType of Object.keys(source)) {
44
- const targetHooks = result[eventType];
45
- const sourceHooks = source[eventType];
46
- if (targetHooks && sourceHooks) {
47
- // Append source hooks to existing event type
48
- result[eventType] = [...targetHooks, ...sourceHooks];
49
- }
50
- else if (sourceHooks) {
51
- // New event type
52
- result[eventType] = sourceHooks;
53
- }
54
- }
55
- return result;
56
- }
57
- /**
58
- * Merge settings from a source settings.json file into the IDE settings file.
59
- * Reads from the provided source path and merges into .claude/settings.json at project root.
60
- *
61
- * @param targetDir - Project root directory
62
- * @param sourceSettingsPath - Absolute path to source settings.json file
63
- * @returns true if merge successful, false otherwise
64
- */
65
- async function mergeSharedSettingsFromSource(targetDir, sourceSettingsPath) {
66
- const resolver = new IdePathResolver(targetDir);
67
- const ideSettingsPath = resolver.getClaudeSettings();
68
- // Check if source settings exists
69
- if (!(await pathExists(sourceSettingsPath))) {
70
- return false;
71
- }
72
- try {
73
- // Read source settings
74
- const sourceContent = await fs.readFile(sourceSettingsPath, 'utf8');
75
- const sourceSettings = JSON.parse(sourceContent);
76
- // Read IDE settings (create empty object if doesn't exist)
77
- let ideSettings = {};
78
- if (await pathExists(ideSettingsPath)) {
79
- const ideContent = await fs.readFile(ideSettingsPath, 'utf8');
80
- ideSettings = JSON.parse(ideContent);
81
- }
82
- else {
83
- // Create .claude directory if it doesn't exist
84
- await fs.mkdir(dirname(ideSettingsPath), { recursive: true });
85
- }
86
- // Merge source settings into IDE settings
87
- const mergedSettings = deepMergeSettings(ideSettings, sourceSettings);
88
- // Write merged settings back
89
- await fs.writeFile(ideSettingsPath, JSON.stringify(mergedSettings, null, 4) + '\n', 'utf8');
90
- return true;
91
- }
92
- catch {
93
- // Silently fail on parse/write errors
94
- return false;
95
- }
96
- }
97
5
  /**
98
6
  * Check template installation status for a method.
99
7
  * Returns which items exist and which are missing.
@@ -186,32 +94,6 @@ export function shouldExclude(name) {
186
94
  return pattern.test(name);
187
95
  });
188
96
  }
189
- /**
190
- * Merge source directory into destination, skipping existing files.
191
- * Unlike copyDir, this preserves existing files in destination.
192
- *
193
- * @param src - Source directory path
194
- * @param dest - Destination directory path
195
- */
196
- async function mergeDirectory(src, dest) {
197
- await fs.mkdir(dest, { recursive: true });
198
- const entries = await fs.readdir(src, { withFileTypes: true });
199
- for (const entry of entries) {
200
- if (shouldExclude(entry.name))
201
- continue;
202
- const srcPath = join(src, entry.name);
203
- const destPath = join(dest, entry.name);
204
- if (entry.isDirectory()) {
205
- await mergeDirectory(srcPath, destPath);
206
- }
207
- else {
208
- // Skip if file already exists
209
- if (!(await pathExists(destPath))) {
210
- await fs.copyFile(srcPath, destPath);
211
- }
212
- }
213
- }
214
- }
215
97
  /**
216
98
  * Copy directory recursively with proper error handling.
217
99
  * Excludes test files, cache directories, and output folders.
@@ -249,20 +131,45 @@ export async function copyDir(src, dest, excludeIdeFolders = false) {
249
131
  });
250
132
  await Promise.all(operations);
251
133
  }
134
+ /**
135
+ * Merge source directory into destination, skipping existing files.
136
+ * Unlike copyDir, this preserves existing files in destination.
137
+ *
138
+ * @param src - Source directory path
139
+ * @param dest - Destination directory path
140
+ */
141
+ async function mergeDirectory(src, dest) {
142
+ await fs.mkdir(dest, { recursive: true });
143
+ const entries = await fs.readdir(src, { withFileTypes: true });
144
+ const ops = entries
145
+ .filter((entry) => !shouldExclude(entry.name))
146
+ .map(async (entry) => {
147
+ const srcPath = join(src, entry.name);
148
+ const destPath = join(dest, entry.name);
149
+ if (entry.isDirectory()) {
150
+ await mergeDirectory(srcPath, destPath);
151
+ }
152
+ else if (!(await pathExists(destPath))) {
153
+ await fs.copyFile(srcPath, destPath);
154
+ }
155
+ });
156
+ await Promise.all(ops);
157
+ }
252
158
  /**
253
159
  * Install template with IDE-specific folder selection.
254
- * Supports selective installation - only installs items that don't already exist.
255
160
  *
256
161
  * Template structure:
257
- * - Non-dot folders (e.g., _bmad/, GSR/) are installed if not already present
258
- * - Dot folders (e.g., .claude/, .windsurf/) are installed only if matching IDE flag and not already present
162
+ * - Non-dot folders (e.g., _bmad/, GSR/) .aiwcli/ (always overwritten)
163
+ * - _shared/ .aiwcli/_shared/ (always overwritten)
164
+ * - IDE dot folders (e.g., .claude/) → decomposed into method-owned subdirs
165
+ *
166
+ * Settings reconstruction is handled separately by the caller via reconstructIdeSettings().
259
167
  *
260
168
  * @param config - Installation configuration
261
- * @param skipExisting - If true, skip items that already exist (default: true for regeneration support)
262
- * @returns Installation result with list of installed and skipped folders
169
+ * @returns Installation result with list of installed folders
263
170
  * @throws Error if template doesn't exist or requested IDE folder not found
264
171
  */
265
- export async function installTemplate(config, skipExisting = true) {
172
+ export async function installTemplate(config) {
266
173
  const { templateName, targetDir, ides, templatePath } = config;
267
174
  // Verify template exists
268
175
  try {
@@ -295,108 +202,77 @@ export async function installTemplate(config, skipExisting = true) {
295
202
  `Available: ${availableIdes.join(', ')}`);
296
203
  }
297
204
  const installedFolders = [];
298
- const skippedFolders = [];
299
- const mergedFolders = [];
300
- let mergedFileCount = 0;
301
205
  // Create .aiwcli container folder for method-specific files
302
206
  const resolver = new IdePathResolver(targetDir);
303
207
  const containerDir = resolver.getAiwcliContainer();
304
208
  await fs.mkdir(containerDir, { recursive: true });
305
- // Install non-dot folders into .aiwcli/ container (skip if already exist and skipExisting is true)
209
+ // Install non-dot folders into .aiwcli/ container (always overwrite)
306
210
  const nonDotInstalls = nonDotFolders.map(async (folder) => {
307
211
  const srcPath = join(templatePath, folder);
308
- // Destination is inside .aiwcli/ container
309
212
  const destPath = join(containerDir, folder);
310
- if (skipExisting && (await pathExists(destPath))) {
311
- return { folder, skipped: true };
312
- }
313
213
  await copyDir(srcPath, destPath);
314
- return { folder, skipped: false };
214
+ return folder;
315
215
  });
316
216
  const nonDotResults = await Promise.all(nonDotInstalls);
317
- for (const result of nonDotResults) {
318
- if (result.skipped) {
319
- skippedFolders.push(result.folder);
320
- }
321
- else {
322
- installedFolders.push(result.folder);
323
- }
324
- }
217
+ installedFolders.push(...nonDotResults);
325
218
  // Install root-level _shared directory (shared across all templates)
326
- // This is at templates/_shared, not inside the specific template directory
327
219
  // Exclude IDE config folders (.claude, .windsurf) - they are used for settings merging only
328
220
  const templatesRoot = dirname(templatePath);
329
221
  const rootSharedSrc = join(templatesRoot, '_shared');
330
222
  const rootSharedDest = join(containerDir, '_shared');
331
223
  if (await pathExists(rootSharedSrc)) {
332
- if (skipExisting && (await pathExists(rootSharedDest))) {
333
- skippedFolders.push('_shared');
334
- }
335
- else {
336
- await copyDir(rootSharedSrc, rootSharedDest, true); // excludeIdeFolders = true
337
- installedFolders.push('_shared');
338
- }
339
- // Merge shared IDE folders (commands, workflows) into project IDE folders
340
- // This handles _shared/.claude/, _shared/.windsurf/, etc.
224
+ await copyDir(rootSharedSrc, rootSharedDest, true); // excludeIdeFolders = true
225
+ installedFolders.push('_shared');
226
+ // Copy shared IDE content (e.g., _shared/.claude/commands/handoff.md)
227
+ // These are non-method-owned files that live in IDE folders
341
228
  const sharedIdeInstalls = ides.map(async (ide) => {
342
229
  const sharedIdeFolder = join(rootSharedSrc, `.${ide}`);
343
230
  if (await pathExists(sharedIdeFolder)) {
344
231
  const destIdeFolder = resolver.getIdeDir(ide);
345
232
  await fs.mkdir(destIdeFolder, { recursive: true });
346
- // Recursively copy, but skip files that already exist
233
+ // Merge shared IDE content, skipping files that already exist
347
234
  await mergeDirectory(sharedIdeFolder, destIdeFolder);
348
235
  }
349
236
  });
350
237
  await Promise.all(sharedIdeInstalls);
351
238
  }
352
- // Install matching IDE folders
353
- // If folder exists, merge content recursively by looking for method name folders
239
+ // Install method-owned IDE content (decomposed approach)
240
+ // Instead of copying entire .claude/ from template, only copy method-namespaced subdirectories
354
241
  const ideInstalls = ides.map(async (ide) => {
355
242
  const folderName = dotFolders.get(ide);
356
- if (folderName) {
357
- const srcPath = join(templatePath, folderName);
358
- const destPath = resolver.getIdeDir(ide);
359
- if (await pathExists(destPath)) {
360
- if (skipExisting) {
361
- // Folder exists - merge template content by finding method-named folders
362
- const mergeResult = await mergeTemplateContent(srcPath, destPath, templateName);
363
- return {
364
- folder: folderName,
365
- skipped: false,
366
- merged: true,
367
- mergedFiles: mergeResult.copiedFiles.length,
368
- };
369
- }
370
- // skipExisting is false, so overwrite
371
- await copyDir(srcPath, destPath);
372
- return { folder: folderName, skipped: false, merged: false, mergedFiles: 0 };
243
+ if (!folderName)
244
+ return null;
245
+ const srcIdePath = join(templatePath, folderName);
246
+ const destIdePath = resolver.getIdeDir(ide);
247
+ await fs.mkdir(destIdePath, { recursive: true });
248
+ // Scan the template IDE folder for subdirectories and copy method-owned content
249
+ const ideEntries = await fs.readdir(srcIdePath, { withFileTypes: true });
250
+ const subdirOps = ideEntries
251
+ .filter((entry) => entry.isDirectory())
252
+ .map(async (entry) => {
253
+ const subdirSrc = join(srcIdePath, entry.name);
254
+ const subdirDest = join(destIdePath, entry.name);
255
+ // Check for method-namespaced child within this subdirectory
256
+ const methodChildSrc = join(subdirSrc, templateName);
257
+ if (await pathExists(methodChildSrc)) {
258
+ // Copy only the method-namespaced subdirectory (overwrite)
259
+ const methodChildDest = join(subdirDest, templateName);
260
+ await copyDir(methodChildSrc, methodChildDest);
373
261
  }
374
- await copyDir(srcPath, destPath);
375
- return { folder: folderName, skipped: false, merged: false, mergedFiles: 0 };
376
- }
377
- return null;
262
+ else {
263
+ // No method-namespaced child copy the entire subdirectory, merging with existing
264
+ await mergeDirectory(subdirSrc, subdirDest);
265
+ }
266
+ });
267
+ await Promise.all(subdirOps);
268
+ return folderName;
378
269
  });
379
270
  const ideResults = (await Promise.all(ideInstalls)).filter((result) => result !== null);
380
- for (const result of ideResults) {
381
- if (result.merged) {
382
- mergedFolders.push(result.folder);
383
- mergedFileCount += result.mergedFiles;
384
- }
385
- else if (result.skipped) {
386
- skippedFolders.push(result.folder);
387
- }
388
- else {
389
- installedFolders.push(result.folder);
390
- }
391
- }
392
- // Settings merging is now handled by the caller via mergeMethodsSettings()
393
- // This allows unified merging of _shared + method-specific settings
271
+ installedFolders.push(...ideResults);
272
+ // Settings reconstruction is handled by the caller via reconstructIdeSettings()
394
273
  return {
395
274
  installedFolders,
396
- skippedFolders,
397
- mergedFolders,
398
- mergedFileCount,
399
- sharedSettingsMerged: false, // Deprecated, kept for backwards compatibility
275
+ sharedSettingsMerged: false,
400
276
  templatePath,
401
277
  };
402
278
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Unified reconstruction of shared IDE settings files.
3
+ *
4
+ * Both `aiw init` and `aiw clear` use the same operation: reconstruct shared
5
+ * settings from the union of all active templates. Install adds a template to
6
+ * the list; clear removes one. The reconstruction logic is identical.
7
+ *
8
+ * Template files fall into two categories:
9
+ * 1. **Method-owned** — lives in method-namespaced paths (e.g., `.claude/commands/cc-native/`),
10
+ * owned exclusively by one template. Handled by copy/delete, not by this module.
11
+ * 2. **Shared** — lives in common locations (e.g., `settings.json`), multiple templates
12
+ * contribute. Handled by this module via reconstruction from source.
13
+ *
14
+ * @module lib/template-settings-reconstructor
15
+ */
16
+ /**
17
+ * Reconstruct .claude/settings.json and .windsurf/hooks.json from the union
18
+ * of all specified templates.
19
+ *
20
+ * The function:
21
+ * 1. Starts with empty settings
22
+ * 2. Merges _shared template settings (always included)
23
+ * 3. For each active template, merges its template-source settings
24
+ * 4. Writes the result to the IDE settings file
25
+ *
26
+ * Uses mergeClaudeSettings() from hooks-merger.ts for dedup-aware merging.
27
+ *
28
+ * Install calls: reconstructIdeSettings(targetDir, [...existingTemplates, newTemplate], ides)
29
+ * Clear calls: reconstructIdeSettings(targetDir, existingTemplates.filter(t => t !== removed), ides)
30
+ *
31
+ * @param targetDir - Project root directory
32
+ * @param activeTemplates - Template names to include (e.g., ['cc-native', 'bmad'])
33
+ * @param ides - IDEs to reconstruct for (e.g., ['claude', 'windsurf'])
34
+ */
35
+ export declare function reconstructIdeSettings(targetDir: string, activeTemplates: string[], ides: string[]): Promise<void>;