orbital-command 0.3.0 → 1.0.0

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 (160) hide show
  1. package/README.md +67 -42
  2. package/bin/commands/config.js +19 -0
  3. package/bin/commands/events.js +40 -0
  4. package/bin/commands/launch.js +126 -0
  5. package/bin/commands/manifest.js +283 -0
  6. package/bin/commands/registry.js +104 -0
  7. package/bin/commands/update.js +24 -0
  8. package/bin/lib/helpers.js +229 -0
  9. package/bin/orbital.js +95 -870
  10. package/dist/assets/Landing-CfQdHR0N.js +11 -0
  11. package/dist/assets/PrimitivesConfig-DThSipFy.js +32 -0
  12. package/dist/assets/QualityGates-B4kxM5UU.js +26 -0
  13. package/dist/assets/SessionTimeline-Bz1iZnmg.js +1 -0
  14. package/dist/assets/Settings-DLcZwbCT.js +12 -0
  15. package/dist/assets/SourceControl-BMNIz7Lt.js +36 -0
  16. package/dist/assets/WorkflowVisualizer-CxuSBOYu.js +69 -0
  17. package/dist/assets/{arrow-down-CPy85_J6.js → arrow-down-DVPp6_qp.js} +1 -1
  18. package/dist/assets/bot-NFaJBDn_.js +6 -0
  19. package/dist/assets/{charts-DbDg0Psc.js → charts-LGLb8hyU.js} +1 -1
  20. package/dist/assets/{circle-x-Cwz6ZQDV.js → circle-x-IsFCkBZu.js} +1 -1
  21. package/dist/assets/{file-text-C46Xr65c.js → file-text-J1cebZXF.js} +1 -1
  22. package/dist/assets/{globe-Cn2yNZUD.js → globe-WzeyHsUc.js} +1 -1
  23. package/dist/assets/index-BdJ57EhC.css +1 -0
  24. package/dist/assets/index-o4ScMAuR.js +349 -0
  25. package/dist/assets/{key-OPaNTWJ5.js → key-CKR8JJSj.js} +1 -1
  26. package/dist/assets/{minus-GMsbpKym.js → minus-CHBsJyjp.js} +1 -1
  27. package/dist/assets/radio-xqZaR-Uk.js +6 -0
  28. package/dist/assets/rocket-D_xvvNG6.js +6 -0
  29. package/dist/assets/{shield-DwAFkDYI.js → shield-TdB1yv_a.js} +1 -1
  30. package/dist/assets/useSocketListener-0L5yiN5i.js +1 -0
  31. package/dist/assets/useWorkflowEditor-CqeRWVQX.js +11 -0
  32. package/dist/assets/workflow-constants-Rw-GmgHZ.js +6 -0
  33. package/dist/assets/zap-C9wqYMpl.js +6 -0
  34. package/dist/index.html +3 -3
  35. package/dist/server/server/__tests__/data-routes.test.js +2 -0
  36. package/dist/server/server/__tests__/scope-routes.test.js +1 -0
  37. package/dist/server/server/config-migrator.js +0 -3
  38. package/dist/server/server/config.js +35 -6
  39. package/dist/server/server/database.js +0 -22
  40. package/dist/server/server/index.js +26 -814
  41. package/dist/server/server/init.js +32 -399
  42. package/dist/server/server/launch.js +1 -1
  43. package/dist/server/server/parsers/event-parser.js +4 -1
  44. package/dist/server/server/project-context.js +19 -9
  45. package/dist/server/server/project-manager.js +6 -6
  46. package/dist/server/server/routes/aggregate-routes.js +871 -0
  47. package/dist/server/server/routes/config-routes.js +41 -88
  48. package/dist/server/server/routes/data-routes.js +5 -15
  49. package/dist/server/server/routes/dispatch-routes.js +24 -8
  50. package/dist/server/server/routes/manifest-routes.js +1 -1
  51. package/dist/server/server/routes/scope-routes.js +10 -7
  52. package/dist/server/server/schema.js +1 -0
  53. package/dist/server/server/services/batch-orchestrator.js +17 -3
  54. package/dist/server/server/services/config-service.js +10 -1
  55. package/dist/server/server/services/scope-service.js +7 -7
  56. package/dist/server/server/services/sprint-orchestrator.js +24 -11
  57. package/dist/server/server/services/sprint-service.js +2 -2
  58. package/dist/server/server/uninstall.js +195 -0
  59. package/dist/server/server/update.js +212 -0
  60. package/dist/server/server/utils/dispatch-utils.js +8 -6
  61. package/dist/server/server/utils/flag-builder.js +54 -0
  62. package/dist/server/server/utils/json-fields.js +14 -0
  63. package/dist/server/server/utils/json-fields.test.js +73 -0
  64. package/dist/server/server/utils/route-helpers.js +37 -0
  65. package/dist/server/server/utils/route-helpers.test.js +115 -0
  66. package/dist/server/server/watchers/event-watcher.js +28 -13
  67. package/dist/server/server/wizard/config-editor.js +4 -4
  68. package/dist/server/server/wizard/doctor.js +2 -2
  69. package/dist/server/server/wizard/index.js +224 -39
  70. package/dist/server/server/wizard/phases/welcome.js +1 -4
  71. package/dist/server/server/wizard/ui.js +6 -7
  72. package/dist/server/shared/api-types.js +80 -1
  73. package/dist/server/shared/workflow-engine.js +1 -1
  74. package/package.json +20 -20
  75. package/schemas/orbital.config.schema.json +1 -19
  76. package/scripts/postinstall.js +6 -42
  77. package/scripts/release.sh +53 -0
  78. package/server/__tests__/data-routes.test.ts +2 -0
  79. package/server/__tests__/scope-routes.test.ts +1 -0
  80. package/server/config-migrator.ts +0 -3
  81. package/server/config.ts +39 -11
  82. package/server/database.ts +0 -26
  83. package/server/global-config.ts +4 -0
  84. package/server/index.ts +29 -894
  85. package/server/init.ts +32 -443
  86. package/server/launch.ts +1 -1
  87. package/server/parsers/event-parser.ts +4 -1
  88. package/server/project-context.ts +26 -10
  89. package/server/project-manager.ts +5 -6
  90. package/server/routes/aggregate-routes.ts +968 -0
  91. package/server/routes/config-routes.ts +41 -81
  92. package/server/routes/data-routes.ts +7 -16
  93. package/server/routes/dispatch-routes.ts +29 -8
  94. package/server/routes/manifest-routes.ts +1 -1
  95. package/server/routes/scope-routes.ts +12 -7
  96. package/server/schema.ts +1 -0
  97. package/server/services/batch-orchestrator.ts +18 -2
  98. package/server/services/config-service.ts +10 -1
  99. package/server/services/scope-service.ts +6 -6
  100. package/server/services/sprint-orchestrator.ts +24 -9
  101. package/server/services/sprint-service.ts +2 -2
  102. package/server/uninstall.ts +214 -0
  103. package/server/update.ts +263 -0
  104. package/server/utils/dispatch-utils.ts +8 -6
  105. package/server/utils/flag-builder.ts +56 -0
  106. package/server/utils/json-fields.test.ts +83 -0
  107. package/server/utils/json-fields.ts +14 -0
  108. package/server/utils/route-helpers.test.ts +144 -0
  109. package/server/utils/route-helpers.ts +38 -0
  110. package/server/watchers/event-watcher.ts +24 -12
  111. package/server/wizard/config-editor.ts +4 -4
  112. package/server/wizard/doctor.ts +2 -2
  113. package/server/wizard/index.ts +291 -40
  114. package/server/wizard/phases/welcome.ts +1 -5
  115. package/server/wizard/ui.ts +6 -7
  116. package/shared/api-types.ts +106 -0
  117. package/shared/workflow-engine.ts +1 -1
  118. package/templates/agents/QUICK-REFERENCE.md +1 -0
  119. package/templates/agents/README.md +1 -0
  120. package/templates/agents/SKILL-TRIGGERS.md +11 -0
  121. package/templates/agents/green-team/deep-dive.md +361 -0
  122. package/templates/hooks/end-session.sh +1 -0
  123. package/templates/hooks/init-session.sh +1 -0
  124. package/templates/hooks/scope-commit-logger.sh +2 -2
  125. package/templates/hooks/scope-create-gate.sh +2 -4
  126. package/templates/hooks/scope-gate.sh +4 -6
  127. package/templates/hooks/scope-helpers.sh +10 -1
  128. package/templates/hooks/scope-lifecycle-gate.sh +14 -5
  129. package/templates/hooks/scope-prepare.sh +1 -1
  130. package/templates/hooks/scope-transition.sh +14 -6
  131. package/templates/hooks/time-tracker.sh +2 -5
  132. package/templates/orbital.config.json +1 -4
  133. package/templates/presets/development.json +4 -4
  134. package/templates/presets/gitflow.json +7 -0
  135. package/templates/prompts/README.md +23 -0
  136. package/templates/prompts/deep-dive-audit.md +94 -0
  137. package/templates/quick/rules.md +56 -5
  138. package/templates/skills/git-commit/SKILL.md +21 -6
  139. package/templates/skills/git-dev/SKILL.md +8 -4
  140. package/templates/skills/git-main/SKILL.md +8 -4
  141. package/templates/skills/git-production/SKILL.md +6 -3
  142. package/templates/skills/git-staging/SKILL.md +6 -3
  143. package/templates/skills/scope-fix-review/SKILL.md +8 -4
  144. package/templates/skills/scope-implement/SKILL.md +13 -5
  145. package/templates/skills/scope-post-review/SKILL.md +16 -4
  146. package/templates/skills/scope-pre-review/SKILL.md +6 -2
  147. package/dist/assets/PrimitivesConfig-CrmQXYh4.js +0 -32
  148. package/dist/assets/QualityGates-BbasOsF3.js +0 -21
  149. package/dist/assets/SessionTimeline-CGeJsVvy.js +0 -1
  150. package/dist/assets/Settings-oiM496mc.js +0 -12
  151. package/dist/assets/SourceControl-B1fP2nJL.js +0 -41
  152. package/dist/assets/WorkflowVisualizer-CWLYf-f0.js +0 -74
  153. package/dist/assets/formatDistanceToNow-BMqsSP44.js +0 -1
  154. package/dist/assets/index-Aj4sV8Al.css +0 -1
  155. package/dist/assets/index-Bc9dK3MW.js +0 -354
  156. package/dist/assets/useWorkflowEditor-BJkTX_NR.js +0 -16
  157. package/dist/assets/zap-DfbUoOty.js +0 -11
  158. package/dist/server/server/services/telemetry-service.js +0 -143
  159. package/server/services/telemetry-service.ts +0 -195
  160. /package/{shared/default-workflow.json → templates/presets/default.json} +0 -0
