Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/commands/advanced-session.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import { executeSystemCommand, analyzeCommand, requireApproval, spawnAgent, ToolRegistry } from '../utils/advanced-executioner.js';

Check warning on line 5 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'requireApproval' is defined but never used. Allowed unused vars must match /^_/u
import { AIService } from '../services/ai.service.js';
import NamespacedVectorMemory from '../services/namespaced-memory.js';
import { TaxonomySystem } from '../services/taxonomy.js';
import { ContextScrubber } from '../utils/context-scrubber.js';
import SessionContext from '../utils/session-context.js';
import { UniversalPredictor } from '../services/universal-predictor.js';

Check warning on line 11 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'UniversalPredictor' is defined but never used. Allowed unused vars must match /^_/u
import process from 'process';
import os from 'os';

Expand All @@ -16,9 +16,10 @@

// Instant mode: skip persistent memory, lightweight in-memory session only
const memory = process.env.NEBULA_INSTANT_MODE === '1' ? null : new NamespacedVectorMemory();
const taxonomy = new TaxonomySystem();

// CRITICAL: Global error handler
process.on('unhandledRejection', (reason, promise) => {

Check warning on line 22 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'promise' is defined but never used. Allowed unused args must match /^_/u
console.error(chalk.red('⚠️ Unhandled promise:', reason));
});

Expand Down Expand Up @@ -81,10 +82,10 @@
efficiency: async () => {
const history = SessionContext.getHistory();
const { ProjectID } = await import('../utils/project-id.js');
const pid = await ProjectID.getOrCreateUID(SessionContext.getCwd());

Check warning on line 85 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'pid' is assigned a value but never used. Allowed unused vars must match /^_/u

const localHits = history.filter(h => h.includes('Instant Fix')).length;
const aiCalls = history.filter(h => h.includes('ask')).length;

Check warning on line 88 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'aiCalls' is assigned a value but never used. Allowed unused vars must match /^_/u

console.log(chalk.bold.cyan('\n📊 Nebula Token Currency Audit'));
console.log(chalk.gray('=============================================='));
Expand Down Expand Up @@ -458,6 +459,11 @@
if (confirm) {
const output = await executeSystemCommand(similar[0].fix, { cwd: SessionContext.getCwd() });
console.log(output);

// Record team pattern usage if applicable
if (similar[0].patternId && memory.teamMemory) {
memory.teamMemory.recordUsage(similar[0].patternId, true);
}
}
return;
}
Expand All @@ -477,7 +483,7 @@
const helpOutput = await executeSystemCommand(`${cmdName} --help 2>&1 || man ${cmdName} | head -n 200`, {
cwd: SessionContext.getCwd(),
silent: true
}).catch(e => '');

Check warning on line 486 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'e' is defined but never used. Allowed unused args must match /^_/u

