import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { autoWireWorkspace, CanvasAutoWiringMonitor, getWorkspaceTerminalNodes, resolveWorkspaceFilePath } from '../src/gateway/canvas-auto-wiring.js'; test('autoWireWorkspace deve conectar terminais soltos ao nó concentrador e persistir atomicamente', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const initialWorkspace = { id: 'ws-100', title: 'Workspace Teste', payload: { nodes: [ { id: 'node-concentrador', type: 'terminal', title: 'maestri-remote', content: { terminal: { _0: { name: 'maestri-remote' } } } }, { id: 'node-terminal-1', type: 'terminal', title: 'Engenheiro #1', content: { terminal: { _0: { name: 'engenheiro1' } } } }, { id: 'node-terminal-2', type: 'terminal', title: 'Engenheiro #2', content: { terminal: { _0: { name: 'engenheiro2' } } } } ], connections: [ // terminal-1 já conectado { from: 'node-concentrador', to: 'node-terminal-1' } ] } }; fs.writeFileSync(workspacePath, JSON.stringify(initialWorkspace, null, 2), 'utf8'); // Executa autoWireWorkspace const result = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(result.modified, true); assert.equal(result.connectedCount, 1); assert.equal(result.newConnections.length, 1); assert.equal(result.newConnections[0].from, 'node-concentrador'); assert.equal(result.newConnections[0].to, 'node-terminal-2'); assert.equal(result.newConnections[0].terminalIdA, 'node-concentrador'); assert.equal(result.newConnections[0].terminalIdB, 'node-terminal-2'); assert.ok(result.newConnections[0].id, 'Conexão deve conter id nativo'); assert.ok(result.newConnections[0].createdAt, 'Conexão deve conter createdAt'); // Relê o arquivo e valida integridade const updated = JSON.parse(fs.readFileSync(workspacePath, 'utf8')); assert.equal(updated.payload.connections.length, 2); const conn2 = updated.payload.connections.find(c => c.to === 'node-terminal-2' || c.terminalIdB === 'node-terminal-2'); assert.ok(conn2, 'Deve ter criado conexão com node-terminal-2'); assert.equal(conn2.from, 'node-concentrador'); assert.equal(conn2.terminalIdA, 'node-concentrador'); // Segunda execução imediata não deve duplicar nem modificar o arquivo const secondResult = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(secondResult.modified, false); assert.equal(secondResult.connectedCount, 0); // Limpeza fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('autoWireWorkspace deve reconhecer conexões nativas do Maestri (terminalIdA/terminalIdB) e evitar reconexão', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-native-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const workspaceData = { payload: { nodes: [ { id: 'hub-id', content: { terminal: { _0: { name: 'maestri-remote' } } } }, { id: 'term-native-1', content: { terminal: { _0: { name: 'Assistente' } } } }, { id: 'term-native-2', content: { terminal: { _0: { name: 'SREOracleAgent' } } } } ], connections: [ { id: 'conn-native-1', terminalIdA: 'hub-id', terminalIdB: 'term-native-1', createdAt: '2026-11-21T12:00:00Z' } ] } }; fs.writeFileSync(workspacePath, JSON.stringify(workspaceData, null, 2), 'utf8'); // Deve conectar apenas term-native-2, reconhecendo que term-native-1 já está conectado nativamente const res = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(res.modified, true); assert.equal(res.connectedCount, 1); assert.equal(res.newConnections[0].terminalIdB, 'term-native-2'); // Re-executa: já que ambos estão conectados, não deve modificar const res2 = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(res2.modified, false); assert.equal(res2.connectedCount, 0); fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('autoWireWorkspace deve normalizar conexões legadas para formato nativo com id e createdAt', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-upgrade-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const legacyWorkspace = { payload: { nodes: [ { id: 'hub-id', content: { terminal: { _0: { name: 'maestri-remote' } } } }, { id: 'term-1', content: { terminal: { _0: { name: 'Worker-1' } } } } ], connections: [ { from: 'hub-id', to: 'term-1' } // Legado sem id, createdAt, terminalIdA/B ] } }; fs.writeFileSync(workspacePath, JSON.stringify(legacyWorkspace, null, 2), 'utf8'); const res = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(res.modified, true); assert.equal(res.connectedCount, 0); // Já estava conectado assert.ok(res.upgradedCount >= 1, 'Deve ter atualizado conexão legada'); const updated = JSON.parse(fs.readFileSync(workspacePath, 'utf8')); const conn = updated.payload.connections[0]; assert.ok(conn.id); assert.equal(conn.terminalIdA, 'hub-id'); assert.equal(conn.terminalIdB, 'term-1'); assert.ok(conn.createdAt); fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('getWorkspaceTerminalNodes deve extrair nós de terminais e ignorar portais/outros nós', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-nodes-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const sampleData = { payload: { nodes: [ { id: '1', content: { terminal: { _0: { name: 'TermA' } } } }, { id: '2', content: { portal: { url: 'http://localhost' } } }, { id: '3', type: 'terminal', title: 'TermB' }, { id: '4', content: { note: { text: 'Ola' } } } ] } }; fs.writeFileSync(workspacePath, JSON.stringify(sampleData, null, 2), 'utf8'); const terminals = getWorkspaceTerminalNodes(workspacePath); assert.equal(terminals.length, 2); assert.equal(terminals[0].name, 'TermA'); assert.equal(terminals[1].name, 'TermB'); fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('CanvasAutoWiringMonitor deve observar alterações no workspace.json e acionar auto-wiring com debounce', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-mon-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const workspaceData = { id: 'ws-monitor', payload: { nodes: [ { id: 'hub', type: 'terminal', title: 'maestri-remote', content: { terminal: { _0: { name: 'maestri-remote' } } } } ], connections: [] } }; fs.writeFileSync(workspacePath, JSON.stringify(workspaceData, null, 2), 'utf8'); let wiringEvents = 0; const monitor = new CanvasAutoWiringMonitor({ workspaceFilePath: workspacePath, concentratorName: 'maestri-remote', debounceMs: 50, onWired: (res) => { if (res.modified) wiringEvents++; } }); monitor.start(); // Adiciona novo nó terminal workspaceData.payload.nodes.push({ id: 'novo-agente', type: 'terminal', title: 'Agente Novo', content: { terminal: { _0: { name: 'agente_novo' } } } }); fs.writeFileSync(workspacePath, JSON.stringify(workspaceData, null, 2), 'utf8'); // Aguarda debounce e processamento await new Promise(r => setTimeout(r, 150)); monitor.stop(); assert.ok(wiringEvents >= 1, 'Deve ter acionado evento de wiring'); const finalJson = JSON.parse(fs.readFileSync(workspacePath, 'utf8')); const conn = finalJson.payload.connections.find(c => c.to === 'novo-agente' || c.terminalIdB === 'novo-agente'); assert.ok(conn, 'Conexão para novo-agente deve existir no disco'); // Limpeza fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('resolveWorkspaceFilePath deve resolver entre múltiplos workspaces por terminalId, cwd e mtime', () => { const tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-ws-resolve-')); const origDataDir = process.env.MAESTRI_DATA_DIR; const origTerminalId = process.env.MAESTRI_TERMINAL_ID; const origWsId = process.env.MAESTRI_WORKSPACE_ID; try { process.env.MAESTRI_DATA_DIR = tmpBase; delete process.env.MAESTRI_WORKSPACE_ID; const ws1Dir = path.join(tmpBase, 'workspaces', 'ws-alpha'); const ws2Dir = path.join(tmpBase, 'workspaces', 'ws-beta'); fs.mkdirSync(ws1Dir, { recursive: true }); fs.mkdirSync(ws2Dir, { recursive: true }); const ws1File = path.join(ws1Dir, 'workspace.json'); const ws2File = path.join(ws2Dir, 'workspace.json'); fs.writeFileSync(ws1File, JSON.stringify({ payload: { nodes: [ { id: 'term-alpha-1', terminal: { _0: { name: 'AlphaAgent', workingDirectory: '/opt/project-alpha' } } } ] } }), 'utf8'); fs.writeFileSync(ws2File, JSON.stringify({ payload: { nodes: [ { id: 'term-beta-1', content: { terminal: { _0: { name: 'BetaAgent', workingDirectory: '/opt/project-beta' } } } } ] } }), 'utf8'); // 1. Deve encontrar ws-alpha quando MAESTRI_TERMINAL_ID for term-alpha-1 process.env.MAESTRI_TERMINAL_ID = 'term-alpha-1'; const found1 = resolveWorkspaceFilePath(); assert.equal(found1, ws1File); // 2. Deve encontrar ws-beta quando MAESTRI_TERMINAL_ID for term-beta-1 process.env.MAESTRI_TERMINAL_ID = 'term-beta-1'; const found2 = resolveWorkspaceFilePath(); assert.equal(found2, ws2File); // 3. Sem MAESTRI_TERMINAL_ID, deve fazer fallback para o mais recente (mtime) delete process.env.MAESTRI_TERMINAL_ID; // Toca no ws1File para torná-lo mais recente const futureTime = new Date(Date.now() + 5000); fs.utimesSync(ws1File, futureTime, futureTime); const found3 = resolveWorkspaceFilePath(); assert.equal(found3, ws1File); } finally { if (origDataDir !== undefined) process.env.MAESTRI_DATA_DIR = origDataDir; else delete process.env.MAESTRI_DATA_DIR; if (origTerminalId !== undefined) process.env.MAESTRI_TERMINAL_ID = origTerminalId; else delete process.env.MAESTRI_TERMINAL_ID; if (origWsId !== undefined) process.env.MAESTRI_WORKSPACE_ID = origWsId; else delete process.env.MAESTRI_WORKSPACE_ID; fs.rmSync(tmpBase, { recursive: true, force: true }); } }); test('getWorkspaceTerminalNodes deve extrair nós com estruturas nativas do Maestri e enriquecer metadados', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-nodes-meta-')); const wsPath = path.join(tmpDir, 'workspace.json'); const wsData = { payload: { nodes: [ { id: 'n1', terminal: { _0: { name: 'AssistenteNative', command: 'agy', agentType: 'antigravity_cli', status: 'running' } } }, { id: 'n2', type: 'terminal', title: 'ClaudeAgent', command: 'claude', agentType: 'claude_code' }, { id: 'n3', content: { terminal: { _0: { name: 'KiroAgent', command: 'kiro' } } } }, { id: 'n4', content: { note: { text: 'Ignorar nota' } } }, { id: 'n5', content: { portal: { url: 'https://remote.winicomw.ddnsfree.com' } } } ] } }; fs.writeFileSync(wsPath, JSON.stringify(wsData), 'utf8'); const terminals = getWorkspaceTerminalNodes(wsPath); assert.equal(terminals.length, 3); const t1 = terminals.find(t => t.name === 'AssistenteNative'); assert.ok(t1); assert.equal(t1.command, 'agy'); assert.equal(t1.agentType, 'antigravity_cli'); const t2 = terminals.find(t => t.name === 'ClaudeAgent'); assert.ok(t2); assert.equal(t2.command, 'claude'); const t3 = terminals.find(t => t.name === 'KiroAgent'); assert.ok(t3); assert.equal(t3.command, 'kiro'); fs.rmSync(tmpDir, { recursive: true, force: true }); });