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
51 changes: 28 additions & 23 deletions src/commands/advanced-session.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,22 @@
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 { ContextScrubber } from '../utils/context-scrubber.js';
import SessionContext from '../utils/session-context.js';
import { UniversalPredictor } from '../services/universal-predictor.js';

Check warning on line 10 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';

const aiService = new AIService();
const memory = new NamespacedVectorMemory();

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

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

Check warning on line 20 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 @@ -78,10 +80,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 83 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 86 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 @@ -291,7 +293,7 @@

export const startSession = async () => {
console.log(chalk.cyan(`\n🚀 Nebula v${pkg.version} Session (Advanced Hybrid Shell)\n`));
await memory.initialize(SessionContext.getCwd());
if (memory) await memory.initialize(SessionContext.getCwd());
await SessionContext.initialize(SessionContext.getCwd());

const sessionHistory = [];
Expand Down Expand Up @@ -354,7 +356,7 @@
try {
process.chdir(targetDir || os.homedir());
SessionContext.setCwd(process.cwd());
await memory.initialize(process.cwd());
if (memory) await memory.initialize(process.cwd());
console.log(chalk.gray(`📂 ${process.cwd()}`));
} catch (e) {
console.log(chalk.red(`cd: ${e.message}`));
Expand Down Expand Up @@ -410,26 +412,29 @@
try {
const errorMsg = result.stderr || 'Unknown error';

// Vector Cache Check
const similar = await Promise.race([
memory.findSimilar(command, errorMsg),
new Promise(r => setTimeout(() => r([]), 3000))
]);

if (similar && similar.length > 0) {
console.log(chalk.green(`\n⚡ Instant Fix (Memory ${Math.round(similar[0].similarity * 100)}%):`));
console.log(chalk.bold(similar[0].fix));

const inquirer = (await import('inquirer')).default;
const { confirm } = await inquirer.prompt([{
type: 'confirm', name: 'confirm', message: 'Execute?', default: true
}]);

if (confirm) {
const output = await executeSystemCommand(similar[0].fix, { cwd: SessionContext.getCwd() });
console.log(output);
// Instant mode: no vector memory — go straight to AI diagnosis
if (memory) {
// Vector Cache Check
const similar = await Promise.race([
memory.findSimilar(command, errorMsg),
new Promise(r => setTimeout(() => r([]), 3000))
]);

if (similar && similar.length > 0) {
console.log(chalk.green(`\n⚡ Instant Fix (Memory ${Math.round(similar[0].similarity * 100)}%):`));
console.log(chalk.bold(similar[0].fix));

const inquirer = (await import('inquirer')).default;
const { confirm } = await inquirer.prompt([{
type: 'confirm', name: 'confirm', message: 'Execute?', default: true
}]);

if (confirm) {
const output = await executeSystemCommand(similar[0].fix, { cwd: SessionContext.getCwd() });
console.log(output);
}
return;
}
return;
}

// Smart Help Mode
Expand All @@ -446,7 +451,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 454 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 @@ -477,7 +482,7 @@
return;
}
}
} catch (e) {

Check warning on line 485 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 Expand Up @@ -509,7 +514,7 @@
const output = await executeSystemCommand(diagnosis.response, { cwd: SessionContext.getCwd() });
console.log(output);

await memory.store(command, errorMsg, diagnosis.response, { cwd: SessionContext.getCwd() });
if (memory) await memory.store(command, errorMsg, diagnosis.response, { cwd: SessionContext.getCwd() });
}
} catch (error) {
console.log(chalk.gray('Healing skipped:', error.message));
Expand Down
71 changes: 53 additions & 18 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,21 @@ const flags = {
quiet: false,
config: null,
dryRun: false,
persist: false,
instant: false
};

const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
process.env.npm_command === 'npx' ||
process.env._?.endsWith('npx');

flags.instant = isNpx;

// Propagate instant mode to all modules via env var (avoids circular imports)
if (flags.instant) {
process.env.NEBULA_INSTANT_MODE = '1';
}

for (let i = 0; i < args.length; i++) {
if (args[i] === '--verbose' || args[i] === '-v') {
flags.verbose = true;
Expand All @@ -30,8 +43,10 @@ for (let i = 0; i < args.length; i++) {
i++;
} else if (args[i] === '--dry-run' || args[i] === '-d') {
flags.dryRun = true;
} else if (args[i] === '--persist') {
flags.persist = true;
} else if (args[i] === '--help' || args[i] === '-h') {
console.log(`\n🌌 Nebula-CLI Options:\n -v, --verbose Enable verbose logging\n -q, --quiet Suppress non-essential output\n -c, --config Specify custom config file\n -d, --dry-run Run command in dry-run mode (no changes applied)\n -h, --help Show this help message\n `);
console.log(`\n🌌 Nebula-CLI Options:\n -v, --verbose Enable verbose logging\n -q, --quiet Suppress non-essential output\n -c, --config Specify custom config file\n -d, --dry-run Run command in dry-run mode (no changes applied)\n --persist Persist session to disk (used in instant mode)\n -h, --help Show this help message\n `);
process.exit(0);
} else if (args[i].startsWith('-')) {
// Unknown flag
Expand All @@ -54,7 +69,7 @@ if (flags.config) {
export { flags };

// Filter out flags from args for command processing
const KNOWN_FLAGS = ['--verbose', '-v', '--quiet', '-q', '--config', '-c', '--help', '-h', '--dry-run', '-d'];
const KNOWN_FLAGS = ['--verbose', '-v', '--quiet', '-q', '--config', '-c', '--help', '-h', '--dry-run', '-d', '--persist'];
const commandArgs = args.filter(arg =>
(!arg.startsWith('--') && !arg.startsWith('-')) || !KNOWN_FLAGS.includes(arg)
);
Expand All @@ -75,15 +90,34 @@ if (!flags.quiet) {
}

const aiService = new AIService();
const memory = new NamespacedVectorMemory();

// Instant mode: skip persistent memory, use lightweight in-memory only
const memory = flags.instant ? null : new NamespacedVectorMemory();

import { dynamicNebula } from './dynamic-transparency.js';

// Show one-time instant mode upgrade hint
function showInstantHint() {
if (flags.instant && !flags.quiet) {
console.log(chalk.gray('─────────────────────────────────────────────'));
console.log(chalk.yellow('⚡ Instant Mode — no config needed'));
console.log(chalk.gray(' Run ') + chalk.cyan('nebula setup') + chalk.gray(' to enable memory, healing patterns & advanced features.'));
console.log(chalk.gray('─────────────────────────────────────────────\n'));
}
}

(async () => {
// Show instant mode hint before first interaction
showInstantHint();

// 🔥 v5.2.1 Dynamic Startup
// Only run if interactive (no args) or specifically requested
// Skip heavy startup in instant mode — use lightweight fallback
if ((cleanedArgs.length === 0 || cleanedArgs[0] === 'session') && !process.env.SKIP_INTRO) {
await dynamicNebula.dynamicStartup(process.cwd());
if (flags.instant) {
console.log(chalk.gray('⚡ Lightweight mode — skipping project analysis'));
} else {
await dynamicNebula.dynamicStartup(process.cwd());
}
}

// 1. Nebula Predict Mode
Expand Down Expand Up @@ -362,7 +396,7 @@ ${chalk.cyan('Commands:')}
// 3. One-Shot Command Mode
const command = cleanedArgs.join(' ');
try {
await memory.initialize(process.cwd()); // Initialize Project Memory
if (memory) await memory.initialize(process.cwd()); // Initialize Project Memory (skipped in instant mode)
console.log(chalk.gray(`Running: ${command}`));
if (flags.dryRun) console.log(chalk.yellow('🧪 DRY-RUN MODE: No changes will be made.'));
const output = await executeSystemCommand(command, { dryRun: flags.dryRun });
Expand All @@ -374,20 +408,21 @@ ${chalk.cyan('Commands:')}
console.log(chalk.yellow('\n🤖 Nebula is analyzing the failure...'));

try {
// Check Vector Memory
// Check Vector Memory (skipped in instant mode — go straight to AI)
let suggestedFix;
let isCached = false;

// console.log('DEBUG MSG:', error.message); // Debugging exact error string
const similarFixes = await memory.findSimilar(command, error.message);

if (similarFixes.length > 0) {
const bestMatch = similarFixes[0];
if (bestMatch.fix && bestMatch.fix.trim().length > 0) {
suggestedFix = bestMatch.fix;
const similarity = (bestMatch.similarity * 100).toFixed(1);
console.log(chalk.green.bold(`\n⚡ Instant Fix (Vector Match: ${similarity}%)`));
isCached = true;
if (memory) {
const similarFixes = await memory.findSimilar(command, error.message);

if (similarFixes.length > 0) {
const bestMatch = similarFixes[0];
if (bestMatch.fix && bestMatch.fix.trim().length > 0) {
suggestedFix = bestMatch.fix;
const similarity = (bestMatch.similarity * 100).toFixed(1);
console.log(chalk.green.bold(`\n⚡ Instant Fix (Vector Match: ${similarity}%)`));
isCached = true;
}
}
}

Expand Down Expand Up @@ -435,7 +470,7 @@ ${chalk.cyan('Commands:')}
console.log(fixOutput);
console.log(chalk.green('✅ Fix applied successfully!'));

if (!isCached) {
if (!isCached && memory) {
await memory.store(command, error.message, suggestedFix, { cwd: process.cwd() });
}
}
Expand Down
156 changes: 156 additions & 0 deletions test/unit/instant-mode.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs';
import path from 'path';

describe('instant mode (#39)', () => {
let origArgv;
let origEnv;

beforeEach(() => {
origArgv = process.argv;
origEnv = { ...process.env };
});

afterEach(() => {
process.argv = origArgv;
process.env = origEnv;
});

describe('npx detection', () => {
it('detects npx via npm_config_user_agent', () => {
process.env.npm_config_user_agent = 'npm/x.x.x npx/x.x.x node/v22.x.x linux x64';
process.env.npm_command = undefined;

const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
process.env.npm_command === 'npx' ||
process.env._?.endsWith('npx');
expect(isNpx).toBe(true);
});

it('detects npx via npm_command', () => {
process.env.npm_config_user_agent = undefined;
process.env.npm_command = 'npx';
process.env._ = '/usr/bin/node';

const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
process.env.npm_command === 'npx' ||
process.env._?.endsWith('npx');
expect(isNpx).toBe(true);
});

it('detects npx via _ env var', () => {
process.env.npm_config_user_agent = undefined;
process.env.npm_command = undefined;
process.env._ = '/usr/bin/npx';

const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
process.env.npm_command === 'npx' ||
process.env._?.endsWith('npx');
expect(isNpx).toBe(true);
});

it('does not detect npx when run directly via node', () => {
process.env.npm_config_user_agent = 'node/v22.x.x linux x64';
process.env.npm_command = 'start';
process.env._ = '/usr/bin/node';

const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
process.env.npm_command === 'npx' ||
process.env._?.endsWith('npx');
expect(isNpx).toBe(false);
});

it('does not detect npx when env vars are undefined', () => {
process.env.npm_config_user_agent = undefined;
process.env.npm_command = undefined;
process.env._ = '/usr/bin/node';

const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
process.env.npm_command === 'npx' ||
process.env._?.endsWith('npx');
expect(isNpx).toBe(false);
});
});

describe('flags parsing', () => {
it('includes --persist in help text', async () => {
// Read the help text from index.js source
const src = fs.readFileSync(path.join(process.cwd(), 'src/index.js'), 'utf8');
expect(src).toContain('--persist');
expect(src).toContain('nebula setup');
});

it('parses --persist flag correctly', () => {
const KNOWN_FLAGS = ['--verbose', '-v', '--quiet', '-q', '--config', '-c', '--help', '-h', '--dry-run', '-d', '--persist'];
const args = ['--persist', 'ls'];
const commandArgs = args.filter(arg =>
(!arg.startsWith('--') && !arg.startsWith('-')) || !KNOWN_FLAGS.includes(arg)
);
expect(commandArgs).toContain('ls');
expect(commandArgs).not.toContain('--persist');
});

it('sets NEBULA_INSTANT_MODE env var when instant', () => {
process.env.NEBULA_INSTANT_MODE = '1';
expect(process.env.NEBULA_INSTANT_MODE).toBe('1');
delete process.env.NEBULA_INSTANT_MODE;
});
});

describe('instant mode graceful degradation', () => {
it('skips memory creation when instant mode env is set', () => {
process.env.NEBULA_INSTANT_MODE = '1';
// Simulate the conditional memory creation in advanced-session.js
const memory = process.env.NEBULA_INSTANT_MODE === '1' ? null : {};
expect(memory).toBeNull();
});

it('creates memory when instant mode is NOT set', () => {
delete process.env.NEBULA_INSTANT_MODE;
const memory = process.env.NEBULA_INSTANT_MODE === '1' ? null : {};
expect(memory).not.toBeNull();
});

it('memory findSimilar is safe to call as null check', async () => {
const memory = null;
// The advanced-session code checks `if (memory)` before calling
expect(memory).toBeFalsy();
});
});

describe('upgrade hint message', () => {
it('shows nebula setup command in upgrade hint', () => {
const src = fs.readFileSync(path.join(process.cwd(), 'src/index.js'), 'utf8');
expect(src).toContain('nebula setup');
expect(src).toContain('Instant Mode');
});

it('shows lightweight mode message in startup', () => {
const src = fs.readFileSync(path.join(process.cwd(), 'src/index.js'), 'utf8');
expect(src).toContain('Lightweight mode');
});
});

describe('session mode instant behavior', () => {
it('session still initializes SessionContext regardless of mode', () => {
const src = fs.readFileSync(path.join(process.cwd(), 'src/commands/advanced-session.js'), 'utf8');
// SessionContext should always initialize
expect(src).toContain('SessionContext.initialize');
});

it('session skips memory.initialize when memory is null', () => {
const src = fs.readFileSync(path.join(process.cwd(), 'src/commands/advanced-session.js'), 'utf8');
expect(src).toContain('if (memory) await memory.initialize');
});

it('handleAutoHealingSafe skips vector cache when memory is null', () => {
const src = fs.readFileSync(path.join(process.cwd(), 'src/commands/advanced-session.js'), 'utf8');
expect(src).toContain('if (memory)');
});

it('skips memory.store when memory is null', () => {
const src = fs.readFileSync(path.join(process.cwd(), 'src/commands/advanced-session.js'), 'utf8');
expect(src).toContain('if (memory) await memory.store');
});
});
});
Loading