package/server/index.ts CHANGED
@@ -4,15 +4,8 @@ import { Server } from 'socket.io';
4
4
  import path from 'path';
5
5
  import fs from 'fs';
6
6
  import { fileURLToPath } from 'url';
7
- import type { GateRow } from './services/gate-service.js';
8
- import { launchInTerminal } from './utils/terminal-launcher.js';
9
- import { getClaudeSessions, getSessionStats } from './services/claude-session-service.js';
10
- import { getActiveScopeIds, getAbandonedScopeIds } from './utils/dispatch-utils.js';
11
- import { ConfigService, isValidPrimitiveType } from './services/config-service.js';
12
- import { GLOBAL_PRIMITIVES_DIR } from './global-config.js';
13
7
  import { createVersionRoutes } from './routes/version-routes.js';
14
- import { WorkflowEngine } from '../shared/workflow-engine.js';
15
- import { getHookEnforcement } from '../shared/workflow-config.js';
8
+ import { createAggregateRoutes } from './routes/aggregate-routes.js';
16
9
  import { createLogger, setLogLevel } from './utils/logger.js';
17
10
  import type { LogLevel } from './utils/logger.js';
18
11
 
@@ -24,13 +17,12 @@ import { ProjectManager } from './project-manager.js';
24
17
  import { SyncService } from './services/sync-service.js';
25
18
  import { startGlobalWatcher } from './watchers/global-watcher.js';
26
19
  import { createSyncRoutes } from './routes/sync-routes.js';
27
- import { seedGlobalPrimitives, runUpdate } from './init.js';
28
- import { loadManifest, refreshFileStatuses, summarizeManifest } from './manifest.js';
29
- import { getPackageVersion } from './utils/package-info.js';
20
+ import { seedGlobalPrimitives } from './init.js';
30
21
  import {
31
22
  ensureOrbitalHome,
32
23
  loadGlobalConfig,
33
24
  registerProject as registerProjectGlobal,
25
+ GLOBAL_PRIMITIVES_DIR,
34
26
  ORBITAL_HOME,
35
27
  } from './global-config.js';
36
28
 
@@ -86,6 +78,29 @@ export async function startCentralServer(overrides?: CentralServerOverrides): Pr
86
78
 
87
79
  app.use(express.json());
88
80
 