if (helpOutput) {
const fixPrompt = `
Expand Down Expand Up @@ -508,7 +514,7 @@
return;
}
}
} catch (e) {

Check warning on line 517 in src/commands/advanced-session.js

View workflow job for this annotation

GitHub Actions / build

'e' is defined but never used. Allowed unused caught errors must match /^_/u
// Fallback
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/commands/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { TaxonomySystem } from '../services/taxonomy.js';
import { ContextScrubber } from '../utils/context-scrubber.js';
import SessionContext from '../utils/session-context.js';
import { UniversalPredictor } from '../services/universal-predictor.js';

Check warning on line 11 in src/commands/session.js

View workflow job for this annotation

GitHub Actions / build

'UniversalPredictor' is defined but never used. Allowed unused vars must match /^_/u
import process from 'process';
import os from 'os';

Expand All @@ -16,13 +16,12 @@
const memory = new NamespacedVectorMemory();
const taxonomy = new TaxonomySystem();
// Load community patterns on startup if exists
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
taxonomy.loadCommunityPatterns(path.join(__dirname, '../../data/community-patterns.json'));

// CRITICAL: Global error handler
process.on('unhandledRejection', (reason, promise) => {

Check warning on line 24 in src/commands/session.js

View workflow job for this annotation

GitHub Actions / build

'promise' is defined but never used. Allowed unused args must match /^_/u
console.error(chalk.red('⚠️ Unhandled promise:', reason));
});

Expand Down Expand Up @@ -81,7 +80,7 @@
efficiency: async () => {
const history = SessionContext.getHistory();
const { ProjectID } = await import('../utils/project-id.js');
const pid = await ProjectID.getOrCreateUID(SessionContext.getCwd());

Check warning on line 83 in src/commands/session.js

View workflow job for this annotation

GitHub Actions / build

'pid' is assigned a value but never used. Allowed unused vars must match /^_/u

// Mock calculations / Heuristics
const localHits = history.filter(h => h.includes('Instant Fix')).length; // Rough heuristic if we tracked it better
Expand Down Expand Up @@ -319,6 +318,11 @@
if (confirm) {
const output = await executeSystemCommand(similar[0].fix, { cwd: SessionContext.getCwd() });
console.log(output);

// Record team pattern usage if applicable
if (similar[0].patternId && memory.teamMemory) {
memory.teamMemory.recordUsage(similar[0].patternId, true);
}
}
return;
}
Expand Down
152 changes: 152 additions & 0 deletions src/commands/team.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import chalk from 'chalk';
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
import inquirer from 'inquirer';
import { TeamAuth } from '../services/team-auth.js';
import { TeamConfig } from '../config/team-config.js';
import { TeamMemory } from '../services/team-memory.js';
import { TeamAnalytics } from '../services/team-analytics.js';

export async function runTeamCommand(args) {
const subcommand = args[0];

if (!subcommand || subcommand === 'help') {
console.log(`
🌌 ${chalk.bold('Nebula Team Features')}

Usage: nebula team <command>

Commands:
${chalk.cyan('init')} Initialize team memory for current project
${chalk.cyan('join')} Join an existing team via invite code/SSO
${chalk.cyan('sync')} Manually sync patterns with team server
${chalk.cyan('patterns')} List stored team patterns and workflows
${chalk.cyan('analytics')} Show team usage and efficiency dashboard
${chalk.cyan('perms')} Control pattern edit permissions (admin)
${chalk.cyan('audit')} Export team audit log (admin)
${chalk.cyan('login')} Authenticate with GitHub/SSO
`);
return;
}

const auth = new TeamAuth();
const config = new TeamConfig();
const analytics = new TeamAnalytics();

switch (subcommand) {
case 'login': {
const user = (await inquirer.prompt([{
type: 'input',
name: 'user',
message: 'GitHub/SSO username:',
default: 'me'
}])).user;
console.log(chalk.yellow('Simulating OAuth Login...'));
await auth.authenticateOAuth('github', user);
console.log(chalk.green(`✅ Successfully logged in as ${user}!`));
break;
}
case 'init': {
const token = await auth.getToken();
if (!token) {
console.log(chalk.red('❌ Not logged in. Run `nebula team login` first.'));
return;
}
const { teamName } = await inquirer.prompt([{
type: 'input',
name: 'teamName',
message: 'Enter Team Name:'
}]);
const user = await auth.getUsername();
await config.save({
teamId: `team-${Date.now()}`,
teamName,
autoSync: true,
members: [user],
admins: [user],
patternPermissions: {}
});
console.log(chalk.green(`✅ Team ${teamName} initialized! You are admin.`));
break;
}
case 'analytics': {
const data = await analytics.getDashboardData();
console.log(chalk.cyan.bold('\n📊 Team Analytics Dashboard'));
console.log(chalk.white('Patterns Used: ') + chalk.green(data.efficiency.patternsUsed));
console.log(chalk.white('Time Saved: ') + chalk.green(`${Math.round(data.efficiency.timeSavedMs / 1000)}s`));
console.log(chalk.gray('\nMost Frequent Errors:'));
for (const [err, count] of Object.entries(data.errors).slice(0, 5)) {
console.log(`- ${err}: ${count}`);
}
break;
}
case 'sync': {
console.log(chalk.yellow('Syncing team patterns...'));
// Simulating sync
setTimeout(() => {
console.log(chalk.green('✅ Sync complete!'));
}, 1000);
break;
}
case 'patterns': {
const cfg = await config.load();
const memory = new TeamMemory({ teamId: cfg.teamId });
const patterns = memory.listAll();
console.log(chalk.cyan.bold('\n🧠 Team Patterns'));
if (patterns.length === 0) {
console.log(chalk.gray('No patterns stored yet.'));
} else {
patterns.forEach(p => {
const cmd = Array.isArray(p.commands) ? p.commands.join(' && ') : p.commands;
console.log(`- ${chalk.yellow(p.name)} [${p.category}]: ${chalk.white(cmd)}`);
});
}
break;
}
case 'perms': {
const user = await auth.getUsername();
const cfg = await config.load();
if (!cfg.admins.includes(user)) {
console.log(chalk.red(`❌ Only admins can control pattern permissions (${user} is not admin).`));
return;
}
const raw = args.slice(1);
if (raw.length < 2) {
console.log(chalk.gray('Usage: nebula team perms <category> <all|admin|user1,user2>'));
console.log(chalk.gray('Examples:'));
console.log(chalk.gray(' nebula team perms deploy admin'));
console.log(chalk.gray(' nebula team perms review alice,bob'));
return;
}
const [category, perm] = raw;
const patternPermissions = { ...(cfg.patternPermissions || {}), [category]: perm };
await config.save({ ...cfg, patternPermissions });
console.log(chalk.green(`✅ Permission for "${category}" set to: ${perm}`));
break;
}
case 'audit': {
const user = await auth.getUsername();
const cfg = await config.load();
if (!cfg.admins.includes(user)) {
console.log(chalk.red(`❌ Only admins can export audit logs (${user} is not admin).`));
return;
}
const memory = new TeamMemory({ teamId: cfg.teamId });
const log = memory.exportAuditLog();
const outDir = path.join(os.homedir(), '.nebula-cli', 'team');
const outFile = path.join(outDir, `audit-${new Date().toISOString().replace(/[:.]/g, '-')}.json`);
await fs.mkdir(outDir, { recursive: true });
await fs.writeFile(outFile, JSON.stringify(log, null, 2), 'utf8');
console.log(chalk.cyan.bold(`\n📋 Team Audit Log (${log.length} events)`));
for (const entry of log.slice(-5)) {
console.log(`- ${entry.timestamp} [${entry.nodeId}] ${entry.eventType} ${entry.patternId || ''}`);
}
console.log(chalk.green(`\n✅ Exported to: ${outFile}`));
break;
}
default:
console.log(chalk.red(`Unknown team command: ${subcommand}`));
console.log(chalk.gray('Run `nebula team help` for usage.'));
}
}
74 changes: 74 additions & 0 deletions src/config/team-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
import { z } from 'zod';

const TEAM_CONFIG_DIR = path.join(os.homedir(), '.nebula-cli', 'team');
const TEAM_CONFIG_FILE = path.join(TEAM_CONFIG_DIR, 'config.json');

const TeamConfigSchema = z.object({
teamId: z.string().optional(),
teamName: z.string().optional(),
ssoProvider: z.string().optional(),
syncUrl: z.string().optional(),
autoSync: z.boolean().default(true),
members: z.array(z.string()).default([]),
admins: z.array(z.string()).default([]),
patternPermissions: z.record(z.string(), z.union([z.string(), z.array(z.string())])).default({}),
});

export class TeamConfig {
constructor(options = {}) {
this.configFile = options.configFile || TEAM_CONFIG_FILE;
this.configDir = path.dirname(this.configFile);
}

async load() {
try {
const data = await fs.readFile(this.configFile, 'utf8');
const parsed = JSON.parse(data);
return TeamConfigSchema.parse(parsed);
} catch (error) {
if (error.code === 'ENOENT') {
return this.getDefaults();
}
throw new Error(`Failed to load team config: ${error.message}`, { cause: error });
}
}

async save(configData) {
try {
const validated = TeamConfigSchema.parse(configData);
await fs.mkdir(this.configDir, { recursive: true });
await fs.writeFile(this.configFile, JSON.stringify(validated, null, 2), 'utf8');
return validated;
} catch (error) {
throw new Error(`Failed to save team config: ${error.message}`, { cause: error });
}
}

getDefaults() {
return TeamConfigSchema.parse({});
}

/**
* Check whether `user` may create/edit patterns in a given category.
*
* Permission semantics for `patternPermissions[category]`:
* - undefined | 'all' -> any member may edit
* - 'admin' -> only team admins may edit
* - string[] of member names -> only those members may edit
*
* @param {object} config — a loaded TeamConfig (from load())
* @param {string} user — member identity (e.g. GitHub username)
* @param {string} [category='custom'] — pattern category
* @returns {boolean}
*/
canEditPattern(config, user, category = 'custom') {
if (!user) return false;
const perm = config.patternPermissions?.[category];
if (perm === undefined || perm === null || perm === 'all') return true;
if (perm === 'admin') return (config.admins || []).includes(user);
return Array.isArray(perm) && perm.includes(user);
}
}
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ ${chalk.cyan('Commands:')}
analyze <cmd> Analyze command for risks & PTY needs
pty <cmd> Run in PTY mode (vim, htop, ssh)
run <cmd> Smart run with auto-PTY detection
team Team workflows, patterns, and memory
plugin Manage healing plugins (list, scaffold, install, test, docs)
help Show this screen
`);
Expand Down Expand Up @@ -395,6 +396,13 @@ ${chalk.cyan('Commands:')}
return;
}

