-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathinit.ts
More file actions
367 lines (326 loc) · 11.3 KB
/
init.ts
File metadata and controls
367 lines (326 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { execSync } from 'child_process';
import inquirer from 'inquirer';
import { ConfigManager } from '../lib/Config';
import { TemplateManager } from '../lib/TemplateManager';
import { EnvironmentSelector } from '../lib/EnvironmentSelector';
import { PhaseSelector } from '../lib/PhaseSelector';
import { SkillManager } from '../lib/SkillManager';
import { loadInitTemplate, InitTemplateConfig, InitTemplateSkill } from '../lib/InitTemplate';
import { writeGitignoreWithAiDevkitBlock } from '../lib/gitignoreArtifacts';
import { EnvironmentCode, PHASE_DISPLAY_NAMES, Phase, DEFAULT_DOCS_DIR } from '../types';
import { isValidEnvironmentCode } from '../util/env';
import { ui } from '../util/terminal-ui';
function isGitAvailable(): boolean {
try {
execSync('git --version', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function isInsideGitWorkTree(): boolean {
if (!isGitAvailable()) {
return false;
}
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function ensureGitRepository(): void {
if (!isGitAvailable()) {
ui.warning(
'Git is not installed or not available on the PATH. Skipping repository initialization.'
);
return;
}
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
} catch {
try {
execSync('git init', { stdio: 'ignore' });
ui.success('Initialized a new git repository');
} catch (error) {
ui.error(
`Failed to initialize git repository: ${error instanceof Error ? error.message : error}`
);
}
}
}
interface InitOptions {
environment?: EnvironmentCode[] | string;
all?: boolean;
phases?: string;
template?: string;
docsDir?: string;
gitignoreArtifacts?: boolean;
}
async function resolveShouldGitignoreArtifacts(
options: InitOptions,
templateConfig: InitTemplateConfig | null
): Promise<boolean> {
if (options.gitignoreArtifacts === true) {
return true;
}
if (templateConfig?.gitignoreArtifacts === true) {
return true;
}
if (templateConfig?.gitignoreArtifacts === false) {
return false;
}
if (process.stdin.isTTY) {
const { addGitignore } = await inquirer.prompt([
{
type: 'confirm',
name: 'addGitignore',
message:
'Add .ai-devkit.json, your AI docs folder, and installed slash-command folders (e.g. .cursor/commands, .opencode/commands) to .gitignore? They will not be shared when you push to git.',
default: false
}
]);
return Boolean(addGitignore);
}
return false;
}
function normalizeEnvironmentOption(
environment: EnvironmentCode[] | string | undefined
): EnvironmentCode[] {
if (!environment) {
return [];
}
if (Array.isArray(environment)) {
return environment;
}
return environment
.split(',')
.map(value => value.trim())
.filter((value): value is EnvironmentCode => value.length > 0);
}
interface TemplateSkillInstallResult {
registry: string;
skill: string;
status: 'installed' | 'skipped' | 'failed';
reason?: string;
}
async function installTemplateSkills(
skillManager: SkillManager,
skills: InitTemplateSkill[]
): Promise<TemplateSkillInstallResult[]> {
const seen = new Set<string>();
const results: TemplateSkillInstallResult[] = [];
for (const entry of skills) {
const dedupeKey = `${entry.registry}::${entry.skill}`;
if (seen.has(dedupeKey)) {
results.push({
registry: entry.registry,
skill: entry.skill,
status: 'skipped',
reason: 'Duplicate skill entry in template'
});
continue;
}
seen.add(dedupeKey);
try {
await skillManager.addSkill(entry.registry, entry.skill);
results.push({
registry: entry.registry,
skill: entry.skill,
status: 'installed'
});
} catch (error) {
results.push({
registry: entry.registry,
skill: entry.skill,
status: 'failed',
reason: error instanceof Error ? error.message : String(error)
});
}
}
return results;
}
export async function initCommand(options: InitOptions) {
const configManager = new ConfigManager();
const templateManager = new TemplateManager();
const environmentSelector = new EnvironmentSelector();
const phaseSelector = new PhaseSelector();
const skillManager = new SkillManager(configManager, environmentSelector);
const templatePath = options.template?.trim();
const hasTemplate = Boolean(templatePath);
const templateConfig = hasTemplate
? await loadInitTemplate(templatePath as string).catch(error => {
ui.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
return null;
})
: null;
if (hasTemplate && !templateConfig) {
return;
}
ensureGitRepository();
if (await configManager.exists() && !hasTemplate) {
const { shouldContinue } = await inquirer.prompt([
{
type: 'confirm',
name: 'shouldContinue',
message: 'AI DevKit is already initialized. Do you want to reconfigure?',
default: false
}
]);
if (!shouldContinue) {
ui.warning('Initialization cancelled.');
return;
}
} else if (await configManager.exists() && hasTemplate) {
ui.warning('AI DevKit is already initialized. Reconfiguring from template.');
}
let selectedEnvironments: EnvironmentCode[] = normalizeEnvironmentOption(options.environment);
if (selectedEnvironments.length === 0 && templateConfig?.environments?.length) {
selectedEnvironments = templateConfig.environments;
}
if (selectedEnvironments.length === 0) {
ui.info('AI Environment Setup');
selectedEnvironments = await environmentSelector.selectEnvironments();
}
if (selectedEnvironments.length === 0) {
ui.warning('No environments selected. Initialization cancelled.');
return;
}
for (const envCode of selectedEnvironments) {
if (!isValidEnvironmentCode(envCode)) {
ui.error(`Invalid environment code: ${envCode}`);
return;
}
}
const existingEnvironments: EnvironmentCode[] = [];
for (const envId of selectedEnvironments) {
if (await templateManager.checkEnvironmentExists(envId)) {
existingEnvironments.push(envId);
}
}
let shouldProceedWithSetup = true;
if (existingEnvironments.length > 0) {
ui.warning(`The following environments are already set up: ${existingEnvironments.join(', ')}`);
if (hasTemplate) {
ui.warning('Template mode enabled: proceeding with overwrite of selected environments.');
} else {
shouldProceedWithSetup = await environmentSelector.confirmOverride(existingEnvironments);
}
}
if (!shouldProceedWithSetup) {
ui.warning('Environment setup cancelled.');
return;
}
let selectedPhases: Phase[] = [];
if (options.all || options.phases) {
selectedPhases = await phaseSelector.selectPhases(options.all, options.phases);
} else if (templateConfig?.phases?.length) {
selectedPhases = templateConfig.phases;
} else {
selectedPhases = await phaseSelector.selectPhases();
}
if (selectedPhases.length === 0) {
ui.warning('No phases selected. Nothing to initialize.');
return;
}
let docsDir = DEFAULT_DOCS_DIR;
if (options.docsDir?.trim()) {
docsDir = options.docsDir.trim();
} else if (templateConfig?.paths?.docs) {
docsDir = templateConfig.paths.docs;
}
const phaseTemplateManager = new TemplateManager({ docsDir });
ui.text('Initializing AI DevKit...', { breakline: true });
let config = await configManager.read();
if (!config) {
config = await configManager.create();
ui.success('Created configuration file');
}
if (docsDir !== DEFAULT_DOCS_DIR) {
await configManager.update({ paths: { docs: docsDir } });
}
await configManager.setEnvironments(selectedEnvironments);
ui.success('Updated configuration with selected environments');
environmentSelector.displaySelectionSummary(selectedEnvironments);
phaseSelector.displaySelectionSummary(selectedPhases);
if (hasTemplate && templateConfig) {
ui.info(`Template mode: ${templatePath}`);
if (templateConfig.skills?.length) {
ui.info(`Template skills to install: ${templateConfig.skills.length}`);
}
}
ui.text('Setting up environment templates...', { breakline: true });
const envFiles = await phaseTemplateManager.setupMultipleEnvironments(selectedEnvironments);
envFiles.forEach(file => {
ui.success(`Created ${file}`);
});
for (const phase of selectedPhases) {
const exists = await phaseTemplateManager.fileExists(phase);
let shouldCopy = true;
if (exists) {
if (hasTemplate) {
ui.warning(`${PHASE_DISPLAY_NAMES[phase]} already exists. Overwriting in template mode.`);
} else {
const { overwrite } = await inquirer.prompt([
{
type: 'confirm',
name: 'overwrite',
message: `${PHASE_DISPLAY_NAMES[phase]} already exists. Overwrite?`,
default: false
}
]);
shouldCopy = overwrite;
}
}
if (shouldCopy) {
await phaseTemplateManager.copyPhaseTemplate(phase);
await configManager.addPhase(phase);
ui.success(`Created ${phase} phase`);
} else {
ui.warning(`Skipped ${phase} phase`);
}
}
if (templateConfig?.skills?.length) {
ui.text('Installing skills from template...', { breakline: true });
const skillResults = await installTemplateSkills(skillManager, templateConfig.skills);
const installedCount = skillResults.filter(result => result.status === 'installed').length;
const skippedCount = skillResults.filter(result => result.status === 'skipped').length;
const failedResults = skillResults.filter(result => result.status === 'failed');
if (installedCount > 0) {
ui.success(`Installed ${installedCount} skill(s) from template.`);
}
if (skippedCount > 0) {
ui.warning(`Skipped ${skippedCount} duplicate skill entry(ies) from template.`);
}
if (failedResults.length > 0) {
ui.warning(
`${failedResults.length} skill install(s) failed. Continuing with warnings as configured.`
);
failedResults.forEach(result => {
ui.warning(`${result.registry}/${result.skill}: ${result.reason || 'Unknown error'}`);
});
}
}
const shouldGitignore = await resolveShouldGitignoreArtifacts(options, templateConfig);
if (shouldGitignore) {
if (!isInsideGitWorkTree()) {
ui.warning('Not inside a git repository; skipped updating .gitignore for AI DevKit artifacts.');
} else {
try {
await writeGitignoreWithAiDevkitBlock(process.cwd(), docsDir);
ui.success('Updated .gitignore to exclude AI DevKit artifacts (not shared via git).');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
ui.error(`Failed to update .gitignore: ${message}`);
process.exitCode = 1;
}
}
}
ui.text('AI DevKit initialized successfully!', { breakline: true });
ui.info('Next steps:');
ui.text(` • Review and customize templates in ${docsDir}/`);
ui.text(' • Your AI environments are ready to use with the generated configurations');
ui.text(' • Run `ai-devkit phase <name>` to add more phases later');
ui.text(' • Run `ai-devkit init` again to add more environments\n');
}