forked from MrLesk/Backlog.md
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.ts
More file actions
301 lines (287 loc) · 10.6 KB
/
Copy pathinit.ts
File metadata and controls
301 lines (287 loc) · 10.6 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
import { spawn } from "bun";
import {
type AgentInstructionFile,
addAgentInstructions,
ensureMcpGuidelines,
installClaudeAgent,
} from "../agent-instructions.ts";
import { DEFAULT_INIT_CONFIG } from "../constants/index.ts";
import type { BacklogConfig } from "../types/index.ts";
import { normalizeProjectBacklogDirectory } from "../utils/backlog-directory.ts";
import type { Core } from "./backlog.ts";
export const MCP_SERVER_NAME = "backlog";
export const MCP_GUIDE_URL = "https://github.com/MrLesk/Backlog.md#-mcp-integration-model-context-protocol";
export type IntegrationMode = "mcp" | "cli" | "none";
export type McpClient = "claude" | "codex" | "gemini" | "kiro" | "guide";
export interface InitializeProjectOptions {
projectName: string;
backlogDirectory?: string;
backlogDirectorySource?: "backlog" | ".backlog" | "custom";
configLocation?: "folder" | "root";
integrationMode: IntegrationMode;
mcpClients?: McpClient[];
agentInstructions?: AgentInstructionFile[];
installClaudeAgent?: boolean;
advancedConfig?: {
checkActiveBranches?: boolean;
remoteOperations?: boolean;
activeBranchDays?: number;
bypassGitHooks?: boolean;
autoCommit?: boolean;
zeroPaddedIds?: number;
defaultEditor?: string;
definitionOfDone?: string[];
defaultPort?: number;
autoOpenBrowser?: boolean;
/** Custom task prefix (e.g., "JIRA"). Only set during first init, read-only after. */
taskPrefix?: string;
};
/** Existing config for re-initialization */
existingConfig?: BacklogConfig | null;
}
export interface InitializeProjectResult {
success: boolean;
projectName: string;
isReInitialization: boolean;
config: BacklogConfig;
mcpResults?: Record<string, string>;
}
async function runMcpClientCommand(label: string, command: string, args: string[]): Promise<string> {
try {
const child = spawn({
cmd: [command, ...args],
stdout: "pipe",
stderr: "pipe",
});
const exitCode = await child.exited;
if (exitCode !== 0) {
throw new Error(`Command exited with code ${exitCode}`);
}
return `Added Backlog MCP server to ${label}`;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`Unable to configure ${label} automatically (${message}). Run manually: ${command} ${args.join(" ")}`,
);
}
}
/**
* Core initialization logic shared between CLI and browser.
* Both CLI and browser validate input before calling this function.
*/
export async function initializeProject(
core: Core,
options: InitializeProjectOptions,
): Promise<InitializeProjectResult> {
const {
projectName,
integrationMode,
mcpClients = [],
agentInstructions = [],
installClaudeAgent: installClaudeAgentFlag = false,
advancedConfig = {},
existingConfig,
} = options;
const isReInitialization = !!existingConfig;
const projectRoot = core.filesystem.rootDir;
const hasDefaultEditorOverride = Object.hasOwn(advancedConfig, "defaultEditor");
const hasZeroPaddedIdsOverride = Object.hasOwn(advancedConfig, "zeroPaddedIds");
const hasDefinitionOfDoneOverride = Object.hasOwn(advancedConfig, "definitionOfDone");
// Build config, preserving existing values for re-initialization.
// Re-init should be idempotent for fields that init does not explicitly manage.
const d = DEFAULT_INIT_CONFIG;
const baseConfig: BacklogConfig = {
projectName,
statuses: ["To Do", "In Progress", "Done"],
labels: [],
defaultStatus: "To Do",
dateFormat: "yyyy-mm-dd",
maxColumnWidth: 20,
autoCommit: advancedConfig.autoCommit ?? existingConfig?.autoCommit ?? d.autoCommit,
remoteOperations: advancedConfig.remoteOperations ?? existingConfig?.remoteOperations ?? d.remoteOperations,
bypassGitHooks: advancedConfig.bypassGitHooks ?? existingConfig?.bypassGitHooks ?? d.bypassGitHooks,
checkActiveBranches:
advancedConfig.checkActiveBranches ?? existingConfig?.checkActiveBranches ?? d.checkActiveBranches,
activeBranchDays: advancedConfig.activeBranchDays ?? existingConfig?.activeBranchDays ?? d.activeBranchDays,
defaultPort: advancedConfig.defaultPort ?? existingConfig?.defaultPort ?? d.defaultPort,
autoOpenBrowser: advancedConfig.autoOpenBrowser ?? existingConfig?.autoOpenBrowser ?? d.autoOpenBrowser,
taskResolutionStrategy: existingConfig?.taskResolutionStrategy || "most_recent",
// Preserve existing prefixes on re-init, or use custom prefix if provided during first init
prefixes: existingConfig?.prefixes || {
task: advancedConfig.taskPrefix || "task",
},
};
const config: BacklogConfig = {
...baseConfig,
...(existingConfig ?? {}),
projectName,
autoCommit: advancedConfig.autoCommit ?? existingConfig?.autoCommit ?? d.autoCommit,
remoteOperations: advancedConfig.remoteOperations ?? existingConfig?.remoteOperations ?? d.remoteOperations,
bypassGitHooks: advancedConfig.bypassGitHooks ?? existingConfig?.bypassGitHooks ?? d.bypassGitHooks,
checkActiveBranches:
advancedConfig.checkActiveBranches ?? existingConfig?.checkActiveBranches ?? d.checkActiveBranches,
activeBranchDays: advancedConfig.activeBranchDays ?? existingConfig?.activeBranchDays ?? d.activeBranchDays,
defaultPort: advancedConfig.defaultPort ?? existingConfig?.defaultPort ?? d.defaultPort,
autoOpenBrowser: advancedConfig.autoOpenBrowser ?? existingConfig?.autoOpenBrowser ?? d.autoOpenBrowser,
prefixes: existingConfig?.prefixes || {
task: advancedConfig.taskPrefix || "task",
},
...(hasDefaultEditorOverride && advancedConfig.defaultEditor
? { defaultEditor: advancedConfig.defaultEditor }
: {}),
...(hasZeroPaddedIdsOverride && typeof advancedConfig.zeroPaddedIds === "number" && advancedConfig.zeroPaddedIds > 0
? { zeroPaddedIds: advancedConfig.zeroPaddedIds }
: {}),
...(hasDefinitionOfDoneOverride && Array.isArray(advancedConfig.definitionOfDone)
? { definitionOfDone: [...advancedConfig.definitionOfDone] }
: {}),
};
// Preserve all non-init-managed fields, but allow init-managed optional fields to be explicitly cleared.
if (hasDefaultEditorOverride && !advancedConfig.defaultEditor) {
delete config.defaultEditor;
}
if (
hasZeroPaddedIdsOverride &&
!(typeof advancedConfig.zeroPaddedIds === "number" && advancedConfig.zeroPaddedIds > 0)
) {
delete config.zeroPaddedIds;
}
if (hasDefinitionOfDoneOverride && !Array.isArray(advancedConfig.definitionOfDone)) {
delete config.definitionOfDone;
}
// Create structure and save config
if (isReInitialization) {
await core.filesystem.saveConfig(config);
} else {
const normalizedBacklogDirectory = normalizeProjectBacklogDirectory(options.backlogDirectory);
const inferredBacklogDirectorySource = normalizedBacklogDirectory
? normalizedBacklogDirectory === ".backlog"
? ".backlog"
: normalizedBacklogDirectory === "backlog"
? "backlog"
: "custom"
: undefined;
if (
options.backlogDirectorySource &&
inferredBacklogDirectorySource &&
options.backlogDirectorySource !== inferredBacklogDirectorySource
) {
throw new Error("Backlog directory source and backlog directory value must agree.");
}
const effectiveBacklogDirectorySource = options.backlogDirectorySource ?? inferredBacklogDirectorySource;
if (effectiveBacklogDirectorySource === "custom" && !normalizedBacklogDirectory) {
throw new Error("Backlog directory must be a valid project-relative path.");
}
const effectiveConfigLocation =
options.configLocation ?? (effectiveBacklogDirectorySource === "custom" ? "root" : "folder");
if (effectiveBacklogDirectorySource === "custom" && effectiveConfigLocation !== "root") {
throw new Error("Custom backlog directories require root config discovery.");
}
const selectedBacklogDirectory =
normalizedBacklogDirectory ??
(effectiveBacklogDirectorySource === ".backlog"
? ".backlog"
: effectiveBacklogDirectorySource === "backlog"
? "backlog"
: "backlog");
core.filesystem.setBacklogDirectory(selectedBacklogDirectory);
core.filesystem.setConfigLocation(effectiveConfigLocation);
await core.filesystem.ensureBacklogStructure();
await core.filesystem.saveConfig(config);
await core.ensureConfigLoaded();
}
const mcpResults: Record<string, string> = {};
// Handle MCP integration
if (integrationMode === "mcp" && mcpClients.length > 0) {
for (const client of mcpClients) {
try {
if (client === "claude") {
const result = await runMcpClientCommand("Claude Code", "claude", [
"mcp",
"add",
"-s",
"user",
MCP_SERVER_NAME,
"--",
"backlog",
"mcp",
"start",
]);
mcpResults.claude = result;
await ensureMcpGuidelines(projectRoot, "CLAUDE.md");
} else if (client === "codex") {
const result = await runMcpClientCommand("OpenAI Codex", "codex", [
"mcp",
"add",
MCP_SERVER_NAME,
"backlog",
"mcp",
"start",
]);
mcpResults.codex = result;
await ensureMcpGuidelines(projectRoot, "AGENTS.md");
} else if (client === "gemini") {
const result = await runMcpClientCommand("Gemini CLI", "gemini", [
"mcp",
"add",
"-s",
"user",
MCP_SERVER_NAME,
"backlog",
"mcp",
"start",
]);
mcpResults.gemini = result;
await ensureMcpGuidelines(projectRoot, "GEMINI.md");
} else if (client === "kiro") {
const result = await runMcpClientCommand("Kiro", "kiro-cli", [
"mcp",
"add",
"--scope",
"global",
"--name",
MCP_SERVER_NAME,
"--command",
"backlog",
"--args",
"mcp,start",
]);
mcpResults.kiro = result;
await ensureMcpGuidelines(projectRoot, "AGENTS.md");
} else if (client === "guide") {
mcpResults.guide = `Setup guide: ${MCP_GUIDE_URL}`;
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
mcpResults[client] = `Failed: ${message}`;
}
}
}
// Handle CLI integration - agent instruction files
if (integrationMode === "cli" && agentInstructions.length > 0) {
try {
await addAgentInstructions(projectRoot, core.gitOps, agentInstructions, config.autoCommit);
mcpResults.agentFiles = `Created: ${agentInstructions.join(", ")}`;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
mcpResults.agentFiles = `Failed: ${message}`;
}
}
// Handle Claude agent installation
if (integrationMode === "cli" && installClaudeAgentFlag) {
try {
await installClaudeAgent(projectRoot);
mcpResults.claudeAgent = "Installed to .claude/agents/";
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
mcpResults.claudeAgent = `Failed: ${message}`;
}
}
return {
success: true,
projectName,
isReInitialization,
config,
mcpResults: Object.keys(mcpResults).length > 0 ? mcpResults : undefined,
};
}