@mrpatronz/nexusflow 0.1.4 → 0.1.6

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 (49) hide show
  1. package/dist/commands/create.d.ts.map +1 -1
  2. package/dist/commands/create.js +26 -0
  3. package/dist/commands/create.js.map +1 -1
  4. package/dist/commands/open.d.ts.map +1 -1
  5. package/dist/commands/open.js +27 -1
  6. package/dist/commands/open.js.map +1 -1
  7. package/dist/commands/pack.d.ts +7 -0
  8. package/dist/commands/pack.d.ts.map +1 -0
  9. package/dist/commands/pack.js +64 -0
  10. package/dist/commands/pack.js.map +1 -0
  11. package/dist/core/graph.d.ts +35 -0
  12. package/dist/core/graph.d.ts.map +1 -0
  13. package/dist/core/graph.js +281 -0
  14. package/dist/core/graph.js.map +1 -0
  15. package/dist/core/packer.d.ts +13 -0
  16. package/dist/core/packer.d.ts.map +1 -0
  17. package/dist/core/packer.js +84 -0
  18. package/dist/core/packer.js.map +1 -0
  19. package/dist/core/worktree.d.ts.map +1 -1
  20. package/dist/core/worktree.js +36 -2
  21. package/dist/core/worktree.js.map +1 -1
  22. package/dist/generators/index.d.ts.map +1 -1
  23. package/dist/generators/index.js +9 -0
  24. package/dist/generators/index.js.map +1 -1
  25. package/dist/gui/assets/index-io0N2VQx.js +21 -0
  26. package/dist/gui/index.html +1 -1
  27. package/dist/index.js +19 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/mcp/server.d.ts.map +1 -1
  30. package/dist/mcp/server.js +125 -0
  31. package/dist/mcp/server.js.map +1 -1
  32. package/dist/server.d.ts.map +1 -1
  33. package/dist/server.js +22 -0
  34. package/dist/server.js.map +1 -1
  35. package/dist/utils/update-check.js +1 -1
  36. package/gui/src/App.tsx +21 -1
  37. package/package.json +3 -2
  38. package/src/commands/create.ts +29 -0
  39. package/src/commands/open.ts +29 -1
  40. package/src/commands/pack.ts +73 -0
  41. package/src/core/graph.ts +345 -0
  42. package/src/core/packer.ts +107 -0
  43. package/src/core/worktree.ts +42 -6
  44. package/src/generators/index.ts +12 -0
  45. package/src/index.ts +19 -0
  46. package/src/mcp/server.ts +131 -0
  47. package/src/server.ts +25 -0
  48. package/src/utils/update-check.ts +1 -1
  49. package/dist/gui/assets/index-DDn7UKEM.js +0 -21
