company.js 33.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
/**
 * Company Routes — 公司管理 API
 *
 * 挂载: /api/company
 */

const express = require('express');
const router = express.Router();
const { CompanyService } = require('../services/company-service');
const { ScheduleService } = require('../services/schedule-service');

const companyService = new CompanyService();
const scheduleService = new ScheduleService();

// ═══════════════════════════════════════
//  Company CRUD
// ═══════════════════════════════════════

// POST /api/company/create
router.post('/create', async (req, res) => {
  try {
    const { id, name, description, skipBootstrap } = req.body;
    if (!id || !name) return res.status(400).json({ error: 'id 和 name 为必填项' });

    // 校验 id 格式 (小写字母、数字、-) 
    if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(id) && id.length < 2) {
      return res.status(400).json({ error: 'id 格式无效 (只允许小写字母、数字、-)' });
    }

    const company = companyService.create({ id, name, description });

    // ── Phase A: Company Bootstrap 自举 ──
    // 读取 _company_bootstrap/manifest.json,自动部署核心骨干
    const bootstrapResults = [];
    if (!skipBootstrap) {
      const path = require('path');
      const fs = require('fs');
      const manifestPath = path.resolve(__dirname, '../../data/templates/_company_bootstrap/manifest.json');
      
      if (fs.existsSync(manifestPath)) {
        const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
        const agents = manifest.bootstrap_agents || [];
        
        for (const agentDef of agents) {
          try {
            const hireResult = companyService.hire(id, agentDef.role, {
              type: agentDef.type,
              name: agentDef.name,
            });
            bootstrapResults.push({ role: agentDef.role, status: hireResult.status });
            console.log(`[Bootstrap] ✅ ${id} 自动部署 ${agentDef.role} → ${hireResult.status}`);
          } catch (err) {
            bootstrapResults.push({ role: agentDef.role, status: 'error', error: err.message });
            console.error(`[Bootstrap] ❌ ${id} 部署 ${agentDef.role} 失败:`, err.message);
          }
        }

        // 自动启动公司 + 激活心跳
        companyService.update(id, { status: 'running', heartbeat: { enabled: true } });

        // 自动向 CEO 下达启动令 (异步不阻塞)
        if (manifest.auto_dispatch_to_ceo && description) {
          const config = require('../config');
          const PORT = config.port || 3000;
          const startupPrompt = `${manifest.ceo_startup_prompt || '请执行你的五步战略工作流'}\n\n公司名称: ${name}\n公司描述/业务需求: ${description}`;
          
          setTimeout(() => {
            const http = require('http');
            const postData = JSON.stringify({
              from: 'master', to: `${id}:ceo`,
              task: startupPrompt, priority: 'P0', autoExecute: true,
            });
            const reqOpts = {
              hostname: '127.0.0.1', port: PORT, path: '/api/agent/task/dispatch',
              method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) },
            };
            const r = http.request(reqOpts, () => {});
            r.on('error', e => console.error('[Bootstrap] CEO dispatch 失败:', e.message));
            r.write(postData);
            r.end();
            console.log(`[Bootstrap] 🚀 已向 ${id}:ceo 发送启动战略指令`);
          }, 2000);
        }

        console.log(`[Bootstrap] 🏢 公司 ${id} 已完成自举,部署了 ${bootstrapResults.length} 名核心骨干`);
      }
    }

    res.json({ success: true, company, bootstrap: bootstrapResults });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/list
router.get('/list', (req, res) => {
  res.json(companyService.list());
});

// GET /api/company/templates
router.get('/templates', (req, res) => {
  res.json(companyService.listTemplates());
});

// GET /api/company/:companyId
router.get('/:companyId', (req, res) => {
  const company = companyService.get(req.params.companyId);
  if (!company) return res.status(404).json({ error: '公司不存在' });
  res.json(company);
});

// PUT /api/company/:companyId
router.put('/:companyId', (req, res) => {
  const company = companyService.update(req.params.companyId, req.body);
  if (!company) return res.status(404).json({ error: '公司不存在' });
  res.json({ success: true, company });
});