// NEW: Team Mode
if (cleanedArgs[0] === 'team') {
const { runTeamCommand } = await import('./commands/team.js');
await runTeamCommand(cleanedArgs.slice(1));
return;
}

// NEW: Plugin Mode
if (cleanedArgs[0] === 'plugin') {
const { runPluginCommand } = await import('./commands/plugin.js');
Expand Down
29 changes: 27 additions & 2 deletions src/services/namespaced-memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'path';
import os from 'os';
import ollama from 'ollama';
import { ProjectID } from '../utils/project-id.js';
import TeamMemory from './team-memory.js';

const MEMORY_DIR = path.join(os.homedir(), '.nebula-cli', 'memory'); // Cleaned up path
const DB_FILE = path.join(MEMORY_DIR, 'projects.json');
Expand All @@ -16,6 +17,11 @@ class NamespacedVectorMemory {
if (!fs.existsSync(MEMORY_DIR)) {
fs.mkdirSync(MEMORY_DIR, { recursive: true });
}
try {
this.teamMemory = new TeamMemory();
} catch (e) {
this.teamMemory = null;
}
}

/**
Expand Down Expand Up @@ -93,9 +99,28 @@ class NamespacedVectorMemory {
return projectMatches.map(m => ({ ...m, tier: 2 }));
}

// Tier 3: Global universal fixes
// Tier 3: Team Memory (shared patterns)
if (this.teamMemory && this.teamMemory.teamId) {
// Find in team memory by free-text search (we use 'error' as query to find relevant patterns)
const teamMatches = this.teamMemory.find({ search: error, limit: topK });
if (teamMatches.length > 0) {
// Return the first command from the highest matching pattern
const pattern = teamMatches[0];
if (pattern.commands && pattern.commands.length > 0) {
return [{
fix: pattern.commands[0],
similarity: 0.95, // Approximate high confidence since it matches team patterns
source: `team-memory:${pattern.name}`,
patternId: pattern.id,
tier: 3
}];
}
}
}

// Tier 4: Global universal fixes
const globalMatches = await this.searchGlobal(query, topK);
return globalMatches.map(m => ({ ...m, tier: 3 }));
return globalMatches.map(m => ({ ...m, tier: 4 }));
}

async searchNamespace(query, topK, command) {
Expand Down
Loading
Loading