81
+ // ─── Bind port early ──────────────────────────────────────
82
+ // Listen before async init so Vite's proxy doesn't get ECONNREFUSED
83
+ const actualPort = await new Promise<number>((resolve, reject) => {
84
+ let attempt = 0;
85
+ const maxAttempts = 10;
86
+
87
+ httpServer.on('error', (err: NodeJS.ErrnoException) => {
88
+ if (err.code === 'EADDRINUSE' && attempt < maxAttempts) {
89
+ attempt++;
90
+ httpServer.listen(port + attempt);
91
+ } else {
92
+ reject(new Error(`Failed to start server: ${err.message}`));
93
+ }
94
+ });
95
+
96
+ httpServer.on('listening', () => {
97
+ const addr = httpServer.address();
98
+ resolve(typeof addr === 'object' && addr ? addr.port : port);
99
+ });
100
+
101
+ httpServer.listen(port);
102
+ });
103
+
89
104
  // Initialize ProjectManager and boot all registered projects
90
105
  const projectManager = new ProjectManager(io);
91
106
  await projectManager.initializeAll();
@@ -127,867 +142,8 @@ export async function startCentralServer(overrides?: CentralServerOverrides): Pr
127
142
  router(req, res, next);
128
143
  });
129
144
 
130
- // Aggregate endpoints
131
- app.get('/api/orbital/aggregate/scopes', (_req, res) => {
132
- const allScopes: Array<Record<string, unknown>> = [];
133
- for (const [projectId, ctx] of projectManager.getAllContexts()) {
134
- for (const scope of ctx.scopeService.getAll()) {
135
- allScopes.push({ ...scope, project_id: projectId });
136
- }
137
- }
138
- res.json(allScopes);
139
- });
140
-
141
- app.get('/api/orbital/aggregate/events', (req, res) => {
142
- const limit = Number(req.query.limit) || 50;
143
- const allEvents: Array<Record<string, unknown>> = [];
144
- for (const [projectId, ctx] of projectManager.getAllContexts()) {
145
- const events = ctx.db.prepare(
146
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`
147
- ).all(limit) as Array<Record<string, unknown>>;
148
- for (const event of events) {
149
- allEvents.push({ ...event, project_id: projectId });
150
- }
151
- }
152
- // Sort by timestamp descending across all projects
153
- allEvents.sort((a, b) => String(b.timestamp).localeCompare(String(a.timestamp)));
154
- res.json(allEvents.slice(0, limit));
155
- });
156
-
157
- // Aggregate sessions across all projects
158
- const JSON_FIELDS = ['tags', 'blocked_by', 'blocks', 'data', 'discoveries', 'next_steps', 'details'];
159
- function parseJsonFields(row: Record<string, unknown>): Record<string, unknown> {
160
- const parsed = { ...row };
161
- for (const field of JSON_FIELDS) {
162
- if (typeof parsed[field] === 'string') {
163
- try { parsed[field] = JSON.parse(parsed[field] as string); } catch { /* keep string */ }
164
- }
165
- }
166
- return parsed;
167
- }
168
-
169
- app.get('/api/orbital/aggregate/sessions', (_req, res) => {
170
- const allRows: Array<Record<string, unknown>> = [];
171
- for (const [projectId, ctx] of projectManager.getAllContexts()) {
172
- const rows = ctx.db.prepare(
173
- 'SELECT * FROM sessions ORDER BY started_at DESC'
174
- ).all() as Array<Record<string, unknown>>;
175
- for (const row of rows) {
176
- allRows.push({ ...parseJsonFields(row), project_id: projectId });
177
- }
178
- }
179
-
180
- // Deduplicate by claude_session_id, aggregate scope_ids and actions
181
- const seen = new Map<string, Record<string, unknown>>();
182
- const scopeMap = new Map<string, number[]>();
183
- const actionMap = new Map<string, string[]>();
184
-
185
- for (const row of allRows) {
186
- const key = (row.claude_session_id as string | null) ?? (row.id as string);
187
- if (!seen.has(key)) {
188
- seen.set(key, row);
189
- scopeMap.set(key, []);
190
- actionMap.set(key, []);
191
- }
192
- const sid = row.scope_id as number | null;
193
- if (sid != null) {
194
- const arr = scopeMap.get(key)!;
195
- if (!arr.includes(sid)) arr.push(sid);
196
- }
197
- const action = row.action as string | null;
198
- if (action) {
199
- const actions = actionMap.get(key)!;
200
- if (!actions.includes(action)) actions.push(action);
201
- }
202
- }
203
-
204
- const results = [...seen.values()].map((row) => {
205
- const key = (row.claude_session_id as string | null) ?? (row.id as string);
206
- return { ...row, scope_ids: scopeMap.get(key) ?? [], actions: actionMap.get(key) ?? [] };
207
- });
208
-
209
- // Sort by started_at descending across all projects
210
- results.sort((a, b) =>
211
- String((b as Record<string, unknown>).started_at ?? '').localeCompare(
212
- String((a as Record<string, unknown>).started_at ?? ''),
213
- ),
214
- );
215
- res.json(results.slice(0, 50));
216
- });
217
-
218
- app.get('/api/orbital/aggregate/sessions/:id/content', async (req, res) => {
219
- const sessionId = req.params.id;
220
-
221
- // Find the session across all project databases
222
- let session: Record<string, unknown> | undefined;
223
- let matchedProjectRoot: string | undefined;
224
- for (const [, ctx] of projectManager.getAllContexts()) {
225
- const row = ctx.db.prepare('SELECT * FROM sessions WHERE id = ?').get(sessionId) as Record<string, unknown> | undefined;
226
- if (row) {
227
- session = parseJsonFields(row);
228
- matchedProjectRoot = ctx.config.projectRoot;
229
- break;
230
- }
231
- }
232
-
233
- if (!session || !matchedProjectRoot) {
234
- res.status(404).json({ error: 'Session not found' });
235
- return;
236
- }
237
-
238
- let content = '';
239
- let meta: Record<string, unknown> | null = null;
240
- let stats: Record<string, unknown> | null = null;
241
-
242
- if (session.claude_session_id && typeof session.claude_session_id === 'string') {
243
- const claudeSessions = await getClaudeSessions(undefined, matchedProjectRoot);
244
- const match = claudeSessions.find(s => s.id === session!.claude_session_id);
245
- if (match) {
246
- meta = {
247
- slug: match.slug,
248
- branch: match.branch,
249
- fileSize: match.fileSize,
250
- summary: match.summary,
251
- startedAt: match.startedAt,
252
- lastActiveAt: match.lastActiveAt,
253
- };
254
- }
255
- stats = getSessionStats(session.claude_session_id, matchedProjectRoot) as Record<string, unknown> | null;
256
- }
257
-
258
- if (!content) {
259
- const parts: string[] = [];
260
- if (session.summary) parts.push(`# ${session.summary}\n`);
261
- const discoveries = Array.isArray(session.discoveries) ? session.discoveries : [];
262
- if (discoveries.length > 0) {
263
- parts.push('## Completed\n');
264
- for (const d of discoveries) parts.push(`- ${d}`);
265
- parts.push('');
266
- }
267
- const nextSteps = Array.isArray(session.next_steps) ? session.next_steps : [];
268
- if (nextSteps.length > 0) {
269
- parts.push('## Next Steps\n');
270
- for (const n of nextSteps) parts.push(`- ${n}`);
271
- }
272
- content = parts.join('\n');
273
- }
274
-
275
- res.json({
276
- id: session.id,
277
- content,
278
- claude_session_id: session.claude_session_id ?? null,
279
- meta,
280
- stats,
281
- });
282
- });
283
-
284
- app.post('/api/orbital/aggregate/sessions/:id/resume', async (req, res) => {
285
- const sessionId = req.params.id;
286
- const { claude_session_id } = req.body as { claude_session_id?: string };
287
-
288
- if (!claude_session_id || !/^[0-9a-f-]{36}$/i.test(claude_session_id)) {
289
- res.status(400).json({ error: 'Valid claude_session_id (UUID) required' });
290
- return;
291
- }
292
-
293
- // Find the session's project root
294
- let matchedProjectRoot: string | undefined;
295
- for (const [, ctx] of projectManager.getAllContexts()) {
296
- const row = ctx.db.prepare('SELECT * FROM sessions WHERE id = ?').get(sessionId);
297
- if (row) {
298
- matchedProjectRoot = ctx.config.projectRoot;
299
- break;
300
- }
301
- }
302
-
303
- if (!matchedProjectRoot) {
304
- res.status(404).json({ error: 'Session not found' });
305
- return;
306
- }
307
-
308
- const resumeCmd = `cd '${matchedProjectRoot}' && claude --dangerously-skip-permissions --resume '${claude_session_id}'`;
309
- try {
310
- await launchInTerminal(resumeCmd);
311
- res.json({ ok: true, session_id: claude_session_id });
312
- } catch (err) {
313
- log.error('Terminal launch failed', { error: String(err) });
314
- res.status(500).json({ error: 'Failed to launch terminal', details: String(err) });
315
- }
316
- });
317
-
318
- // ─── Aggregate: Enforcement & Gates ──────────────────────
319
-
320
- app.get('/api/orbital/aggregate/events/violations/summary', (_req, res) => {
321
- try {
322
- const mergedByRule = new Map<string, { rule: string; count: number; last_seen: string }>();
323
- const mergedByFile = new Map<string, { file: string; count: number }>();
324
- let allOverrides: Array<{ rule: string; reason: string; date: string }> = [];
325
- let totalViolations = 0;
326
- let totalOverrides = 0;
327
-
328
- for (const [, ctx] of projectManager.getAllContexts()) {
329
- const byRule = ctx.db.prepare(
330
- `SELECT JSON_EXTRACT(data, '$.rule') as rule, COUNT(*) as count, MAX(timestamp) as last_seen
331
- FROM events WHERE type = 'VIOLATION' GROUP BY rule ORDER BY count DESC`
332
- ).all() as Array<{ rule: string; count: number; last_seen: string }>;
333
- for (const r of byRule) {
334
- const existing = mergedByRule.get(r.rule);
335
- if (existing) {
336
- existing.count += r.count;
337
- if (r.last_seen > existing.last_seen) existing.last_seen = r.last_seen;
338
- } else {
339
- mergedByRule.set(r.rule, { ...r });
340
- }
341
- }
342
-
343
- const byFile = ctx.db.prepare(
344
- `SELECT JSON_EXTRACT(data, '$.file') as file, COUNT(*) as count FROM events
345
- WHERE type = 'VIOLATION' AND JSON_EXTRACT(data, '$.file') IS NOT NULL AND JSON_EXTRACT(data, '$.file') != ''
346
- GROUP BY file ORDER BY count DESC LIMIT 20`
347
- ).all() as Array<{ file: string; count: number }>;
348
- for (const f of byFile) {
349
- const existing = mergedByFile.get(f.file);
350
- if (existing) {
351
- existing.count += f.count;
352
- } else {
353
- mergedByFile.set(f.file, { ...f });
354
- }
355
- }
356
-
357
- const overrides = ctx.db.prepare(
358
- `SELECT JSON_EXTRACT(data, '$.rule') as rule, JSON_EXTRACT(data, '$.reason') as reason, timestamp as date
359
- FROM events WHERE type = 'OVERRIDE' ORDER BY timestamp DESC LIMIT 50`
360
- ).all() as Array<{ rule: string; reason: string; date: string }>;
361
- allOverrides = allOverrides.concat(overrides);
362
-
363
- const tv = ctx.db.prepare(`SELECT COUNT(*) as count FROM events WHERE type = 'VIOLATION'`).get() as { count: number };
364
- const to = ctx.db.prepare(`SELECT COUNT(*) as count FROM events WHERE type = 'OVERRIDE'`).get() as { count: number };
365
- totalViolations += tv.count;
366
- totalOverrides += to.count;
367
- }
368
-
369
- const byRule = [...mergedByRule.values()].sort((a, b) => b.count - a.count);
370
- const byFile = [...mergedByFile.values()].sort((a, b) => b.count - a.count).slice(0, 20);
371
- allOverrides.sort((a, b) => b.date.localeCompare(a.date));
372
-
373
- res.json({ byRule, byFile, overrides: allOverrides.slice(0, 50), totalViolations, totalOverrides });
374
- } catch (err) {
375
- log.error('Violations summary failed', { error: String(err) });
376
- res.status(500).json({ error: 'Failed to aggregate violations summary' });
377
- }
378
- });
379
-
380
- app.get('/api/orbital/aggregate/enforcement/rules', (_req, res) => {
381
- try {
382
- const hookMap = new Map<string, {
383
- hook: ReturnType<WorkflowEngine['getAllHooks']>[number];
384
- enforcement: string;
385
- edges: Array<{ from: string; to: string; label: string }>;
386
- stats: { violations: number; overrides: number; last_triggered: string | null };
387
- }>();
388
- const summary = { guards: 0, gates: 0, lifecycle: 0, observers: 0 };
389
- const edgeIdSet = new Set<string>();
390
- let totalEdges = 0;
391
-
392
- for (const [, ctx] of projectManager.getAllContexts()) {
393
- const allHooks = ctx.workflowEngine.getAllHooks();
394
- const allEdges = ctx.workflowEngine.getAllEdges();
395
-
396
- // Build edge map for this project
397
- const hookEdgeMap = new Map<string, Array<{ from: string; to: string; label: string }>>();
398
- for (const edge of allEdges) {
399
- const edgeKey = `${edge.from}->${edge.to}`;
400
- if (!edgeIdSet.has(edgeKey)) {
401
- edgeIdSet.add(edgeKey);
402
- totalEdges++;
403
- }
404
- for (const hookId of edge.hooks ?? []) {
405
- if (!hookEdgeMap.has(hookId)) hookEdgeMap.set(hookId, []);
406
- hookEdgeMap.get(hookId)!.push({ from: edge.from, to: edge.to, label: edge.label });
407
- }
408
- }
409
-
410
- // Query stats from this project's DB
411
- const violationStats = ctx.db.prepare(
412
- `SELECT JSON_EXTRACT(data, '$.rule') as rule, COUNT(*) as count, MAX(timestamp) as last_seen
413
- FROM events WHERE type = 'VIOLATION' GROUP BY rule`
414
- ).all() as Array<{ rule: string; count: number; last_seen: string }>;
415
- const overrideStats = ctx.db.prepare(
416
- `SELECT JSON_EXTRACT(data, '$.rule') as rule, COUNT(*) as count
417
- FROM events WHERE type = 'OVERRIDE' GROUP BY rule`
418
- ).all() as Array<{ rule: string; count: number }>;
419
- const violationMap = new Map(violationStats.map((v) => [v.rule, v]));
420
- const overrideMap = new Map(overrideStats.map((o) => [o.rule, o]));
421
-
422
- for (const hook of allHooks) {
423
- const existing = hookMap.get(hook.id);
424
- const projViolations = violationMap.get(hook.id)?.count ?? 0;
425
- const projOverrides = overrideMap.get(hook.id)?.count ?? 0;
426
- const projLastTriggered = violationMap.get(hook.id)?.last_seen ?? null;
427
-
428
- if (existing) {
429
- // Sum stats across projects
430
- existing.stats.violations += projViolations;
431
- existing.stats.overrides += projOverrides;
432
- if (projLastTriggered && (!existing.stats.last_triggered || projLastTriggered > existing.stats.last_triggered)) {
433
- existing.stats.last_triggered = projLastTriggered;
434
- }
435
- // Union edges
436
- const existingEdgeKeys = new Set(existing.edges.map((e) => `${e.from}->${e.to}`));
437
- for (const edge of hookEdgeMap.get(hook.id) ?? []) {
438
- if (!existingEdgeKeys.has(`${edge.from}->${edge.to}`)) {
439
- existing.edges.push(edge);
440
- }
441
- }
442
- } else {
443
- // First time seeing this hook — count it in summary
444
- if (hook.category === 'guard') summary.guards++;
445
- else if (hook.category === 'gate') summary.gates++;
446
- else if (hook.category === 'lifecycle') summary.lifecycle++;
447
- else if (hook.category === 'observer') summary.observers++;
448
-
449
- hookMap.set(hook.id, {
450
- hook,
451
- enforcement: getHookEnforcement(hook),
452
- edges: hookEdgeMap.get(hook.id) ?? [],
453
- stats: {
454
- violations: projViolations,
455
- overrides: projOverrides,
456
- last_triggered: projLastTriggered,
457
- },
458
- });
459
- }
460
- }
461
- }
462
-
463
- res.json({ summary, rules: [...hookMap.values()], totalEdges });
464
- } catch (err) {
465
- log.error('Enforcement rules failed', { error: String(err) });
466
- res.status(500).json({ error: 'Failed to aggregate enforcement rules' });
467
- }
468
- });
469
-
470
- app.get('/api/orbital/aggregate/events/violations/trend', (req, res) => {
471
- try {
472
- const days = Number(req.query.days) || 30;
473
- const merged = new Map<string, { day: string; rule: string; count: number }>();
474
-
475
- for (const [, ctx] of projectManager.getAllContexts()) {
476
- const trend = ctx.db.prepare(
477
- `SELECT date(timestamp) as day, JSON_EXTRACT(data, '$.rule') as rule, COUNT(*) as count
478
- FROM events WHERE type = 'VIOLATION' AND timestamp >= datetime('now', ? || ' days')
479
- GROUP BY day, rule ORDER BY day ASC`
480
- ).all(`-${days}`) as Array<{ day: string; rule: string; count: number }>;
481
- for (const t of trend) {
482
- const key = `${t.day}:${t.rule}`;
483
- const existing = merged.get(key);
484
- if (existing) {
485
- existing.count += t.count;
486
- } else {
487
- merged.set(key, { ...t });
488
- }
489
- }
490
- }
491
-
492
- const result = [...merged.values()].sort((a, b) => a.day.localeCompare(b.day));
493
- res.json(result);
494
- } catch (err) {
495
- log.error('Violation trends failed', { error: String(err) });
496
- res.status(500).json({ error: 'Failed to aggregate violation trends' });
497
- }
498
- });
499
-
500
- app.get('/api/orbital/aggregate/gates', (req, res) => {
501
- try {
502
- const scopeId = req.query.scope_id;
503
- const filterProjectId = req.query.project_id as string | undefined;
504
- const mergedGates = new Map<string, GateRow & { project_id: string }>();
505
-
506
- for (const [projectId, ctx] of projectManager.getAllContexts()) {
507
- if (filterProjectId && projectId !== filterProjectId) continue;
508
- const gates = scopeId
509
- ? ctx.gateService.getLatestForScope(Number(scopeId))
510
- : ctx.gateService.getLatestRun();
511
- for (const gate of gates) {
512
- const existing = mergedGates.get(gate.gate_name);
513
- if (!existing || gate.run_at > existing.run_at) {
514
- mergedGates.set(gate.gate_name, { ...gate, project_id: projectId });
515
- }
516
- }
517
- }
518
-
519
- res.json([...mergedGates.values()]);
520
- } catch (err) {
521
- log.error('Gates aggregation failed', { error: String(err) });
522
- res.status(500).json({ error: 'Failed to aggregate gates' });
523
- }
524
- });
525
-
526
- app.get('/api/orbital/aggregate/gates/stats', (_req, res) => {
527
- try {
528
- const merged = new Map<string, { gate_name: string; total: number; passed: number; failed: number }>();
529
-
530
- for (const [, ctx] of projectManager.getAllContexts()) {
531
- const stats = ctx.gateService.getStats();
532
- for (const s of stats) {
533
- const existing = merged.get(s.gate_name);
534
- if (existing) {
535
- existing.total += s.total;
536
- existing.passed += s.passed;
537
- existing.failed += s.failed;
538
- } else {
539
- merged.set(s.gate_name, { ...s });
540
- }
541
- }
542
- }
543
-
544
- res.json([...merged.values()]);
545
- } catch (err) {
546
- log.error('Gate stats failed', { error: String(err) });
547
- res.status(500).json({ error: 'Failed to aggregate gate stats' });
548
- }
549
- });
550
-
551
- // ─── Aggregate: Git & GitHub ───────────────────────────────
552
-
553
- app.get('/api/orbital/aggregate/git/overview', async (_req, res) => {
554
- try {
555
- const projects = projectManager.getProjectList();
556
- const results = await Promise.allSettled(
557
- projects.filter(p => p.enabled && p.status === 'active').map(async (proj) => {
558
- const ctx = projectManager.getContext(proj.id);
559
- if (!ctx) throw new Error('Project offline');
560
- const config = ctx.workflowEngine.getConfig();
561
- const overview = await ctx.gitService.getOverview(config.branchingMode ?? 'trunk');
562
- return {
563
- projectId: proj.id,
564
- projectName: proj.name,
565
- projectColor: proj.color,
566
- status: 'ok' as const,
567
- overview,
568
- };
569
- }),
570
- );
571
-
572
- const overviews = results.map((r, i) => {
573
- if (r.status === 'fulfilled') return r.value;
574
- const proj = projects.filter(p => p.enabled && p.status === 'active')[i];
575
- return {
576
- projectId: proj.id,
577
- projectName: proj.name,
578
- projectColor: proj.color,
579
- status: 'error' as const,
580
- error: String((r as PromiseRejectedResult).reason),
581
- };
582
- });
583
-
584
- res.json(overviews);
585
- } catch (err) {
586
- log.error('Git overviews failed', { error: String(err) });
587
- res.status(500).json({ error: 'Failed to aggregate git overviews' });
588
- }
589
- });
590
-
591
- app.get('/api/orbital/aggregate/git/commits', async (req, res) => {
592
- try {
593
- const limit = Number(req.query.limit) || 50;
594
- const projects = projectManager.getProjectList().filter(p => p.enabled && p.status === 'active');
595
-
596
- const results = await Promise.allSettled(
597
- projects.map(async (proj) => {
598
- const ctx = projectManager.getContext(proj.id);
599
- if (!ctx) return [];
600
- const commits = await ctx.gitService.getCommits({ limit });
601
- return commits.map(c => ({
602
- ...c,
603
- project_id: proj.id,
604
- projectName: proj.name,
605
- projectColor: proj.color,
606
- }));
607
- }),
608
- );
609
-
610
- const allCommits: Array<Record<string, unknown>> = [];
611
- for (const r of results) {
612
- if (r.status === 'fulfilled') allCommits.push(...r.value);
613
- }
614
- allCommits.sort((a, b) => String(b.date).localeCompare(String(a.date)));
615
- res.json(allCommits.slice(0, limit));
616
- } catch (err) {
617
- log.error('Commits aggregation failed', { error: String(err) });
618
- res.status(500).json({ error: 'Failed to aggregate commits' });
619
- }
620
- });
621
-
622
- app.get('/api/orbital/aggregate/github/prs', async (_req, res) => {
623
- try {
624
- const projects = projectManager.getProjectList().filter(p => p.enabled && p.status === 'active');
625
-
626
- const results = await Promise.allSettled(
627
- projects.map(async (proj) => {
628
- const ctx = projectManager.getContext(proj.id);
629
- if (!ctx) return [];
630
- const prs = await ctx.githubService.getOpenPRs();
631
- return prs.map(pr => ({
632
- ...pr,
633
- project_id: proj.id,
634
- projectName: proj.name,
635
- projectColor: proj.color,
636
- }));
637
- }),
638
- );
639
-
640
- const allPrs: Array<Record<string, unknown>> = [];
641
- for (const r of results) {
642
- if (r.status === 'fulfilled') allPrs.push(...r.value);
643
- }
644
- allPrs.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
645
- res.json(allPrs);
646
- } catch (err) {
647
- log.error('PRs aggregation failed', { error: String(err) });
648
- res.status(500).json({ error: 'Failed to aggregate PRs' });
649
- }
650
- });
651
-
652
- app.get('/api/orbital/aggregate/git/health', async (_req, res) => {
653
- try {
654
- const projects = projectManager.getProjectList().filter(p => p.enabled && p.status === 'active');
655
-
656
- const results = await Promise.allSettled(
657
- projects.map(async (proj) => {
658
- const ctx = projectManager.getContext(proj.id);
659
- if (!ctx) throw new Error('offline');
660
- const branches = await ctx.gitService.getBranches();
661
- const config = ctx.workflowEngine.getConfig();
662
- const listsWithBranch = config.lists.filter(l => l.gitBranch).sort((a, b) => a.order - b.order);
663
- const driftPairs: Array<{ from: string; to: string }> = [];
664
- for (let i = 0; i < listsWithBranch.length - 1; i++) {
665
- driftPairs.push({ from: listsWithBranch[i].gitBranch!, to: listsWithBranch[i + 1].gitBranch! });
666
- }
667
- const drift = driftPairs.length > 0 ? await ctx.gitService.getDrift(driftPairs) : [];
668
- const maxDrift = Math.max(0, ...drift.map(d => d.count));
669
- const staleBranches = branches.filter(b => b.isStale && !b.isRemote);
670
-
671
- return {
672
- projectId: proj.id,
673
- projectName: proj.name,
674
- projectColor: proj.color,
675
- branchCount: branches.filter(b => !b.isRemote).length,
676
- staleBranchCount: staleBranches.length,
677
- featureBranchCount: branches.filter(b => !b.isRemote && /(?:feat|fix|scope)[/-]/.test(b.name)).length,
678
- maxDriftSeverity: maxDrift === 0 ? 'clean' : maxDrift <= 5 ? 'low' : maxDrift <= 20 ? 'moderate' : 'high',
679
- };
680
- }),
681
- );
682
-
683
- const health: Array<Record<string, unknown>> = [];
684
- for (const r of results) {
685
- if (r.status === 'fulfilled') health.push(r.value);
686
- }
687
- res.json(health);
688
- } catch (err) {
689
- log.error('Branch health failed', { error: String(err) });
690
- res.status(500).json({ error: 'Failed to aggregate branch health' });
691
- }
692
- });
693
-
694
- app.get('/api/orbital/aggregate/git/activity', async (req, res) => {
695
- try {
696
- const days = Number(req.query.days) || 30;
697
- const projects = projectManager.getProjectList().filter(p => p.enabled && p.status === 'active');
698
-
699
- const results = await Promise.allSettled(
700
- projects.map(async (proj) => {
701
- const ctx = projectManager.getContext(proj.id);
702
- if (!ctx) return { projectId: proj.id, series: [] };
703
- const series = await ctx.gitService.getActivitySeries(days);
704
- return { projectId: proj.id, projectName: proj.name, projectColor: proj.color, series };
705
- }),
706
- );
707
-
708
- const activity: Array<Record<string, unknown>> = [];
709
- for (const r of results) {
710
- if (r.status === 'fulfilled') activity.push(r.value);
711
- }
712
- res.json(activity);
713
- } catch (err) {
714
- log.error('Activity aggregation failed', { error: String(err) });
715
- res.status(500).json({ error: 'Failed to aggregate activity' });
716
- }
717
- });
718
-
719
- app.get('/api/orbital/aggregate/scopes/:id/readiness', (req, res) => {
720
- const scopeId = Number(req.params.id);
721
- const projectId = req.query.project_id as string | undefined;
722
-
723
- for (const [pid, ctx] of projectManager.getAllContexts()) {
724
- if (projectId && pid !== projectId) continue;
725
- const scope = ctx.scopeService.getById(scopeId);
726
- if (scope) {
727
- const readiness = ctx.readinessService.getReadiness(scopeId);
728
- if (readiness) {
729
- res.json(readiness);
730
- return;
731
- }
732
- }
733
- }
734
- res.status(404).json({ error: 'Scope not found in any project' });
735
- });
736
-
737
- app.get('/api/orbital/aggregate/dispatch/active-scopes', (_req, res) => {
738
- const allActive: Array<{ scope_id: number; project_id: string }> = [];
739
- const seenActive = new Set<string>();
740
- const allAbandoned: Array<{ scope_id: number; project_id: string; from_status: string | null; abandoned_at: string }> = [];
741
- const seenAbandoned = new Set<string>();
742
-
743
- for (const [projectId, ctx] of projectManager.getAllContexts()) {
744
- const activeIds = getActiveScopeIds(ctx.db, ctx.scopeService, ctx.workflowEngine);
745
- for (const id of activeIds) {
746
- const key = `${projectId}::${id}`;
747
- if (!seenActive.has(key)) {
748
- seenActive.add(key);
749
- allActive.push({ scope_id: id, project_id: projectId });
750
- }
751
- }
752
-
753
- const abandoned = getAbandonedScopeIds(ctx.db, ctx.scopeService, ctx.workflowEngine, activeIds);
754
- for (const entry of abandoned) {
755
- const key = `${projectId}::${entry.scope_id}`;
756
- if (!seenAbandoned.has(key)) {
757
- seenAbandoned.add(key);
758
- allAbandoned.push({ ...entry, project_id: projectId });
759
- }
760
- }
761
- }
762
-
763
- res.json({ scope_ids: allActive, abandoned_scopes: allAbandoned });
764
- });
765
-
766
- app.get('/api/orbital/aggregate/dispatch/active', (req, res) => {
767
- const scopeId = Number(req.query.scope_id);
768
- if (isNaN(scopeId) || scopeId <= 0) {
769
- res.status(400).json({ error: 'Valid scope_id query param required' });
770
- return;
771
- }
772
-
773
- for (const [, ctx] of projectManager.getAllContexts()) {
774
- const scope = ctx.scopeService.getById(scopeId);
775
- if (!scope) continue;
776
-
777
- const active = ctx.db.prepare(
778
- `SELECT id, timestamp, JSON_EXTRACT(data, '$.command') as command
779
- FROM events
780
- WHERE type = 'DISPATCH' AND scope_id = ? AND JSON_EXTRACT(data, '$.resolved') IS NULL
781
- ORDER BY timestamp DESC LIMIT 1`
782
- ).get(scopeId) as { id: string; timestamp: string; command: string } | undefined;
783
-
784
- res.json({ active: active ?? null });
785
- return;
786
- }
787
-
788
- res.json({ active: null });
789
- });
790
-
791
- // ─── Aggregate: Manifest Health ────────────────────────────
792
-
793
- app.get('/api/orbital/aggregate/manifest/status', (_req, res) => {
794
- try {
795
- const projects = projectManager.getProjectList().filter(p => p.enabled);
796
- const pkgVersion = getPackageVersion();
797
-
798
- const projectOverviews = projects.map((proj) => {
799
- const ctx = projectManager.getContext(proj.id);
800
- if (!ctx) {
801
- return {
802
- projectId: proj.id,
803
- projectName: proj.name,
804
- projectColor: proj.color,
805
- status: 'error' as const,
806
- manifest: null,
807
- error: 'Project offline',
808
- };
809
- }
810
-
811
- try {
812
- const manifest = loadManifest(ctx.config.projectRoot);
813
- if (!manifest) {
814
- return {
815
- projectId: proj.id,
816
- projectName: proj.name,
817
- projectColor: proj.color,
818
- status: 'no-manifest' as const,
819
- manifest: null,
820
- };
821
- }
822
-
823
- const claudeDir = path.join(ctx.config.projectRoot, '.claude');
824
- refreshFileStatuses(manifest, claudeDir);
825
- const summary = summarizeManifest(manifest);
826
-
827
- return {
828
- projectId: proj.id,
829
- projectName: proj.name,
830
- projectColor: proj.color,
831
- status: 'ok' as const,
832
- manifest: {
833
- exists: true,
834
- packageVersion: pkgVersion,
835
- installedVersion: manifest.packageVersion,
836
- needsUpdate: manifest.packageVersion !== pkgVersion,
837
- preset: manifest.preset,
838
- files: summary,
839
- lastUpdated: manifest.updatedAt,
840
- },
841
- };
842
- } catch (err) {
843
- return {
844
- projectId: proj.id,
845
- projectName: proj.name,
846
- projectColor: proj.color,
847
- status: 'error' as const,
848
- manifest: null,
849
- error: String(err),
850
- };
851
- }
852
- });
853
-
854
- const projectsUpToDate = projectOverviews.filter(p => p.status === 'ok' && !p.manifest?.needsUpdate).length;
855
- const projectsOutdated = projectOverviews.filter(p => p.status === 'ok' && p.manifest?.needsUpdate).length;
856
- const noManifest = projectOverviews.filter(p => p.status === 'no-manifest').length;
857
- const totalOutdated = projectOverviews.reduce((sum, p) => sum + (p.manifest?.files.outdated ?? 0), 0);
858
- const totalModified = projectOverviews.reduce((sum, p) => sum + (p.manifest?.files.modified ?? 0), 0);
859
- const totalPinned = projectOverviews.reduce((sum, p) => sum + (p.manifest?.files.pinned ?? 0), 0);
860
- const totalMissing = projectOverviews.reduce((sum, p) => sum + (p.manifest?.files.missing ?? 0), 0);
861
- const totalSynced = projectOverviews.reduce((sum, p) => sum + (p.manifest?.files.synced ?? 0), 0);
862
- const totalUserOwned = projectOverviews.reduce((sum, p) => sum + (p.manifest?.files.userOwned ?? 0), 0);
863
-
864
- res.json({
865
- total: projects.length,
866
- projectsUpToDate,
867
- projectsOutdated,
868
- noManifest,
869
- totalOutdated,
870
- totalModified,
871
- totalPinned,
872
- totalMissing,
873
- totalSynced,
874
- totalUserOwned,
875
- projects: projectOverviews,
876
- });
877
- } catch (err) {
878
- log.error('Manifest status failed', { error: String(err) });
879
- res.status(500).json({ error: 'Failed to aggregate manifest status' });
880
- }
881
- });
882
-
883
- app.post('/api/orbital/aggregate/manifest/update-all', (_req, res) => {
884
- try {
885
- const projects = projectManager.getProjectList().filter(p => p.enabled);
886
- const pkgVersion = getPackageVersion();
887
- const results: Array<{ projectId: string; success: boolean; error?: string }> = [];
888
-
889
- for (const proj of projects) {
890
- const ctx = projectManager.getContext(proj.id);
891
- if (!ctx) {
892
- results.push({ projectId: proj.id, success: false, error: 'Project offline' });
893
- continue;
894
- }
895
-
896
- const manifest = loadManifest(ctx.config.projectRoot);
897
- if (!manifest) continue; // uninitialized — skip
898
-
899
- // Refresh statuses and check if there's anything to update
900
- const claudeDir = path.join(ctx.config.projectRoot, '.claude');
901
- refreshFileStatuses(manifest, claudeDir);
902
- const manifestSummary = summarizeManifest(manifest);
903
- if (manifest.packageVersion === pkgVersion && manifestSummary.outdated === 0 && manifestSummary.missing === 0) {
904
- continue; // fully up to date
905
- }
906
-
907
- try {
908
- runUpdate(ctx.config.projectRoot, { dryRun: false });
909
- ctx.emitter.emit('manifest:changed', { action: 'updated' });
910
- results.push({ projectId: proj.id, success: true });
911
- } catch (err) {
912
- results.push({ projectId: proj.id, success: false, error: String(err) });
913
- }
914
- }
915
-
916
- res.json({ success: true, results });
917
- } catch (err) {
918
- log.error('Update all projects failed', { error: String(err) });
919
- res.status(500).json({ error: 'Failed to update all projects' });
920
- }
921
- });
922
-
923
- // ─── Aggregate: Config Primitives (Global) ────────────────
924
- // In aggregate mode, config reads/writes target ~/.orbital/primitives/
925
- // Writes propagate to all synced (non-overridden) projects via SyncService.
926
-
927
- const globalConfigService = new ConfigService(GLOBAL_PRIMITIVES_DIR);
928
-
929
- app.get('/api/orbital/aggregate/config/:type/tree', (req, res) => {
930
- const type = req.params.type;
931
- if (!isValidPrimitiveType(type)) {
932
- res.status(400).json({ success: false, error: `Invalid type "${type}". Must be one of: agents, skills, hooks` });
933
- return;
934
- }
935
- try {
936
- const basePath = path.join(GLOBAL_PRIMITIVES_DIR, type);
937
- const tree = globalConfigService.scanDirectory(basePath);
938
- res.json({ success: true, data: tree });
939
- } catch (err) {
940
- log.error('Config tree read failed', { type, error: String(err) });
941
- res.status(500).json({ success: false, error: 'Failed to read global config tree' });
942
- }
943
- });
944
-
945
- app.get('/api/orbital/aggregate/config/:type/file', (req, res) => {
946
- const type = req.params.type;
947
- if (!isValidPrimitiveType(type)) {
948
- res.status(400).json({ success: false, error: `Invalid type "${type}". Must be one of: agents, skills, hooks` });
949
- return;
950
- }
951
- const filePath = req.query.path as string | undefined;
952
- if (!filePath) { res.status(400).json({ success: false, error: 'path query parameter is required' }); return; }
953
-
954
- try {
955
- const basePath = path.join(GLOBAL_PRIMITIVES_DIR, type);
956
- const content = globalConfigService.readFile(basePath, filePath);
957
- res.json({ success: true, data: { path: filePath, content } });
958
- } catch (err) {
959
- const msg = err instanceof Error ? err.message : String(err);
960
- const status = msg.includes('traversal') ? 403 : msg.includes('ENOENT') || msg.includes('not found') ? 404 : 500;
961
- res.status(status).json({ success: false, error: msg });
962
- }
963
- });
964
-
965
- app.put('/api/orbital/aggregate/config/:type/file', (req, res) => {
966
- const type = req.params.type;
967
- if (!isValidPrimitiveType(type)) {
968
- res.status(400).json({ success: false, error: `Invalid type "${type}". Must be one of: agents, skills, hooks` });
969
- return;
970
- }
971
- const { path: filePath, content } = req.body as { path?: string; content?: string };
972
- if (!filePath || content === undefined) {
973
- res.status(400).json({ success: false, error: 'path and content are required' });
974
- return;
975
- }
976
-
977
- try {
978
- const basePath = path.join(GLOBAL_PRIMITIVES_DIR, type);
979
- globalConfigService.writeFile(basePath, filePath, content);
980
- // Propagate to all synced projects
981
- const relativePath = path.join(type, filePath);
982
- const result = syncService.propagateGlobalChange(relativePath);
983
- io.emit(`config:${type}:changed`, { action: 'updated', path: filePath, global: true });
984
- res.json({ success: true, propagation: result });
985
- } catch (err) {
986
- const msg = err instanceof Error ? err.message : String(err);
987
- const status = msg.includes('traversal') ? 403 : msg.includes('not found') ? 404 : 500;
988
- res.status(status).json({ success: false, error: msg });
989
- }
990
- });
145
+ // Aggregate endpoints (cross-project)
146
+ app.use('/api/orbital', createAggregateRoutes({ projectManager, io, syncService }));
991
147
 
992
148
  // ─── Static File Serving ─────────────────────────────────
993
149
 
@@ -1042,28 +198,7 @@ export async function startCentralServer(overrides?: CentralServerOverrides): Pr
1042
198
  }
1043
199
  });
1044
200
 
1045
- // ─── Start Listening ─────────────────────────────────────
1046
-
1047
- const actualPort = await new Promise<number>((resolve, reject) => {
1048
- let attempt = 0;
1049
- const maxAttempts = 10;
1050
-
1051
- httpServer.on('error', (err: NodeJS.ErrnoException) => {
1052
- if (err.code === 'EADDRINUSE' && attempt < maxAttempts) {
1053
- attempt++;
1054
- httpServer.listen(port + attempt);
1055
- } else {
1056
- reject(new Error(`Failed to start server: ${err.message}`));
1057
- }
1058
- });
1059
-
1060
- httpServer.on('listening', () => {
1061
- const addr = httpServer.address();
1062
- resolve(typeof addr === 'object' && addr ? addr.port : port);
1063
- });
1064
-
1065
- httpServer.listen(port);
1066
- });
201
+ // ─── Startup Banner ──────────────────────────────────────
1067
202
 
1068
203
  const projectList = projectManager.getProjectList();
1069
204
  const projectLines = projectList.map(p =>