// POST /api/company/:companyId/shutdown
router.post('/:companyId/shutdown', (req, res) => {
  const company = companyService.shutdown(req.params.companyId);
  if (!company) return res.status(404).json({ error: '公司不存在' });

  // 停止该公司下所有 Agent 的心跳
  try {
    const heartbeatService = require('../services/heartbeat-service');
    const agents = companyService.listAgents(req.params.companyId);
    for (const agent of agents) {
      const namespacedId = `${req.params.companyId}:${agent.id}`;
      if (heartbeatService.timers.has(namespacedId)) {
        clearInterval(heartbeatService.timers.get(namespacedId));
        heartbeatService.timers.delete(namespacedId);
        console.log(`[Company] 🛑 已停止 ${namespacedId} 的心跳`);
      }
    }
  } catch (err) {
    console.warn(`[Company] ⚠️ 停止心跳时出错: ${err.message}`);
  }

  res.json({ success: true, company });
});

// POST /api/company/:companyId/start — 启动公司
router.post('/:companyId/start', (req, res) => {
  try {
    const company = companyService.get(req.params.companyId);
    if (!company) return res.status(404).json({ error: '公司不存在' });

    // 更新状态
    const updated = companyService.update(req.params.companyId, {
      status: 'running',
      heartbeat: { enabled: true },
    });

    // 激活该公司下所有 Agent 的心跳
    try {
      const heartbeatService = require('../services/heartbeat-service');
      const agents = companyService.listAgents(req.params.companyId);
      for (const agent of agents) {
        const namespacedId = `${req.params.companyId}:${agent.id}`;
        heartbeatService._setupAgentHeartbeat(namespacedId);
      }
      console.log(`[Company] ✅ ${req.params.companyId} 已启动,${agents.length} 个 Agent 心跳已激活`);
    } catch (err) {
      console.warn(`[Company] ⚠️ 激活心跳时出错: ${err.message}`);
    }

    res.json({ success: true, company: updated });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// GET /api/company/:companyId/status — 获取公司运行状态(含 Agent 进程信息)
router.get('/:companyId/status', (req, res) => {
  try {
    const company = companyService.get(req.params.companyId);
    if (!company) return res.status(404).json({ error: '公司不存在' });

    const agents = companyService.listAgents(req.params.companyId);
    const heartbeatService = require('../services/heartbeat-service');
    const path = require('path');
    const fs = require('fs');
    const DATA_DIR = path.resolve(__dirname, '../../data');

    // 计算运行时长
    const uptimeMs = company.status === 'running' && company.startedAt
      ? Date.now() - new Date(company.startedAt).getTime()
      : 0;

    const agentStatuses = agents.map(agent => {
      const namespacedId = `${req.params.companyId}:${agent.id}`;
      const hasHeartbeat = heartbeatService.timers.has(namespacedId);

      // 读取每个 Agent 自己的心跳配置
      let heartbeatConfig = { enabled: false, intervalMinutes: 15 };
      try {
        const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', agent.id, 'config.json');
        if (fs.existsSync(configPath)) {
          const cfg = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
          if (cfg.heartbeat) {
            heartbeatConfig = cfg.heartbeat;
          }
        }
      } catch {}

      return {
        id: agent.id,
        name: agent.name,
        type: agent.type,
        status: agent.status,
        heartbeatActive: hasHeartbeat,
        heartbeatEnabled: heartbeatConfig.enabled || false,
        heartbeatInterval: heartbeatConfig.intervalMinutes || 15,
      };
    });

    res.json({
      id: company.id,
      name: company.name,
      description: company.description,
      status: company.status,
      createdAt: company.createdAt,
      updatedAt: company.updatedAt,
      startedAt: company.startedAt || null,
      uptimeMs,
      heartbeat: company.heartbeat,
      agents: agentStatuses,
      agentCount: agents.length,
      activeAgentCount: agentStatuses.filter(a => a.heartbeatActive).length,
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// ═══════════════════════════════════════
//  Per-Agent 心跳控制
// ═══════════════════════════════════════

// PUT /api/company/:companyId/agents/:agentId/heartbeat — 更新 Agent 心跳配置
router.put('/:companyId/agents/:agentId/heartbeat', (req, res) => {
  try {
    const { intervalMinutes, enabled } = req.body;
    const path = require('path');
    const fs = require('fs');
    const DATA_DIR = path.resolve(__dirname, '../../data');
    const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'config.json');

    if (!fs.existsSync(configPath)) {
      return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` });
    }

    const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
    if (!config.heartbeat) config.heartbeat = { intervalMinutes: 15, enabled: false };
    
    // 保证有合理的默认值
    if (config.heartbeat.intervalMinutes === undefined) config.heartbeat.intervalMinutes = 15;
    if (config.heartbeat.enabled === undefined) config.heartbeat.enabled = false;

    if (intervalMinutes !== undefined) config.heartbeat.intervalMinutes = Number(intervalMinutes);
    if (enabled !== undefined) config.heartbeat.enabled = Boolean(enabled);
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');

    // 如果正在运行,重新挂载心跳
    const heartbeatService = require('../services/heartbeat-service');
    const namespacedId = `${req.params.companyId}:${req.params.agentId}`;
    if (config.heartbeat.enabled) {
      heartbeatService._setupAgentHeartbeat(namespacedId);
    } else if (heartbeatService.timers.has(namespacedId)) {
      clearInterval(heartbeatService.timers.get(namespacedId));
      heartbeatService.timers.delete(namespacedId);
    }

    console.log(`[Company] ⚙️ ${namespacedId} 心跳配置更新: interval=${config.heartbeat.intervalMinutes}min, enabled=${config.heartbeat.enabled}`);
    res.json({ success: true, heartbeat: config.heartbeat });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// POST /api/company/:companyId/agents/:agentId/heartbeat/start — 启动单个 Agent 心跳
router.post('/:companyId/agents/:agentId/heartbeat/start', (req, res) => {
  try {
    const path = require('path');
    const fs = require('fs');
    const DATA_DIR = path.resolve(__dirname, '../../data');
    const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'config.json');

    if (!fs.existsSync(configPath)) {
      return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` });
    }

    // 更新 config 中的 enabled
    const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
    if (!config.heartbeat) config.heartbeat = { intervalMinutes: 15 };
    config.heartbeat.enabled = true;
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');

    // 激活心跳
    const heartbeatService = require('../services/heartbeat-service');
    const namespacedId = `${req.params.companyId}:${req.params.agentId}`;
    heartbeatService._setupAgentHeartbeat(namespacedId);

    console.log(`[Company] 💓 ${namespacedId} 心跳已启动`);
    res.json({ success: true, message: `${namespacedId} 心跳已启动` });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// POST /api/company/:companyId/agents/:agentId/heartbeat/stop — 停止单个 Agent 心跳
router.post('/:companyId/agents/:agentId/heartbeat/stop', (req, res) => {
  try {
    const path = require('path');
    const fs = require('fs');
    const DATA_DIR = path.resolve(__dirname, '../../data');
    const configPath = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'config.json');

    if (!fs.existsSync(configPath)) {
      return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` });
    }

    // 更新 config 中的 enabled
    const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
    if (!config.heartbeat) config.heartbeat = {};
    config.heartbeat.enabled = false;
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');

    // 停止心跳
    const heartbeatService = require('../services/heartbeat-service');
    const namespacedId = `${req.params.companyId}:${req.params.agentId}`;
    if (heartbeatService.timers.has(namespacedId)) {
      clearInterval(heartbeatService.timers.get(namespacedId));
      heartbeatService.timers.delete(namespacedId);
    }

    console.log(`[Company] 🛑 ${namespacedId} 心跳已停止`);
    res.json({ success: true, message: `${namespacedId} 心跳已停止` });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// ═══════════════════════════════════════
//  Agent 技能查询
// ═══════════════════════════════════════

// GET /api/company/:companyId/agents/:agentId/skills — 获取 Agent 技能列表
router.get('/:companyId/agents/:agentId/skills', (req, res) => {
  try {
    const path = require('path');
    const fs = require('fs');
    const DATA_DIR = path.resolve(__dirname, '../../data');
    const skillsDir = path.join(DATA_DIR, req.params.companyId, 'agents', req.params.agentId, 'skills');

    if (!fs.existsSync(skillsDir)) {
      return res.json([]);
    }

    const skills = fs.readdirSync(skillsDir, { withFileTypes: true })
      .filter(d => d.isDirectory())
      .map(d => d.name);

    res.json(skills);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// ═══════════════════════════════════════
//  Agent 招聘
// ═══════════════════════════════════════

// POST /api/company/:companyId/hire
router.post('/:companyId/hire', async (req, res) => {
  try {
    const { role, type, name, description, customAgent, customSoul, customUser } = req.body;
    if (!role) return res.status(400).json({ error: 'role 为必填项' });

    const result = await companyService.hireWithTraining(req.params.companyId, role, {
      type, name: name || role, description, customAgent, customSoul, customUser,
    });

    // ── 核心逻辑扩展:自动补充定义 + 搜索注入 3 个初始 Skill + Innovator 训练 ──
    if (result.status === 'training' || result.needsTraining) {
      (async () => {
        try {
          console.log(`[Hire] 🚀 自动流水线启动: 为新员工 ${role} 安排 [定义 → 技能注入 → 训练]`);
          const fs = require('fs');
          const path = require('path');
          const config = require('../config');
          const skillDb = require('../services/skill-db');
          
          const namespacedId = `${req.params.companyId}:${role}`;
          const agentDir = result.agentDir || path.resolve(__dirname, '../../data', req.params.companyId, 'agents', role);
          const PORT = config.port || 3000;

          // 1. 发起 Agent-Creator 编写骨架定义 (异步不等待)
          fetch(`http://127.0.0.1:${PORT}/api/agent/agent-creator/chat`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              message: `新员工 ${namespacedId} 已由脚手架创建空白目录在 \`../${req.params.companyId}/agents/${role}\`。工作需求: ${description || name || role}。\n请你按照标准模板,使用 Write 工具为该员工补充完整的定义文件(agent.md, identity.md, soul.md, user.md等)并使用工具 ls 验证。务必要使用 Write 写文件,不要使用 Edit 工具。写完后请答复。`,
              conversationId: `create-${req.params.companyId}-${role}-${Date.now().toString(36)}`
            })
          }).catch(e => console.error('[Hire] Agent-Creator 请求错误:', e.message));

          // 2. 去网上/Arena搜索并注入 3 个基础 Skill
          const skills = skillDb.searchSkills(role, { limit: 3 });
          const skillsDir = path.join(agentDir, 'skills');
          if (skills && skills.length > 0) {
            if (!fs.existsSync(skillsDir)) fs.mkdirSync(skillsDir, { recursive: true });
            
            const copyDir = (src, dest) => {
              fs.mkdirSync(dest, { recursive: true });
              const entries = fs.readdirSync(src, { withFileTypes: true });
              for (const e of entries) {
                if (e.isDirectory()) copyDir(path.join(src, e.name), path.join(dest, e.name));
                else fs.copyFileSync(path.join(src, e.name), path.join(dest, e.name));
              }
            };

            for (const skill of skills) {
              if (skill.directory && fs.existsSync(skill.directory)) {
                const targetPath = path.join(skillsDir, skill.skillName);
                if (!fs.existsSync(targetPath)) {
                  try {
                    copyDir(skill.directory, targetPath);
                    console.log(`[Hire] 💉 成功为其注入基础技能: ${skill.skillName}`);
                  } catch (e) {
                    console.error(`[Hire] 注入技能 ${skill.skillName} 失败:`, e.message);
                  }
                }
              }
            }
          } else {
            console.log(`[Hire] ⚠️ 网上/Arena 未找到该角色的匹配 Skill,将交由 Innovator 凭空生成`);
          }

          // 3. 延时 5 秒触发 Innovator 进行评估与训练 (等 creator 写入完毕)
          setTimeout(() => {
            fetch(`http://127.0.0.1:${PORT}/api/agent/innovator/chat`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                message: `公司 ${req.params.companyId} 的员工 ${role} 骨架和基础技能已注入完毕。请你使用 FDE pipeline 对该 Agent ${namespacedId} (特别是它的技能)进行评测和进化训练,直到 Benchmark 达标 (Score ≥ 95)。训练过程包括 Hunt(验证数据), Digest, Evolver 等。请立即开始评估和训练,并保持向我汇报。`,
                conversationId: `train-${req.params.companyId}-${role}-${Date.now().toString(36)}`
              })
            }).catch(e => console.error('[Hire] Innovator 请求错误:', e.message));
          }, 5000);

        } catch (err) {
          console.error(`[Hire Orchestration] 自动流水线编排异常: ${err.message}`);
        }
      })();
    }

    // ── P0 FIX: 动态心跳挂载 ──
    // 招聘成功后,立即为这个新 Agent 注册心跳定时器(如果它的 config.json 里 heartbeat.enabled = true)
    try {
      const heartbeatService = require('../services/heartbeat-service');
      const namespacedId = `${req.params.companyId}:${role}`;
      heartbeatService._setupAgentHeartbeat(namespacedId);
      console.log(`[Hire] 💓 已为 ${namespacedId} 动态挂载心跳`);
    } catch (hbErr) {
      console.warn(`[Hire] ⚠️ 心跳挂载跳过: ${hbErr.message}`);
    }

    res.json(result);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// POST /api/company/:companyId/fire — 辞退 Agent(招留管退之"退")
