#!/usr/bin/env node
// AggRoot CLI wrapper - ensures Node.js heap is large enough for long sessions.
const v8 = require('node:v8');
const path = require('node:path');
const { spawn } = require('node:child_process');
const heapLimitMB = Math.round(v8.getHeapStatistics().heap_size_limit / 1024 / 1024);

if (heapLimitMB < 3500 && !process.env.AGGROOT_SPAWNED) {
  // Re-spawn with larger heap, inheriting stdio for seamless UX
  const child = spawn(process.execPath, [
    '--max-old-space-size=4096',
    '--no-warnings',
    path.resolve(__dirname, 'index.cjs'),
    ...process.argv.slice(2),
  ], {
    stdio: 'inherit',
    env: { ...process.env, AGGROOT_SPAWNED: '1' },
  });
  child.on('error', (err) => {
    console.error('Failed to re-spawn with larger heap:', err.message);
    process.exit(1);
  });
  child.on('exit', (code) => process.exit(code ?? 0));
} else {
  require('./index.cjs');
}
