@mrpatronz/nexusflow 0.1.5 → 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.
@@ -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
+ }
@@ -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
package/src/mcp/server.ts CHANGED
@@ -66,6 +66,42 @@ export async function startMcpServer(workspacePath?: string) {
66
66
  required: ['serviceName'],
67
67
  },
68
68
  },
69
+ {
70
+ name: 'get_workspace_graph',
71
+ description: 'Retrieve the structural architecture graph of the NexusFlow workspace. Contains nodes for repos, packages, API endpoints, and exposed ports, plus relation edges (CONTAINS, DEPENDS_ON, EXPOSES, CALLS). Highly token-efficient for global workspace context.',
72
+ inputSchema: {
73
+ type: 'object',
74
+ properties: {
75
+ workspaceId: {
76
+ type: 'string',
77
+ description: 'Optional ID/branchName of the workspace. If omitted, uses the currently active workspace.',
78
+ },
79
+ },
80
+ },
81
+ },
82
+ {
83
+ name: 'query_workspace_graph',
84
+ description: 'Query the workspace architecture graph by filtering nodes or edges (e.g., node types like "repo", "package", "endpoint", "port", or edge types like "DEPENDS_ON", "EXPOSES", "CALLS"). Reduces token payload by fetching specific architectural paths.',
85
+ inputSchema: {
86
+ type: 'object',
87
+ properties: {
88
+ nodeType: {
89
+ type: 'string',
90
+ enum: ['repo', 'package', 'endpoint', 'port'],
91
+ description: 'Optional node type to filter.',
92
+ },
93
+ edgeType: {
94
+ type: 'string',
95
+ enum: ['DEPENDS_ON', 'EXPOSES', 'CALLS'],
96
+ description: 'Optional edge/relation type to filter.',
97
+ },
98
+ workspaceId: {
99
+ type: 'string',
100
+ description: 'Optional ID/branchName of the workspace. If omitted, uses the currently active workspace.',
101
+ },
102
+ },
103
+ },
104
+ },
69
105
  ],
70
106
  };
71
107
  });
@@ -179,6 +215,101 @@ export async function startMcpServer(workspacePath?: string) {
179
215
  }
180
216
  }
181
217
 
218
+ if (name === 'get_workspace_graph') {
219
+ try {
220
+ const graphPath = path.join(resolvedWorkspacePath, 'nexusflow-graph.json');
221
+
222
+ try {
223
+ await fs.access(graphPath);
224
+ } catch {
225
+ return {
226
+ content: [
227
+ {
228
+ type: 'text',
229
+ text: `Workspace graph file not found at ${graphPath}. Run "nexusflow sync" or rebuild the workspace to generate it.`,
230
+ },
231
+ ],
232
+ isError: true,
233
+ };
234
+ }
235
+
236
+ const content = await fs.readFile(graphPath, 'utf8');
237
+ return {
238
+ content: [
239
+ {
240
+ type: 'text',
241
+ text: content,
242
+ },
243
+ ],
244
+ };
245
+ } catch (error: any) {
246
+ return {
247
+ content: [
248
+ {
249
+ type: 'text',
250
+ text: `Error reading workspace graph: ${error.message}`,
251
+ },
252
+ ],
253
+ isError: true,
254
+ };
255
+ }
256
+ }
257
+
258
+ if (name === 'query_workspace_graph') {
259
+ const nodeType = (args as any).nodeType;
260
+ const edgeType = (args as any).edgeType;
261
+
262
+ try {
263
+ const graphPath = path.join(resolvedWorkspacePath, 'nexusflow-graph.json');
264
+
265
+ try {
266
+ await fs.access(graphPath);
267
+ } catch {
268
+ return {
269
+ content: [
270
+ {
271
+ type: 'text',
272
+ text: `Workspace graph file not found at ${graphPath}. Run "nexusflow sync" or rebuild the workspace to generate it.`,
273
+ },
274
+ ],
275
+ isError: true,
276
+ };
277
+ }
278
+
279
+ const content = await fs.readFile(graphPath, 'utf8');
280
+ const graph = JSON.parse(content);
281
+
282
+ let nodes = graph.nodes;
283
+ let edges = graph.edges;
284
+
285
+ if (nodeType) {
286
+ nodes = nodes.filter((n: any) => n.type === nodeType);
287
+ }
288
+ if (edgeType) {
289
+ edges = edges.filter((e: any) => e.type === edgeType);
290
+ }
291
+
292
+ return {
293
+ content: [
294
+ {
295
+ type: 'text',
296
+ text: JSON.stringify({ nodes, edges }, null, 2),
297
+ },
298
+ ],
299
+ };
300
+ } catch (error: any) {
301
+ return {
302
+ content: [
303
+ {
304
+ type: 'text',
305
+ text: `Error querying workspace graph: ${error.message}`,
306
+ },
307
+ ],
308
+ isError: true,
309
+ };
310
+ }
311
+ }
312
+
182
313
  throw new Error(`Tool not found: ${name}`);
183
314
  });
184
315
 
package/src/server.ts CHANGED
@@ -17,6 +17,7 @@ import { scanForRepos } from './core/scanner.js';
17
17
  import { createWorkspace, listWorkspaces, loadFeatureConfig } from './core/workspace.js';
18
18
  import { analyzeAllRepos } from './analyzers/index.js';
19
19
  import { generateContextFiles } from './generators/index.js';
20
+ import { packWorkspace } from './core/packer.js';
20
21
  import { detectAIAssistants } from './utils/detect-ai.js';
21
22
  import { detectEditors } from './utils/detect-editors.js';
22
23
  import { findSessions, getSessionTranscript } from './utils/session-finder.js';
@@ -606,6 +607,30 @@ app.get('/api/update-status', async (c) => {
606
607
  }
607
608
  });
608
609
 
610
+ // 18. Pack workspace codebase and download
611
+ app.get('/api/workspace/:id/pack', async (c) => {
612
+ try {
613
+ const id = decodeURIComponent(c.req.param('id'));
614
+ const config = await loadConfig();
615
+ const workspacePath = path.join(config.workspacesDir, id);
616
+
617
+ const feature = await loadFeatureConfig(workspacePath);
618
+ if (!feature) {
619
+ return c.json({ error: 'Workspace configuration not found.' }, 404);
620
+ }
621
+
622
+ const result = await packWorkspace(workspacePath);
623
+ const content = await fs.readFile(result.outputPath, 'utf-8');
624
+
625
+ c.header('Content-Disposition', `attachment; filename="nexusflow-context-${id.replace(/[\/\\ ]/g, '-')}.xml"`);
626
+ c.header('Content-Type', 'application/xml');
627
+ return c.text(content);
628
+ } catch (error) {
629
+ const msg = error instanceof Error ? error.message : String(error);
630
+ return c.json({ error: msg }, 500);
631
+ }
632
+ });
633
+
609
634
  // Serve index.html explicitly on root endpoint
610
635
  app.get('/', async (c) => {
611
636
  try {