@@ -0,0 +1,73 @@
1
+ import chalk from 'chalk';
2
+ import ora from 'ora';
3
+ import * as path from 'node:path';
4
+ import * as fs from 'node:fs/promises';
5
+ import { select } from '@inquirer/prompts';
6
+
7
+ import { loadConfig } from '../core/config.js';
8
+ import { listWorkspaces, loadFeatureConfig } from '../core/workspace.js';
9
+ import { packWorkspace } from '../core/packer.js';
10
+
11
+ /**
12
+ * Packs the workspace codebase into a single token-efficient XML file.
13
+ */
14
+ export async function packCommand(
15
+ workspaceArg?: string,
16
+ options: { compress?: boolean } = {}
17
+ ): Promise<void> {
18
+ console.log(chalk.bold.cyan('\nšŸ“¦ NexusFlow — Codebase Context Packing\n'));
19
+
20
+ const workspacePath = await resolveWorkspace(workspaceArg);
21
+ if (!workspacePath) return;
22
+
23
+ const spinner = ora('Packing workspace repositories using Repomix...').start();
24
+ try {
25
+ const result = await packWorkspace(workspacePath, { compress: options.compress });
26
+ spinner.succeed('Workspace packed successfully!');
27
+
28
+ console.log(`\nšŸ“„ ${chalk.bold('Packed Output File:')} ${chalk.green(result.outputPath)}`);
29
+ console.log(`šŸ“Š ${chalk.bold('Total Files:')} ${result.totalFiles}`);
30
+ console.log(`šŸ”  ${chalk.bold('Total Characters:')} ${result.totalCharacters}`);
31
+ console.log(`šŸ’¾ ${chalk.bold('File Size:')} ${(result.fileSize / 1024).toFixed(2)} KB\n`);
32
+ } catch (error: any) {
33
+ spinner.fail('Failed to pack workspace');
34
+ console.error(chalk.red(` Error: ${error.message}`));
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Resolves the workspace path from argument, cwd, or list.
40
+ */
41
+ async function resolveWorkspace(workspaceArg?: string): Promise<string | null> {
42
+ if (workspaceArg) {
43
+ const absolutePath = path.resolve(workspaceArg);
44
+ try {
45
+ await fs.access(path.join(absolutePath, 'nexusflow.json'));
46
+ return absolutePath;
47
+ } catch {
48
+ console.error(chalk.red(`āœ– Invalid workspace: No nexusflow.json found at ${absolutePath}`));
49
+ return null;
50
+ }
51
+ }
52
+
53
+ const cwdFeature = await loadFeatureConfig(process.cwd());
54
+ if (cwdFeature) return process.cwd();
55
+
56
+ const config = await loadConfig();
57
+ const workspaces = await listWorkspaces(config.workspacesDir);
58
+
59
+ if (workspaces.length === 0) {
60
+ console.log(chalk.yellow('No workspaces found.\n'));
61
+ return null;
62
+ }
63
+
64
+ const selected = await select({
65
+ message: 'Select a workspace to pack:',
66
+ choices: workspaces.map((ws) => ({
67
+ name: `${ws.branchName} ${chalk.dim(`(${ws.repos.length} repos)`)}`,
68
+ value: ws.workspacePath,
69
+ })),
70
+ });
71
+
72
+ return selected;
73
+ }
@@ -0,0 +1,345 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { execa } from 'execa';
4
+ import type { WorkspaceContext, RepoInfo } from '../types.js';
5
+
6
+ export interface GraphNode {
7
+ id: string;
8
+ type: 'repo' | 'package' | 'endpoint' | 'port';
9
+ name: string;
10
+ metadata: Record<string, any>;
11
+ }
12
+
13
+ export interface GraphEdge {
14
+ source: string;
15
+ target: string;
16
+ type: 'CONTAINS' | 'DEPENDS_ON' | 'EXPOSES' | 'CALLS';
17
+ metadata?: Record<string, any>;
18
+ }
19
+
20
+ export interface WorkspaceGraph {
21
+ workspaceId: string;
22
+ nodes: GraphNode[];
23
+ edges: GraphEdge[];
24
+ }
25
+
26
+ /**
27
+ * Builds a structural and API interaction graph across all repos in a workspace.
28
+ */
29
+ export async function buildWorkspaceGraph(
30
+ ctx: WorkspaceContext,
31
+ workspacePath: string,
32
+ ): Promise<WorkspaceGraph> {
33
+ const { feature, repos, analysis } = ctx;
34
+ const nodes: GraphNode[] = [];
35
+ const edges: GraphEdge[] = [];
36
+
37
+ // 1. Add Repository Nodes
38
+ for (const repo of repos) {
39
+ const a = analysis?.get(repo.path);
40
+ nodes.push({
41
+ id: `repo:${repo.name}`,
42
+ type: 'repo',
43
+ name: repo.name,
44
+ metadata: {
45
+ path: repo.path,
46
+ techStack: a?.techStack || null,
47
+ description: a?.readmeSummary || '',
48
+ },
49
+ });
50
+ }
51
+
52
+ // 2. Add API Endpoint and Port Nodes, and EXPOSES Edges
53
+ const allEndpoints: { endpointId: string; method: string; path: string; repoName: string }[] = [];
54
+
55
+ if (analysis) {
56
+ for (const repo of repos) {
57
+ const a = analysis.get(repo.path);
58
+ if (!a) continue;
59
+
60
+ // Add Ports
61
+ for (const p of a.ports) {
62
+ const portId = `port:${repo.name}:${p.port}`;
63
+ nodes.push({
64
+ id: portId,
65
+ type: 'port',
66
+ name: `${p.port}`,
67
+ metadata: {
68
+ protocol: p.protocol,
69
+ source: p.source,
70
+ },
71
+ });
72
+ edges.push({
73
+ source: `repo:${repo.name}`,
74
+ target: portId,
75
+ type: 'EXPOSES',
76
+ });
77
+ }
78
+
79
+ // Add API Endpoints
80
+ for (const ep of a.endpoints) {
81
+ const endpointId = `endpoint:${repo.name}:${ep.method}:${ep.path}`;
82
+ nodes.push({
83
+ id: endpointId,
84
+ type: 'endpoint',
85
+ name: `${ep.method} ${ep.path}`,
86
+ metadata: {
87
+ method: ep.method,
88
+ path: ep.path,
89
+ source: ep.source,
90
+ },
91
+ });
92
+ edges.push({
93
+ source: `repo:${repo.name}`,
94
+ target: endpointId,
95
+ type: 'EXPOSES',
96
+ });
97
+
98
+ allEndpoints.push({
99
+ endpointId,
100
+ method: ep.method,
101
+ path: ep.path,
102
+ repoName: repo.name,
103
+ });
104
+ }
105
+
106
+ // Add package dependencies
107
+ for (const dep of a.dependencies) {
108
+ const packageId = `package:${dep.type}:${dep.name}`;
109
+ if (!nodes.some((n) => n.id === packageId)) {
110
+ nodes.push({
111
+ id: packageId,
112
+ type: 'package',
113
+ name: dep.name,
114
+ metadata: {
115
+ manager: dep.type,
116
+ version: dep.version || 'latest',
117
+ },
118
+ });
119
+ }
120
+ edges.push({
121
+ source: `repo:${repo.name}`,
122
+ target: packageId,
123
+ type: 'DEPENDS_ON',
124
+ });
125
+ }
126
+ }
127
+ }
128
+
129
+ // 3. Add inter-repo DEPENDS_ON edges
130
+ if (analysis) {
131
+ const repoAnalyses = new Map(repos.map((r) => [r.path, analysis.get(r.path)?.dependencies || []]));
132
+ const repoNames = new Map(repos.map((r) => [r.path, r.name]));
133
+ const { findInterRepoDependencies } = await import('../analyzers/detect-deps.js');
134
+ const interDeps = findInterRepoDependencies(repoAnalyses, repoNames);
135
+
136
+ for (const [caller, callees] of interDeps) {
137
+ for (const callee of callees) {
138
+ edges.push({
139
+ source: `repo:${caller}`,
140
+ target: `repo:${callee}`,
141
+ type: 'DEPENDS_ON',
142
+ metadata: { relation: 'repo-to-repo' },
143
+ });
144
+ }
145
+ }
146
+ }
147
+
148
+ // 4. Detect CALLS Edges using git grep inside worktrees
149
+ for (const ep of allEndpoints) {
150
+ const pathQuery = ep.path;
151
+ // Skip very short or generic paths to avoid false positives and noise
152
+ if (!pathQuery || pathQuery.length < 4 || pathQuery === '/api' || pathQuery === '/dev') continue;
153
+
154
+ for (const repo of repos) {
155
+ if (repo.name === ep.repoName) continue; // Skip self
156
+
157
+ const worktreePath = path.join(workspacePath, repo.name);
158
+ try {
159
+ await fs.access(worktreePath);
160
+ // Use git grep to find references to this endpoint path in other worktrees
161
+ const { stdout } = await execa('git', ['grep', '-l', '-F', pathQuery], {
162
+ cwd: worktreePath,
163
+ reject: false,
164
+ });
165
+
166
+ if (stdout && stdout.trim()) {
167
+ const files = stdout.split('\n').filter(Boolean);
168
+ edges.push({
169
+ source: `repo:${repo.name}`,
170
+ target: ep.endpointId,
171
+ type: 'CALLS',
172
+ metadata: {
173
+ files,
174
+ reason: `References endpoint path '${pathQuery}'`,
175
+ },
176
+ });
177
+ }
178
+ } catch {
179
+ // Ignore git grep failures
180
+ }
181
+ }
182
+ }
183
+
184
+ return {
185
+ workspaceId: feature.id,
186
+ nodes,
187
+ edges,
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Builds a Mermaid Flowchart representation of the workspace architecture graph.
193
+ */
194
+ export function buildMermaidDiagram(graph: WorkspaceGraph): string {
195
+ const lines: string[] = ['flowchart TD'];
196
+
197
+ lines.push(' classDef repo fill:#3b82f6,stroke:#1d4ed8,stroke-width:2px,color:#fff;');
198
+ lines.push(' classDef endpoint fill:#10b981,stroke:#047857,stroke-width:2px,color:#fff;');
199
+ lines.push(' classDef port fill:#f59e0b,stroke:#b45309,stroke-width:2px,color:#fff;');
200
+ lines.push(' classDef package fill:#8b5cf6,stroke:#6d28d9,stroke-width:2px,color:#fff;');
201
+
202
+ // Render Repo nodes
203
+ for (const n of graph.nodes) {
204
+ if (n.type === 'repo') {
205
+ lines.push(` ${n.id}["šŸ“¦ ${n.name}"]:::repo`);
206
+ }
207
+ }
208
+
209
+ // Render edges between repos
210
+ const repoEdges = graph.edges.filter(
211
+ (e) => e.source.startsWith('repo:') && e.target.startsWith('repo:'),
212
+ );
213
+ for (const e of repoEdges) {
214
+ lines.push(` ${e.source} -->|depends on| ${e.target}`);
215
+ }
216
+
217
+ // Render API calls and endpoint interactions
218
+ const callsEdges = graph.edges.filter((e) => e.type === 'CALLS');
219
+ const referencedEndpointIds = new Set(callsEdges.map((e) => e.target));
220
+
221
+ for (const n of graph.nodes) {
222
+ if (n.type === 'endpoint' && referencedEndpointIds.has(n.id)) {
223
+ lines.push(` ${n.id}["šŸ”Œ ${n.name}"]:::endpoint`);
224
+ }
225
+ }
226
+
227
+ for (const e of callsEdges) {
228
+ lines.push(` ${e.source} -->|calls| ${e.target}`);
229
+ }
230
+
231
+ // Render exposures from endpoints to their parent repos
232
+ const exposesEdges = graph.edges.filter(
233
+ (e) => e.type === 'EXPOSES' && referencedEndpointIds.has(e.target),
234
+ );
235
+ for (const e of exposesEdges) {
236
+ lines.push(` ${e.target} -.->|exposed by| ${e.source}`);
237
+ }
238
+
239
+ return lines.join('\n');
240
+ }
241
+
242
+ /**
243
+ * Formats the graph as a human/LLM-readable markdown guide.
244
+ */
245
+ export function generateGraphMarkdownContent(graph: WorkspaceGraph): string {
246
+ const repoNodes = graph.nodes.filter((n) => n.type === 'repo');
247
+ const mermaid = buildMermaidDiagram(graph);
248
+
249
+ const lines: string[] = [
250
+ `# Workspace Architecture Graph — ${graph.workspaceId}`,
251
+ '',
252
+ '> **Token-Efficient Architecture Guide**: This file defines the entities, dependencies,',
253
+ '> and API call relationships of your multi-repository workspace. Use this map to navigate',
254
+ '> relationships without having to read through all repository directories.',
255
+ '',
256
+ '## Workspace Relations Diagram',
257
+ '',
258
+ '```mermaid',
259
+ mermaid,
260
+ '```',
261
+ '',
262
+ '## šŸ“¦ Repositories',
263
+ '',
264
+ ];
265
+
266
+ for (const repo of repoNodes) {
267
+ lines.push(`### ${repo.name}`);
268
+ lines.push(`- **Path**: \`${repo.metadata.path}\``);
269
+ if (repo.metadata.techStack) {
270
+ const ts = repo.metadata.techStack;
271
+ lines.push(`- **Languages**: ${ts.languages.join(', ')}`);
272
+ if (ts.frameworks.length > 0) {
273
+ lines.push(`- **Frameworks**: ${ts.frameworks.join(', ')}`);
274
+ }
275
+ }
276
+
277
+ // Dependencies
278
+ const deps = graph.edges
279
+ .filter((e) => e.source === repo.id && e.target.startsWith('package:'))
280
+ .map((e) => {
281
+ const pkgNode = graph.nodes.find((n) => n.id === e.target);
282
+ return pkgNode ? `\`${pkgNode.name}\` (${pkgNode.metadata.manager})` : '';
283
+ })
284
+ .filter(Boolean);
285
+
286
+ if (deps.length > 0) {
287
+ lines.push(`- **Dependencies**: ${deps.slice(0, 10).join(', ')}${deps.length > 10 ? ` (+${deps.length - 10} more)` : ''}`);
288
+ }
289
+
290
+ // Exposed APIs
291
+ const exposed = graph.edges
292
+ .filter((e) => e.source === repo.id && e.target.startsWith('endpoint:'))
293
+ .map((e) => {
294
+ const ep = graph.nodes.find((n) => n.id === e.target);
295
+ return ep ? `\`${ep.name}\`` : '';
296
+ })
297
+ .filter(Boolean);
298
+
299
+ if (exposed.length > 0) {
300
+ lines.push(`- **Exposed APIs**: ${exposed.slice(0, 5).join(', ')}${exposed.length > 5 ? ` (+${exposed.length - 5} more)` : ''}`);
301
+ }
302
+
303
+ // API calls made
304
+ const calls = graph.edges
305
+ .filter((e) => e.source === repo.id && e.type === 'CALLS')
306
+ .map((e) => {
307
+ const ep = graph.nodes.find((n) => n.id === e.target);
308
+ return ep ? `\`${ep.name}\` (exposed by \`${ep.id.split(':')[1]}\`)` : '';
309
+ })
310
+ .filter(Boolean);
311
+
312
+ if (calls.length > 0) {
313
+ lines.push(`- **Calls Endpoints**: ${calls.join(', ')}`);
314
+ }
315
+
316
+ lines.push('');
317
+ }
318
+
319
+ return lines.join('\n');
320
+ }
321
+
322
+ /**
323
+ * Builds the graph, writes `nexusflow-graph.json` and `nexusflow-graph.md` to workspace root.
324
+ */
325
+ export async function generateWorkspaceGraphFiles(
326
+ ctx: WorkspaceContext,
327
+ workspacePath: string,
328
+ ): Promise<void> {
329
+ try {
330
+ const graph = await buildWorkspaceGraph(ctx, workspacePath);
331
+
332
+ // Write JSON file
333
+ const jsonPath = path.join(workspacePath, 'nexusflow-graph.json');
334
+ await fs.writeFile(jsonPath, JSON.stringify(graph, null, 2), 'utf-8');
335
+
336
+ // Write MD file
337
+ const mdPath = path.join(workspacePath, 'nexusflow-graph.md');
338
+ const mdContent = generateGraphMarkdownContent(graph);
339
+ await fs.writeFile(mdPath, mdContent, 'utf-8');
340
+
341
+ console.log(' āœ” Generated Workspace Architecture Graph (nexusflow-graph.json / nexusflow-graph.md)');
342
+ } catch (error: any) {
343
+ console.error(' āœ– Failed to generate workspace architecture graph:', error.message);
344
+ }
345
+ }
@@ -0,0 +1,107 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { execa } from 'execa';
4
+ import { loadFeatureConfig } from './workspace.js';
5
+
6
+ export interface PackResult {
7
+ outputPath: string;
8
+ totalFiles: number;
9
+ totalCharacters: number;
10
+ fileSize: number;
11
+ }
12
+
13
+ /**
14
+ * Packs all repositories in a workspace into a single, compressed XML file using Repomix.
15
+ */
16
+ export async function packWorkspace(
17
+ workspacePath: string,
18
+ options: { compress?: boolean } = {}
19
+ ): Promise<PackResult> {
20
+ const feature = await loadFeatureConfig(workspacePath);
21
+ if (!feature) {
22
+ throw new Error(`Workspace not found at ${workspacePath}`);
23
+ }
24
+
25
+ const compress = options.compress !== false; // default true
26
+
27
+ const reposXmlData: { repoName: string; xmlContent: string }[] = [];
28
+
29
+ let totalFilesCount = 0;
30
+ let totalCharsCount = 0;
31
+
32
+ for (const repoPath of feature.repos) {
33
+ const repoName = path.basename(repoPath);
34
+ const worktreePath = path.join(workspacePath, repoName);
35
+
36
+ try {
37
+ await fs.access(worktreePath);
38
+ } catch {
39
+ continue;
40
+ }
41
+
42
+ const tempXmlPath = path.join(workspacePath, `temp-repomix-${repoName}.xml`);
43
+
44
+ // Build repomix arguments
45
+ const args = ['repomix', '--style', 'xml', '--output', tempXmlPath];
46
+ if (compress) {
47
+ args.push('--compress');
48
+ }
49
+
50
+ try {
51
+ // Run repomix inside the worktree directory
52
+ await execa('npx', args, { cwd: worktreePath });
53
+
54
+ // Read output XML
55
+ const xmlContent = await fs.readFile(tempXmlPath, 'utf8');
56
+
57
+ // Estimate file and character counts
58
+ const fileMatches = xmlContent.match(/<file\s+path=/gi) || [];
59
+ totalFilesCount += fileMatches.length;
60
+ totalCharsCount += xmlContent.length;
61
+
62
+ reposXmlData.push({
63
+ repoName,
64
+ xmlContent,
65
+ });
66
+ } catch (error: any) {
67
+ console.error(`Error packing repository ${repoName}:`, error.message);
68
+ } finally {
69
+ // Clean up temporary XML file
70
+ try {
71
+ await fs.unlink(tempXmlPath);
72
+ } catch {
73
+ // ignore
74
+ }
75
+ }
76
+ }
77
+
78
+ // Combine reposXmlData into a single XML structure
79
+ const xmlLines: string[] = [];
80
+ xmlLines.push('<?xml version="1.0" encoding="UTF-8"?>');
81
+ xmlLines.push(`<workspace id="${feature.id}">`);
82
+ xmlLines.push(` <description><![CDATA[${feature.description}]]></description>`);
83
+ xmlLines.push(' <repositories>');
84
+
85
+ for (const repo of reposXmlData) {
86
+ xmlLines.push(` <repository name="${repo.repoName}">`);
87
+ xmlLines.push(repo.xmlContent);
88
+ xmlLines.push(' </repository>');
89
+ }
90
+
91
+ xmlLines.push(' </repositories>');
92
+ xmlLines.push('</workspace>');
93
+ xmlLines.push('');
94
+
95
+ const outputXmlContent = xmlLines.join('\n');
96
+ const outputPath = path.join(workspacePath, 'nexusflow-context.xml');
97
+ await fs.writeFile(outputPath, outputXmlContent, 'utf-8');
98
+
99
+ const stats = await fs.stat(outputPath);
100
+
101
+ return {
102
+ outputPath,
103
+ totalFiles: totalFilesCount,
104
+ totalCharacters: totalCharsCount,
105
+ fileSize: stats.size,
106
+ };
107
+ }
@@ -32,6 +32,23 @@ export async function createWorktree(
32
32
  // Silently ignore fetch failures (e.g., offline or no remote origin)
33
33
  }
34
34
 
35
+ // Update local baseBranch to keep it in sync with remote before branching
36
+ if (fetched) {
37
+ try {
38
+ // Find out if the main repo currently has baseBranch checked out
39
+ const { stdout: currentBranch } = await execa('git', ['branch', '--show-current'], { cwd: repoPath });
40
+ if (currentBranch.trim() === baseBranch) {
41
+ // Safe fast-forward pull
42
+ await execa('git', ['pull', '--ff-only'], { cwd: repoPath });
43
+ } else {
44
+ // Fast-forward local ref from remote ref without checkout
45
+ await execa('git', ['fetch', 'origin', `${baseBranch}:${baseBranch}`], { cwd: repoPath });
46
+ }
47
+ } catch {
48
+ // Ignore failures (e.g. non-fast-forward, uncommitted changes, or no upstream tracking branch)
49
+ }
50
+ }
51
+
35
52
  // Determine starting point: remote branch if fetched successfully and exists, else local branch.
36
53
  let startPoint = baseBranch;
37
54
  if (fetched) {
@@ -43,12 +60,31 @@ export async function createWorktree(
43
60
  }
44
61
  }
45
62
 
46
- // Create the worktree with a new branch based on the start point.
47
- await execa(
48
- 'git',
49
- ['worktree', 'add', targetPath, '-b', branchName, startPoint],
50
- { cwd: repoPath },
51
- );
63
+ // Check if the target branch already exists locally
64
+ let branchExists = false;
65
+ try {
66
+ await execa('git', ['rev-parse', '--verify', branchName], { cwd: repoPath });
67
+ branchExists = true;
68
+ } catch {
69
+ // Branch does not exist locally
70
+ }
71
+
72
+ // Create the worktree
73
+ if (branchExists) {
74
+ // If the branch already exists, checkout the existing branch
75
+ await execa(
76
+ 'git',
77
+ ['worktree', 'add', targetPath, branchName],
78
+ { cwd: repoPath },
79
+ );
80
+ } else {
81
+ // If the branch does not exist, create a new branch based on the start point
82
+ await execa(
83
+ 'git',
84
+ ['worktree', 'add', targetPath, '-b', branchName, startPoint],
85
+ { cwd: repoPath },
86
+ );
87
+ }
52
88
  }
53
89
 
54
90
  /**
@@ -8,6 +8,7 @@ import { generateCopilotConfig } from './copilot.js';
8
8
  import { generateCursorConfig } from './cursor.js';
9
9
  import { buildContextContent } from './base.js';
10
10
  import { generateImplementationPlan } from './plan-generator.js';
11
+ import { generateWorkspaceGraphFiles } from '../core/graph.js';
11
12
 
12
13
  /** Maps each assistant to its generator function and the file it produces. */
13
14
  const GENERATORS: Record<
@@ -156,6 +157,17 @@ export async function generateContextFiles(
156
157
  }
157
158
  }
158
159
 
160
+ // Generate Workspace Architecture Graph
161
+ try {
162
+ await generateWorkspaceGraphFiles(ctx, workspacePath);
163
+ } catch (error) {
164
+ const message = error instanceof Error ? error.message : String(error);
165
+ console.error(
166
+ chalk.red(' āœ–'),
167
+ `Failed to generate workspace architecture graph: ${message}`,
168
+ );
169
+ }
170
+
159
171
  // Generate implementation plan from dependency analysis (if analysis data available)
160
172
  try {
161
173
  await generateImplementationPlan(ctx, workspacePath);
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ import { uiCommand } from './commands/ui.js';
23
23
  import { syncCommand } from './commands/sync.js';
24
24
  import { commitCommand } from './commands/commit.js';
25
25
  import { diffCommand } from './commands/diff.js';
26
+ import { packCommand } from './commands/pack.js';
26
27
  import { mcpRunCommand, mcpSetupCommand } from './commands/mcp.js';
27
28
  import { getCurrentVersion, checkForUpdates, printUpdateBanner } from './utils/update-check.js';
28
29
 
@@ -234,6 +235,24 @@ program
234
235
  }
235
236
  });
236
237
 
238
+ program
239
+ .command('pack')
240
+ .description('Pack the workspace codebase into a single token-efficient XML file for AI consumption')
241
+ .argument('[workspace]', 'Path to workspace (auto-detects from CWD)')
242
+ .option('--no-compress', 'Do not compress files (strip comments, empty lines)')
243
+ .action(async (workspace: string | undefined, options: { compress?: boolean }) => {
244
+ try {
245
+ await packCommand(workspace, options);
246
+ } catch (error) {
247
+ if (error instanceof Error && error.message.includes('User force closed')) {
248
+ console.log('\nCancelled.');
249
+ process.exit(0);
250
+ }
251
+ console.error(error);
252
+ process.exit(1);
253
+ }
254
+ });
255
+
237
256
  const mcp = program.command('mcp').description('Manage the NexusFlow MCP Server for AI assistants');
238
257
 
239
258
  mcp