router.post('/:companyId/fire', (req, res) => {
  try {
    const { role, archive } = req.body;
    if (!role) return res.status(400).json({ error: 'role 为必填项' });

    const path = require('path');
    const fs = require('fs');
    const DATA_DIR = path.resolve(__dirname, '../../data');
    const companyId = req.params.companyId;
    const agentDir = path.join(DATA_DIR, companyId, 'agents', role);

    if (!fs.existsSync(agentDir)) {
      return res.status(404).json({ error: `Agent ${role} 不存在于公司 ${companyId}` });
    }

    // 1. 停止心跳
    const heartbeatService = require('../services/heartbeat-service');
    const namespacedId = `${companyId}:${role}`;
    if (heartbeatService.timers.has(namespacedId)) {
      clearInterval(heartbeatService.timers.get(namespacedId));
      heartbeatService.timers.delete(namespacedId);
    }

    // 2. 归档或直接删除
    if (archive !== false) {
      const archiveDir = path.join(DATA_DIR, companyId, '_archived_agents', role);
      fs.mkdirSync(path.dirname(archiveDir), { recursive: true });
      fs.renameSync(agentDir, archiveDir);
      console.log(`[Fire] 📦 ${namespacedId} 已归档到 ${archiveDir}`);
    } else {
      fs.rmSync(agentDir, { recursive: true, force: true });
      console.log(`[Fire] 🗑️ ${namespacedId} 已彻底删除`);
    }

    // 3. 从公司 agents 列表中移除
    const company = companyService.get(companyId);
    if (company) {
      company.agents = (company.agents || []).filter(a => a !== role);
      company.updatedAt = new Date().toISOString();
      companyService._saveCompany(company);
    }

    console.log(`[Fire] 🔴 ${namespacedId} 已辞退`);
    res.json({ success: true, message: `${namespacedId} 已辞退`, archived: archive !== false });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});


// POST /api/company/:companyId/deposit-template — 训练合格后沉淀为模板
router.post('/:companyId/deposit-template', (req, res) => {
  try {
    const { agentId, benchmarkScore } = req.body;
    if (!agentId || benchmarkScore === undefined) {
      return res.status(400).json({ error: 'agentId 和 benchmarkScore 为必填项' });
    }

    const result = companyService.depositTemplate(
      req.params.companyId, agentId, Number(benchmarkScore)
    );
    res.json(result);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/:companyId/agents
router.get('/:companyId/agents', (req, res) => {
  const agents = companyService.listAgents(req.params.companyId);
  res.json(agents);
});

// ═══════════════════════════════════════
//  Company Goals / OKR (公司级 OKR)
// ═══════════════════════════════════════

const { GoalsService } = require('../services/goals');

// GET /api/company/:companyId/goals
router.get('/:companyId/goals', (req, res) => {
  const goals = new GoalsService(req.params.companyId);
  res.json(goals.list());
});

// POST /api/company/:companyId/goals
router.post('/:companyId/goals', (req, res) => {
  try {
    const { title, description, owner } = req.body;
    if (!title || !owner) {
      return res.status(400).json({ error: 'title 和 owner 为必填项' });
    }
    const goals = new GoalsService(req.params.companyId);
    const goal = goals.create({ title, description, owner });
    res.status(201).json(goal);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// GET /api/company/:companyId/goals/:goalId
router.get('/:companyId/goals/:goalId', (req, res) => {
  const goals = new GoalsService(req.params.companyId);
  const goal = goals.get(req.params.goalId);
  if (!goal) return res.status(404).json({ error: 'Goal not found' });
  res.json(goal);
});

// PUT /api/company/:companyId/goals/:goalId
router.put('/:companyId/goals/:goalId', (req, res) => {
  const goals = new GoalsService(req.params.companyId);
  const result = goals.updateGoal(req.params.goalId, req.body);
  if (!result) return res.status(404).json({ error: 'Goal not found' });
  res.json(result);
});

// POST /api/company/:companyId/goals/:goalId/nodes
router.post('/:companyId/goals/:goalId/nodes', (req, res) => {
  try {
    const { parentNodeId, title, owner, priority } = req.body;
    if (!title || !owner) {
      return res.status(400).json({ error: 'title 和 owner 为必填项' });
    }
    const goals = new GoalsService(req.params.companyId);
    const result = goals.addNode(req.params.goalId, parentNodeId || null, {
      title, owner, priority,
    });
    if (!result) return res.status(404).json({ error: 'Goal not found' });
    res.status(201).json({ nodeId: result.nodeId, node: result.goal.nodes[result.nodeId] });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// PUT /api/company/:companyId/goals/:goalId/nodes/:nodeId
router.put('/:companyId/goals/:goalId/nodes/:nodeId', (req, res) => {
  const goals = new GoalsService(req.params.companyId);
  const result = goals.updateNode(req.params.goalId, req.params.nodeId, req.body);
  if (!result) return res.status(404).json({ error: 'Node not found' });
  res.json({ nodeId: result.nodeId, node: result.node });
});

// GET /api/company/:companyId/goals/:goalId/progress
router.get('/:companyId/goals/:goalId/progress', (req, res) => {
  const goals = new GoalsService(req.params.companyId);
  const progress = goals.getProgress(req.params.goalId);
  if (!progress) return res.status(404).json({ error: 'Goal not found' });
  res.json(progress);
});

// ═══════════════════════════════════════
//  Pipeline / SOP 流水线
// ═══════════════════════════════════════

const { PipelineService } = require('../services/pipeline-service');

// POST /api/company/:companyId/pipelines — 创建流水线
router.post('/:companyId/pipelines', (req, res) => {
  try {
    const pSvc = new PipelineService(req.params.companyId);
    const pipeline = pSvc.createPipeline(req.body);
    res.status(201).json(pipeline);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/:companyId/pipelines — 列出流水线
router.get('/:companyId/pipelines', (req, res) => {
  const pSvc = new PipelineService(req.params.companyId);
  res.json(pSvc.listPipelines());
});

// GET /api/company/:companyId/pipelines/:pipelineId — 获取流水线定义
router.get('/:companyId/pipelines/:pipelineId', (req, res) => {
  const pSvc = new PipelineService(req.params.companyId);
  const pipeline = pSvc.getPipeline(req.params.pipelineId);
  if (!pipeline) return res.status(404).json({ error: '流水线不存在' });
  res.json(pipeline);
});

// PUT /api/company/:companyId/pipelines/:pipelineId — 更新流水线
router.put('/:companyId/pipelines/:pipelineId', (req, res) => {
  const pSvc = new PipelineService(req.params.companyId);
  const pipeline = pSvc.updatePipeline(req.params.pipelineId, req.body);
  if (!pipeline) return res.status(404).json({ error: '流水线不存在' });
  res.json(pipeline);
});

// POST /api/company/:companyId/pipelines/:pipelineId/run — 启动运行
router.post('/:companyId/pipelines/:pipelineId/run', (req, res) => {
  try {
    const pSvc = new PipelineService(req.params.companyId);
    const run = pSvc.startRun(req.params.pipelineId, req.body);
    res.status(201).json(run);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/:companyId/pipelines/runs/list — 列出运行记录
router.get('/:companyId/pipelines/runs/list', (req, res) => {
  const pSvc = new PipelineService(req.params.companyId);
  res.json(pSvc.listRuns(req.query.pipelineId));
});

// GET /api/company/:companyId/pipelines/runs/:runId — 获取运行详情
router.get('/:companyId/pipelines/runs/:runId', (req, res) => {
  const pSvc = new PipelineService(req.params.companyId);
  const run = pSvc.getRun(req.params.runId);
  if (!run) return res.status(404).json({ error: '运行记录不存在' });
  res.json(run);
});

// POST /api/company/:companyId/pipelines/runs/:runId/advance — 推进步骤
router.post('/:companyId/pipelines/runs/:runId/advance', (req, res) => {
  try {
    const pSvc = new PipelineService(req.params.companyId);
    const { stepIndex, output, status } = req.body;
    if (stepIndex === undefined) return res.status(400).json({ error: 'stepIndex 为必填项' });
    const run = pSvc.advanceStep(req.params.runId, Number(stepIndex), { output, status });
    res.json(run);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/:companyId/pipelines/runs/:runId/current — 获取当前任务
router.get('/:companyId/pipelines/runs/:runId/current', (req, res) => {
  const pSvc = new PipelineService(req.params.companyId);
  const task = pSvc.getCurrentTask(req.params.runId);
  if (!task) return res.json({ message: '无就绪任务' });
  res.json(task);
});

// POST /api/company/:companyId/pipelines/runs/:runId/reject — COO 驳回步骤
router.post('/:companyId/pipelines/runs/:runId/reject', (req, res) => {
  try {
    const pSvc = new PipelineService(req.params.companyId);
    const { stepIndex, reason, reviewedBy } = req.body;
    if (stepIndex === undefined) return res.status(400).json({ error: 'stepIndex 为必填项' });
    const run = pSvc.rejectStep(req.params.runId, Number(stepIndex), {
      reason: reason || '',
      reviewedBy: reviewedBy || 'coo',
    });
    res.json(run);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// ═══════════════════════════════════════
//  Schedule (日程管理)
// ═══════════════════════════════════════

// GET /api/company/:companyId/schedule — 获取日程
router.get('/:companyId/schedule', (req, res) => {
  res.json(scheduleService.getSchedule(req.params.companyId));
});

// POST /api/company/:companyId/schedule/slots — 添加日程
router.post('/:companyId/schedule/slots', (req, res) => {
  try {
    const slot = scheduleService.addSlot(req.params.companyId, req.body);
    res.json(slot);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// PUT /api/company/:companyId/schedule/slots/:slotId — 更新日程
router.put('/:companyId/schedule/slots/:slotId', (req, res) => {
  const slot = scheduleService.updateSlot(req.params.companyId, req.params.slotId, req.body);
  if (!slot) return res.status(404).json({ error: '日程不存在' });
  res.json(slot);
});

// DELETE /api/company/:companyId/schedule/slots/:slotId — 删除日程
router.delete('/:companyId/schedule/slots/:slotId', (req, res) => {
  scheduleService.removeSlot(req.params.companyId, req.params.slotId);
  res.json({ success: true });
});

// ═══════════════════════════════════════
//  DataSource (运营数据接入)
// ═══════════════════════════════════════

const { DataSourceService } = require('../services/datasource-service');
const dataSourceService = new DataSourceService();

// GET /api/company/:companyId/data/metrics — 获取运营指标
router.get('/:companyId/data/metrics', async (req, res) => {
  try {
    const { source = 'mock', startDate, endDate } = req.query;
    const sd = startDate || new Date(Date.now() - 7 * 86400000).toISOString().slice(0, 10);
    const ed = endDate || new Date().toISOString().slice(0, 10);
    const data = await dataSourceService.fetchMetrics(source, { startDate: sd, endDate: ed });
    res.json(data);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/:companyId/data/trending — 获取热点趋势
router.get('/:companyId/data/trending', async (req, res) => {
  try {
    const { source = 'mock', platform = 'weibo', count = '10' } = req.query;
    const data = await dataSourceService.fetchTrending(source, { platform, count: parseInt(count, 10) });
    res.json(data);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// GET /api/company/:companyId/data/attribution — 归因分析
router.get('/:companyId/data/attribution', async (req, res) => {
  try {
    const { source = 'mock' } = req.query;
    const now = new Date();
    const currentEnd = now.toISOString().slice(0, 10);
    const currentStart = new Date(now.getTime() - 7 * 86400000).toISOString().slice(0, 10);
    const previousEnd = new Date(now.getTime() - 7 * 86400000).toISOString().slice(0, 10);
    const previousStart = new Date(now.getTime() - 14 * 86400000).toISOString().slice(0, 10);

    const analysis = await dataSourceService.analyzeAttribution(
      source,
      { startDate: currentStart, endDate: currentEnd },
      { startDate: previousStart, endDate: previousEnd }
    );
    res.json(analysis);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

module.exports = router;