/** * Company Routes — 公司管理 API * * 挂载: /api/company */ const express = require('express'); const path = require('path'); const fs = require('fs'); const router = express.Router(); const { CompanyService, listCompanyAgents, buildAgentDefinitionBrief } = require('../services/company-service'); const { ScheduleService } = require('../services/schedule-service'); const orgGraphService = require('../services/org-graph-service'); // 28 批次 4:公司不再持有 agent 实体 —— 名册查 company_agents,目录一律经 agent-locator 推导 const locator = require('../services/agent-locator'); const companyService = new CompanyService(); const scheduleService = new ScheduleService(); /** * 数据根 / 公司根 —— 本文件里这两个路径此前在 9 个 handler 里各拼一份 * (6 份 `../../data/companies` + 3 份同义异名的 `../../data`),全是模块内的复制品。 * * 收敛的理由和 28 号把 13 处 `system/agents` 收进 `locator.AGENTS_ROOT` 是同一条: * **同一个事实只能有一处持有者 —— 路径也是事实**。副本的危害不是不好看,是下一次搬目录时 * 改 8 处漏 1 处,而本仓库读这类路径几乎都包在 `fs.existsSync()` 守卫里 —— 目录没了不报错, * 只是静默跳过。(这也是「按名字 grep 找不到同义异名副本」的现场:只搜 `DATA_DIR` 这个名字 * 会把它当成一个常量,其实它在本文件里指着两个不同的目录。) */ const REPO_ROOT = path.resolve(__dirname, '../..'); const DATA_ROOT = path.join(REPO_ROOT, 'data'); const COMPANIES_DIR = path.join(DATA_ROOT, 'companies'); /** * 把调用方给的相对路径解析到 baseDir 之内;越界返回 null。 * * **不能写成 `abs.startsWith(base)`** —— 那是本文件里六处文件读写检查原先的写法, * 它在「一个目录名是另一个的前缀」时会放行: * base = .../data/companies/foo * path = ../foo-evil/company.json → abs = .../data/companies/foo-evil/company.json * abs.startsWith(base) === true → 公司 foo 读到了公司 foo-evil 的文件 * PUT 那几处更糟:同样的缝隙上是跨公司**写**。 * * path.relative 才是真的在问「abs 在不在 base 里面」:越界时结果以 `..` 开头, * 指向别的盘/绝对路径时结果是绝对路径。绝对路径入参也被这一条挡住 * (path.resolve(base, '/etc/passwd') === '/etc/passwd' → relative 以 .. 开头)。 */ function resolveInside(baseDir, rel) { const base = path.resolve(baseDir); const abs = path.resolve(base, rel || ''); const r = path.relative(base, abs); if (r === '') return abs; // 指向 base 自身 if (r.startsWith('..') || path.isAbsolute(r)) return null; return abs; } /** * fire-and-forget 触发 orggraph-planning 规划这家公司的 workflow(27-P2 §4.4)。 * 不 await —— 一轮真实 Claude CLI 对话是分钟级的,调用方必须立即返回。 * 写法与本文件 /hire 里触发 agent-creator / innovator 的自调用保持一致。 */ function triggerOrgGraphPlanning(company, tag = 'OrgGraph') { const config = require('../config'); const PORT = config.port || 3000; const { id, name, goal, description } = company || {}; // ⚠️ 必须用 `${companyId}:orggraph-planning` 这个公司限定地址。 // 本体虽然只有一份,但公司态(company-context.md / 记忆 / 会话)是按公司分的, // 裸名 /api/agent/orggraph-planning/chat 会落到 `_global` 那份上,规划时看不到公司语境。 const namespacedId = `${id}:orggraph-planning`; fetch(`http://127.0.0.1:${PORT}/api/agent/${encodeURIComponent(namespacedId)}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: `公司 ${id}(${name})已创建。\n公司目标(company-goal):${goal || '(未填写)'}\n公司描述:${description || '(未填写)'}\n请按 orggraph-planning 工作流规划并建立这家公司的 workflow:读 system/org-graph-templates/ 候选骨架 + 可招角色清单,产出执行流图后调用 POST /api/company/${id}/org-graph 落库,再按拓扑序完成招聘。`, conversationId: `orggraph-bootstrap-${id}-${Date.now().toString(36)}`, }), }) // fetch 不会因为 4xx/5xx 而 reject,只在网络层出错时 reject。 // 不显式检查 res.ok 的话,地址写错这类问题会被完全静默吞掉(实测踩过)。 .then(res => { if (!res.ok) { console.error(`[${tag}] orggraph-planning 触发失败: HTTP ${res.status} @ ${namespacedId}`); } else { console.log(`[${tag}] ✅ 已触发 ${namespacedId} 规划 org graph`); } }) .catch(e => console.error(`[${tag}] orggraph-planning 触发失败(网络):`, e.message)); } // ═══════════════════════════════════════ // Company CRUD // ═══════════════════════════════════════ // POST /api/company/create router.post('/create', async (req, res) => { try { const { id, name, goal, description } = 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, goal, description }); // ── P2 T6:自动招聘 orggraph-planning 并异步触发组织结构规划 ── // 降级约定(27-P2 §4.4):这一步任何失败都不能影响公司创建本身, // 最差退化成一家没有 workflow 的空壳公司(等同 P2 上线前的现状)。 try { const bootstrap = companyService.hire(id, 'orggraph-planning', {}); // 只有拿到真模板(或目录已在)才值得起一轮对话:模板缺失时 hire 会退化成 base 空骨架, // 那个骨架里没有 §4.1 的八步工作流,触发了也规划不出东西。 if (bootstrap.status === 'hired_from_template' || bootstrap.status === 'already_exists') { triggerOrgGraphPlanning(company, 'Create'); } else { console.warn(`[Create] orggraph-planning 招聘未走模板分支 (status=${bootstrap.status}),跳过自动规划;模板就绪后可调 POST /api/company/${id}/org-graph/replan 补跑`); } } catch (e) { console.error('[Create] orggraph-planning 自动招聘失败(不影响公司创建):', e.message); } res.json({ success: true, company, message: '公司已创建,正在由 orggraph-planning 自动规划组织结构(异步进行中)。' }); } 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()); }); // PATCH /api/company/templates/:templateId — 修改模板元信息 (名称, 类型, 描述) router.patch('/templates/:templateId', (req, res) => { try { const { templateId } = req.params; const { name, type, description } = req.body; if (name !== undefined && !name.trim()) return res.status(400).json({ error: 'name 为必填项' }); const path = require('path'); const fs = require('fs'); const TEMPLATES_DIR = locator.AGENTS_ROOT; const templateDir = path.join(TEMPLATES_DIR, templateId); if (!fs.existsSync(templateDir)) { return res.status(404).json({ error: `模板 "${templateId}" 不存在` }); } // 1. 更新 config.json 中的字段 const configPath = path.join(templateDir, 'config.json'); if (fs.existsSync(configPath)) { const config = JSON.parse(fs.readFileSync(configPath, 'utf-8')); if (name !== undefined) config.name = name.trim(); if (type !== undefined) config.type = type.trim(); if (description !== undefined) config.description = description.trim(); fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8'); } // 2. 更新 _registry.json 中的字段 const registryPath = path.join(TEMPLATES_DIR, '_registry.json'); if (fs.existsSync(registryPath)) { try { const registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8')); const entry = registry.find(t => t.id === templateId); if (entry) { if (name !== undefined) entry.name = name.trim(); if (type !== undefined) entry.type = type.trim(); if (description !== undefined) entry.description = description.trim(); fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2) + '\n', 'utf-8'); } } catch {} } console.log(`[Template] ✏️ 模板 ${templateId} 元信息已更新`); res.json({ success: true, id: templateId, name: name?.trim(), type: type?.trim(), description: description?.trim() }); } catch (err) { res.status(500).json({ error: err.message }); } }); // DELETE /api/company/templates/:templateId — 删除模板 router.delete('/templates/:templateId', (req, res) => { try { const { templateId } = req.params; const path = require('path'); const fs = require('fs'); const TEMPLATES_DIR = locator.AGENTS_ROOT; const templateDir = path.join(TEMPLATES_DIR, templateId); if (!fs.existsSync(templateDir)) { return res.status(404).json({ error: `模板 "${templateId}" 不存在` }); } // 1. 删除模版文件夹 fs.rmSync(templateDir, { recursive: true, force: true }); // 2. 更新 registry const registryPath = path.join(TEMPLATES_DIR, '_registry.json'); if (fs.existsSync(registryPath)) { try { let registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8')); registry = registry.filter(t => t.id !== templateId); fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2) + '\n', 'utf-8'); } catch {} } console.log(`[Template] 🗑️ 模板 ${templateId} 已被删除`); res.json({ success: true, message: `模板 ${templateId} 已删除` }); } catch (err) { res.status(500).json({ error: err.message }); } }); // POST /api/company/templates — 创建新模板 Agent router.post('/templates', async (req, res) => { try { const { id, name, type, description } = req.body; if (!id || !name) return res.status(400).json({ error: 'id 和 name 为必填项' }); if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) { return res.status(400).json({ error: 'id 格式无效 (只允许小写字母、数字、-)' }); } const path = require('path'); const fs = require('fs'); // 28 批次 5-21:baseDir 只认 agent-locator 这一份定义(原来这里指向已不存在的 system/templates/) const TEMPLATES_DIR = locator.AGENTS_ROOT; const templateDir = path.join(TEMPLATES_DIR, id); if (fs.existsSync(templateDir)) { return res.status(409).json({ error: `模板 "${id}" 已存在` }); } // 使用 AgentScaffold 创建标准骨架 const { AgentScaffold } = await import('../../packages/agent-core/AgentScaffold.js'); const scaffold = new AgentScaffold(TEMPLATES_DIR); await scaffold.create({ id, type: type || 'skill', name: name, parentId: null, }); // 如果有 description,追加到 config.json if (description) { const configPath = path.join(templateDir, 'config.json'); const config = JSON.parse(fs.readFileSync(configPath, 'utf-8')); config.description = description; fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8'); } console.log(`[Template] ✅ 新模板已创建: ${id} (${type || 'skill'})`); res.status(201).json({ success: true, id, name, type: type || 'skill' }); } catch (err) { res.status(500).json({ error: err.message }); } }); // POST /api/company/templates/:templateId/generate — 调用 Agent Creator 生成定义文件 router.post('/templates/:templateId/generate', async (req, res) => { try { const { templateId } = req.params; const { description } = req.body; const path = require('path'); const fs = require('fs'); const config = require('../config'); const TEMPLATES_DIR = locator.AGENTS_ROOT; const templateDir = path.join(TEMPLATES_DIR, templateId); if (!fs.existsSync(templateDir)) { return res.status(404).json({ error: `模板 "${templateId}" 不存在` }); } const PORT = config.port || 3000; // 与 /hire 那处同一份产出契约(28 批次 5-23)—— 文本单点定义在 company-service, // 两处各抄一份的时候,运行期布局那半段只补进一处就等于没补。 const prompt = buildAgentDefinitionBrief({ agentId: templateId, bodyPath: templateDir, description }); // 异步调用 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: prompt, conversationId: `tpl-gen-${templateId}-${Date.now().toString(36)}`, }), }).catch(e => console.error('[Template] Agent Creator 请求失败:', e.message)); console.log(`[Template] 🤖 已触发 Agent Creator 为 ${templateId} 生成定义`); res.json({ success: true, message: `已触发 Agent Creator 为 "${templateId}" 生成定义文件`, status: 'generating' }); } catch (err) { res.status(500).json({ error: err.message }); } }); // POST /api/company/templates/:templateId/train — 调用 Innovator 训练模板 router.post('/templates/:templateId/train', async (req, res) => { try { const { templateId } = req.params; const { instructions } = req.body; const path = require('path'); const fs = require('fs'); const config = require('../config'); const TEMPLATES_DIR = locator.AGENTS_ROOT; const templateDir = path.join(TEMPLATES_DIR, templateId); if (!fs.existsSync(templateDir)) { return res.status(404).json({ error: `模板 "${templateId}" 不存在` }); } const PORT = config.port || 3000; let prompt = `请你对模板 Agent "${templateId}" 进行评估和训练。 模板位于 \`../../system/agents/${templateId}\` 目录。 请使用 FDE pipeline 对该模板的技能进行评测和进化训练,目标: Benchmark Score ≥ 95。 训练过程包括 Hunt(验证数据), Digest(知识消化), Evolver(技能进化) 等。`; if (instructions) { prompt += `\n**【额外训练要求/指令】**\n${instructions}\n`; } prompt += `\n请立即开始评估和训练,训练完成后请汇报最终分数。`; // 异步调用 innovator fetch(`http://127.0.0.1:${PORT}/api/agent/innovator/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: prompt, conversationId: `tpl-train-${templateId}-${Date.now().toString(36)}`, }), }).catch(e => console.error('[Template] Innovator 请求失败:', e.message)); console.log(`[Template] 🎓 已触发 Innovator 训练 ${templateId}`); res.json({ success: true, message: `已触发 Innovator 训练 "${templateId}"`, status: 'training' }); } catch (err) { res.status(500).json({ error: err.message }); } }); // POST /api/company/templates/:templateId/skills/upload — 上传 Skill 文件/ZIP 包 const multer = require('multer'); const AdmZip = require('adm-zip'); const skillUploadStorage = multer.diskStorage({ destination: (req, file, cb) => { const os = require('os'); const tmpDir = path.join(os.tmpdir(), `skill-upload-${Date.now()}`); fs.mkdirSync(tmpDir, { recursive: true }); cb(null, tmpDir); }, filename: (req, file, cb) => { // Sanitize filename const safe = file.originalname.replace(/[^a-zA-Z0-9._-]/g, '_'); cb(null, safe); }, }); const skillUpload = multer({ storage: skillUploadStorage, limits: { fileSize: 50 * 1024 * 1024, files: 50 }, // 50MB per file, 50 files max }); router.post('/templates/:templateId/skills/upload', skillUpload.array('files', 50), async (req, res) => { try { const { templateId } = req.params; const targetSubdir = req.body.targetDir || '.claude/skills'; // default to .claude/skills/ (Claude Code ACP reads from here) const TEMPLATES_DIR = locator.AGENTS_ROOT; const templateDir = path.join(TEMPLATES_DIR, templateId); if (!fs.existsSync(templateDir)) { return res.status(404).json({ error: `模板 "${templateId}" 不存在` }); } const destDir = path.join(templateDir, targetSubdir); fs.mkdirSync(destDir, { recursive: true }); const uploadedFiles = req.files || []; if (uploadedFiles.length === 0) { return res.status(400).json({ error: '没有上传任何文件' }); } let extractedCount = 0; let copiedCount = 0; const details = []; for (const file of uploadedFiles) { const ext = path.extname(file.originalname).toLowerCase(); if (ext === '.zip') { // ── ZIP 解压 ── try { const zip = new AdmZip(file.path); const entries = zip.getEntries(); // 检测是否整个 ZIP 包在一个顶级目录下(常见的 GitHub 下载格式) const topDirs = new Set(); for (const entry of entries) { const firstSegment = entry.entryName.split('/')[0]; topDirs.add(firstSegment); } const hasWrapper = topDirs.size === 1 && entries.some(e => e.isDirectory && e.entryName === [...topDirs][0] + '/'); const stripPrefix = hasWrapper ? [...topDirs][0] + '/' : ''; for (const entry of entries) { if (entry.isDirectory) continue; // 安全:跳过 __MACOSX、.DS_Store 等系统文件 if (entry.entryName.includes('__MACOSX') || entry.entryName.endsWith('.DS_Store')) continue; let relativePath = entry.entryName; if (stripPrefix && relativePath.startsWith(stripPrefix)) { relativePath = relativePath.substring(stripPrefix.length); } if (!relativePath) continue; const outputPath = path.join(destDir, relativePath); // 防止路径穿越 if (!outputPath.startsWith(destDir)) continue; fs.mkdirSync(path.dirname(outputPath), { recursive: true }); fs.writeFileSync(outputPath, entry.getData()); extractedCount++; details.push({ action: 'extracted', file: `${targetSubdir}/${relativePath}` }); } } catch (zipErr) { details.push({ action: 'error', file: file.originalname, error: `ZIP 解压失败: ${zipErr.message}` }); } } else { // ── 普通文件直接复制 ── // 如果上传了带有 webkitRelativePath 的文件夹结构,保留相对路径 const relativePath = file.originalname; const outputPath = path.join(destDir, relativePath); // 防止路径穿越 if (!outputPath.startsWith(destDir)) continue; fs.mkdirSync(path.dirname(outputPath), { recursive: true }); fs.copyFileSync(file.path, outputPath); copiedCount++; details.push({ action: 'copied', file: `${targetSubdir}/${relativePath}` }); } // 清理临时文件 try { fs.unlinkSync(file.path); } catch {} } // 清理临时上传目录 for (const file of uploadedFiles) { try { fs.rmdirSync(path.dirname(file.path)); } catch {} } console.log(`[Template] 📥 ${templateId}: Skill 导入完成 - ${extractedCount} extracted, ${copiedCount} copied`); res.json({ success: true, templateId, targetDir: targetSubdir, stats: { extractedFromZip: extractedCount, copiedFiles: copiedCount, totalFiles: extractedCount + copiedCount }, details, }); } catch (err) { console.error('[Template] Skill upload error:', err); res.status(500).json({ error: err.message }); } }); /** * POST /api/company/templates/:templateId/provision * 系统级依赖安装 — 绕过 ACP,直接 shell 执行 * * Body: { commands: ["pip install rembg", "npm install ..."], agentDir?: string } * - commands: 要执行的 shell 命令数组 * - agentDir: 可选,指定公司 agent 目录(不传则在 template 目录执行) * * 特点: * 1. 不走 Claude CLI / ACP,不受 45s idle timeout 限制 * 2. 用 child_process.exec 同步执行,每个命令独立超时 10 分钟 * 3. 返回每个命令的 stdout/stderr 供前端展示 */ router.post('/templates/:templateId/provision', async (req, res) => { try { const { templateId } = req.params; const { commands, agentDir } = req.body; const { exec } = require('child_process'); const { promisify } = require('util'); const execAsync = promisify(exec); if (!commands || !Array.isArray(commands) || commands.length === 0) { return res.status(400).json({ error: '请提供 commands 数组' }); } // 确定工作目录 // 原来写的是 `../../data/system/templates` —— 一个从来不存在的路径(`data/` 多余), // 所以不带 agentDir 的调用一直是 404。顺手改正到合并后的本体目录。 const TEMPLATES_DIR = locator.AGENTS_ROOT; let workDir; if (agentDir) { // 公司 agent 目录 workDir = path.resolve(__dirname, '../../', agentDir); } else { workDir = path.join(TEMPLATES_DIR, templateId); } if (!fs.existsSync(workDir)) { return res.status(404).json({ error: `目录不存在: ${workDir}` }); } // 安全检查:禁止危险命令 const BLOCKED_PATTERNS = [/rm\s+-rf\s+\//, /mkfs/, /dd\s+if=/, />\s*\/dev\//]; for (const cmd of commands) { if (BLOCKED_PATTERNS.some(p => p.test(cmd))) { return res.status(400).json({ error: `命令被安全策略拒绝: ${cmd}` }); } } console.log(`[Provision] 🔧 ${templateId}: 开始执行 ${commands.length} 个系统命令`); const results = []; for (const cmd of commands) { console.log(`[Provision] ▶ ${cmd}`); try { const { stdout, stderr } = await execAsync(cmd, { cwd: workDir, timeout: 10 * 60 * 1000, // 每个命令最多 10 分钟 maxBuffer: 10 * 1024 * 1024, // 10MB output buffer env: { ...process.env, PIP_PROGRESS_BAR: 'off' }, }); results.push({ command: cmd, status: 'success', stdout: stdout.slice(-2000), stderr: stderr.slice(-1000) }); console.log(`[Provision] ✅ ${cmd} 完成`); } catch (err) { results.push({ command: cmd, status: 'error', error: err.message, stdout: err.stdout?.slice(-2000), stderr: err.stderr?.slice(-1000) }); console.error(`[Provision] ❌ ${cmd} 失败:`, err.message); } } const allOk = results.every(r => r.status === 'success'); res.json({ success: allOk, templateId, workDir, results, }); } catch (err) { console.error('[Provision] Error:', err); res.status(500).json({ error: err.message }); } }); // GET /api/company/templates/:templateId/logs — 获取模板相关的 agent-creator / innovator 执行日志 router.get('/templates/:templateId/logs', (req, res) => { try { const path = require('path'); const fs = require('fs'); const templateId = req.params.templateId; const locator = require('../services/agent-locator'); const logs = []; // 扫描 agent-creator 和 innovator 的对话,匹配 tpl-gen-{id} 和 tpl-train-{id} const scanAgents = [ { agentId: 'agent-creator', prefix: `tpl-gen-${templateId}`, type: 'generate', label: '🤖 Agent Creator' }, { agentId: 'org-innovator', prefix: `tpl-train-${templateId}`, type: 'train', label: '🎓 Innovator' }, ]; for (const scan of scanAgents) { // 全局 agent 的会话落在保留公司 id `_global` 下(28 §5.1) const convDir = path.join(locator.companyDir(scan.agentId), 'conversations'); if (!fs.existsSync(convDir)) continue; const dirs = fs.readdirSync(convDir, { withFileTypes: true }) .filter(d => d.isDirectory() && d.name.startsWith(scan.prefix)); for (const d of dirs) { const metaPath = path.join(convDir, d.name, 'meta.json'); const histPath = path.join(convDir, d.name, 'history.json'); let meta = {}, history = []; try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); } catch {} try { history = JSON.parse(fs.readFileSync(histPath, 'utf-8')); } catch {} // 提取最后一条 assistant 消息作为摘要 const lastAssistant = [...history].reverse().find(m => m.role === 'assistant'); logs.push({ conversationId: d.name, agentId: scan.agentId, type: scan.type, label: scan.label, createdAt: meta.createdAt || null, messageCount: history.length, summary: lastAssistant ? (lastAssistant.content || '').slice(0, 500) : '(执行中...)', status: lastAssistant ? 'done' : 'running', }); } } // 按时间倒序 logs.sort((a, b) => new Date(b.createdAt || 0).getTime() - new Date(a.createdAt || 0).getTime()); res.json(logs); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/templates/:templateId/files router.get('/templates/:templateId/files', (req, res) => { try { const path = require('path'); const fs = require('fs'); const DATA_DIR = locator.AGENTS_ROOT; const templateDir = path.join(DATA_DIR, req.params.templateId); if (!fs.existsSync(templateDir)) { return res.json({ tree: [], totalFiles: 0 }); } function scanDir(dirPath, relativePath = '') { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); const nodes = []; for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name; if ((entry.name.startsWith('.') && entry.name !== '.claude') || entry.name === 'node_modules') continue; if (entry.isDirectory()) { const children = scanDir(fullPath, relPath); nodes.push({ name: entry.name, path: relPath, type: 'directory', children, fileCount: children.reduce((sum, c) => sum + (c.type === 'file' ? 1 : (c.fileCount || 0)), 0), }); } else { const stat = fs.statSync(fullPath); nodes.push({ name: entry.name, path: relPath, type: 'file', size: stat.size, modifiedAt: stat.mtime.toISOString(), }); } } return nodes.sort((a, b) => { if (a.type !== b.type) return a.type === 'directory' ? -1 : 1; return a.name.localeCompare(b.name); }); } const tree = scanDir(templateDir); const countFiles = (nodes) => nodes.reduce((sum, n) => sum + (n.type === 'file' ? 1 : countFiles(n.children || [])), 0); res.json({ tree, totalFiles: countFiles(tree) }); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/templates/:templateId/files/content router.get('/templates/:templateId/files/content', (req, res) => { try { const path = require('path'); const fs = require('fs'); const DATA_DIR = locator.AGENTS_ROOT; const filePath = req.query.path; if (!filePath) return res.status(400).json({ error: 'path 参数为必填' }); const absPath = resolveInside(path.join(DATA_DIR, req.params.templateId), filePath); if (!absPath) { return res.status(403).json({ error: '路径越界' }); } if (!fs.existsSync(absPath)) { return res.status(404).json({ error: '文件不存在' }); } const stat = fs.statSync(absPath); if (stat.size > 512 * 1024) { return res.json({ content: '(文件过大,跳过预览)', truncated: true, size: stat.size }); } const content = fs.readFileSync(absPath, 'utf-8'); res.json({ content, size: stat.size, path: filePath }); } catch (err) { res.status(500).json({ error: err.message }); } }); // PUT /api/company/templates/:templateId/files/content — 保存模板文件内容 router.put('/templates/:templateId/files/content', (req, res) => { try { const path = require('path'); const fs = require('fs'); const DATA_DIR = locator.AGENTS_ROOT; const filePath = req.body.path; if (!filePath) return res.status(400).json({ error: 'path 参数为必填' }); const absPath = resolveInside(path.join(DATA_DIR, req.params.templateId), filePath); if (!absPath) { return res.status(403).json({ error: '路径越界' }); } // 确保目录存在 const dir = path.dirname(absPath); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(absPath, req.body.content || '', 'utf-8'); console.log(`[Template] 💾 已保存模板文件 ${req.params.templateId}/${filePath}`); res.json({ success: true, path: filePath }); } catch (err) { res.status(500).json({ error: err.message }); } }); // 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 }); }); // DELETE /api/company/:companyId router.delete('/:companyId', (req, res) => { const company = companyService.delete(req.params.companyId); 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 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, 公司)` 读:公司态优先,没设置过才回落本体的缺省。 // 走 heartbeatService 的同一个函数 —— 控制台显示的和定时器真正用的必须是同一个答案。 let heartbeatConfig = { enabled: false, intervalMinutes: 15 }; try { heartbeatConfig = heartbeatService.readHeartbeatConfig(namespacedId); } 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 心跳控制 // ═══════════════════════════════════════ /** * 这家公司雇过这个角色没有(28 批次 4:判据从「公司私有目录在不在」改成「company_agents 有没有行」, * 那个目录整体删掉了,继续判目录的话下面三个心跳端点会无条件 404)。 * * 原来这里返回的是**本体** config.json 的路径,三个端点拿着它读改写 —— 心跳因此是本体级的: * A 公司调成 30 分钟,雇了同一个本体的 B 公司跟着变;更糟的是「读的时候补默认值再整份回写」, * 没人点过开关也能把 `system/agents/{aid}/config.json` 写脏(28 号 E2E 实测)。 * 现在心跳状态落公司态目录,落点与读写口径都收在 heartbeat-service 里,这里只剩「雇没雇」这一问。 */ function isHired(companyId, roleName) { return listCompanyAgents(companyId).some((r) => r.role_name === roleName); } // PUT /api/company/:companyId/agents/:agentId/heartbeat — 更新 Agent 心跳配置 router.put('/:companyId/agents/:agentId/heartbeat', (req, res) => { try { const { intervalMinutes, enabled } = req.body; // 非正数 / NaN 会让 setInterval 退化成每 tick 触发一次 —— 拦在入口,别让它落盘(`> 0` 对 NaN 为 false) if (intervalMinutes !== undefined && !(Number(intervalMinutes) > 0)) { return res.status(400).json({ error: 'intervalMinutes 必须是正数' }); } if (!isHired(req.params.companyId, req.params.agentId)) { return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` }); } const heartbeatService = require('../services/heartbeat-service'); const namespacedId = `${req.params.companyId}:${req.params.agentId}`; // 只写公司态(`system/agents/{aid}/{cid}/heartbeat.json`),本体一个字节都不动 const heartbeat = heartbeatService.writeHeartbeatConfig(namespacedId, { intervalMinutes, enabled }); // 如果正在运行,重新挂载心跳 if (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=${heartbeat.intervalMinutes}min, enabled=${heartbeat.enabled}`); res.json({ success: true, 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 { if (!isHired(req.params.companyId, req.params.agentId)) { return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` }); } const heartbeatService = require('../services/heartbeat-service'); const namespacedId = `${req.params.companyId}:${req.params.agentId}`; heartbeatService.writeHeartbeatConfig(namespacedId, { enabled: true }); // 激活心跳 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 { if (!isHired(req.params.companyId, req.params.agentId)) { return res.status(404).json({ error: `Agent ${req.params.agentId} 不存在` }); } const heartbeatService = require('../services/heartbeat-service'); const namespacedId = `${req.params.companyId}:${req.params.agentId}`; heartbeatService.writeHeartbeatConfig(namespacedId, { enabled: false }); // 停止心跳 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'); // Skill 挂在本体的 `.claude/skills/`(agent-manager 的 scoped skill 遍历找的就是这里), // 不是公司私有目录下那个从来没被 CLI 发现过的 `skills/`。 const hired = listCompanyAgents(req.params.companyId).find((r) => r.role_name === req.params.agentId); if (!hired) return res.json([]); const skillsDir = path.join(locator.bodyDir(hired.system_agent_id), '.claude', '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}`; // result.agentDir 是**公司态**目录;定义文件与 skill 都写本体(28 批次 4: // 公司不再持有 agent 实体,往公司侧写等于刚清完又造一个新的死角)。 const bodyPath = locator.bodyDir(role); const PORT = config.port || 3000; // 1. 发起 Agent-Creator 编写骨架定义 (异步不等待) // ⚠️ 给的是**绝对路径**:agent-creator 的 cwd 现在是它自己的任务态目录 // (system/agents/agent-creator/_global/{taskId}/),原来那个 `../{公司}/agents/{角色}` // 相对路径从那里数出去指向的是一个不存在的位置 —— 它会照着写,且不报错。 fetch(`http://127.0.0.1:${PORT}/api/agent/agent-creator/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ // 产出契约(28 批次 5-23)逐字点名三个必填文件:本体填不满就停在 // status='draft'、别家公司雇不走。以前只写「补充完整的定义文件(…等)」, // 「等」里那份 SKILL.md 谁也没保证过 —— org-coder 就是这么变成空定义的。 // 契约文本(含运行期布局那半段)单点定义在 company-service,见其注释。 message: buildAgentDefinitionBrief({ agentId: role, bodyPath, description: description || name || role, intro: `新员工 ${namespacedId} 已由脚手架创建空白目录在 \`${bodyPath}\`。请你按照标准模板,使用 Write 工具为该员工补充定义文件。写完后请答复。`, }), conversationId: `create-${req.params.companyId}-${role}-${Date.now().toString(36)}` }) }).catch(e => console.error('[Hire] Agent-Creator 请求错误:', e.message)); // 2. 去网上/Arena搜索并注入 3 个基础 Skill。 // 落 `.claude/skills/` 而不是 `skills/`:只有前者会被 CLI(和 agent-manager // 的 scoped skill 遍历)发现,后者是一个从来没人读过的目录。 const skills = skillDb.searchSkills(role, { limit: 3 }); const skillsDir = path.join(bodyPath, '.claude', '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 { // archive 参数保留在协议里(前端还在传),但已无实际作用 —— 见下方注释 const { role } = req.body; if (!role) return res.status(400).json({ error: 'role 为必填项' }); const companyId = req.params.companyId; const namespacedId = `${companyId}:${role}`; // 1. 解雇 = 把 company_agents 那一行标成 removed,同时把 company.json.agents[] 同步掉 // (companyService.fire() 两件事都做)。**不动本体、也不动公司态目录**: // 本体是全系统共享的,删了别家公司的 agent 就没了;公司态目录里是记忆, // 28 §5.6 明确「fire 只软删,记忆不随解雇删除」。 // archive 参数因此退化成无意义 —— 没有目录可搬了,原地保留就是归档。 const fired = companyService.fire(companyId, role); if (!fired) { return res.status(404).json({ error: `Agent ${role} 不存在于公司 ${companyId}` }); } // 2. 停止心跳 const heartbeatService = require('../services/heartbeat-service'); if (heartbeatService.timers.has(namespacedId)) { clearInterval(heartbeatService.timers.get(namespacedId)); heartbeatService.timers.delete(namespacedId); } // 3. P2 T7:org_graph 里对应节点软删除(级联失效它的进出边) try { orgGraphService.removeNode(companyId, role); } catch (e) { console.warn('[Fire] org_graph 清理失败(不影响辞退结果):', e.message); } console.log(`[Fire] 🔴 ${namespacedId} 已辞退`); // archived 恒为 true:公司态目录(记忆 / 会话)原地保留,本来就等于归档 res.json({ success: true, message: `${namespacedId} 已辞退`, archived: true }); } catch (err) { res.status(500).json({ error: err.message }); } }); // ═══════════════════════════════════════ // Org Graph — 公司级 workflow 图(P2 / 27-P2 §4.3) // ═══════════════════════════════════════ // POST /api/company/:companyId/org-graph — 整体写入(规划产物落库) // body: { nodes: [{roleName, systemAgentId?}], edges: [{from, to, condition, edgeKind?}] }(边的 from/to 是 roleName) router.post('/:companyId/org-graph', (req, res) => { try { const { nodes, edges } = req.body || {}; const result = orgGraphService.writeGraph(req.params.companyId, { nodes, edges }); // 校验失败返回 400 + errors[{rule, detail}],供 orggraph-planning 自行修正后重试 if (!result.ok) return res.status(400).json({ error: '图不合法', errors: result.errors }); res.json({ success: true, ...result }); } catch (err) { res.status(500).json({ error: err.message }); } }); // PATCH /api/company/:companyId/org-graph — 增量修改(改完整张图仍须合法,否则整体回滚) // body: { addNodes?, removeNodes?, addEdges?, removeEdges? } router.patch('/:companyId/org-graph', (req, res) => { try { const result = orgGraphService.patchGraph(req.params.companyId, req.body || {}); if (!result.ok) return res.status(400).json({ error: '图不合法', errors: result.errors }); res.json({ success: true }); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/:companyId/org-graph — 只读;公司无图时返回空数组,不报错 // 返回 { nodes: [{id, roleName, systemAgentId, status}], edges: [{from, to, condition, edgeKind}] }(边的 from/to 是节点 id) router.get('/:companyId/org-graph', (req, res) => { try { res.json(orgGraphService.getGraph(req.params.companyId)); } catch (err) { res.status(500).json({ error: err.message }); } }); // POST /api/company/:companyId/org-graph/replan — 对已有公司手动重跑规划(存量公司补图入口) // 异步:立即返回,agent 跑完后自己调上面的 POST 写入新图 router.post('/:companyId/org-graph/replan', (req, res) => { try { const company = companyService.get(req.params.companyId); if (!company) return res.status(404).json({ error: `公司 ${req.params.companyId} 不存在` }); try { // 幂等:已经雇过就是 already_exists,不重复建目录 companyService.hire(company.id, 'orggraph-planning', {}); } catch (e) { console.warn('[Replan] orggraph-planning 招聘跳过:', e.message); } triggerOrgGraphPlanning(company, 'Replan'); res.json({ status: 'replanning', companyId: company.id }); } catch (err) { res.status(500).json({ error: err.message }); } }); // ═══════════════════════════════════════ // 任务入口 — 用户 → 公司(T12 / 27-P3P4 §五 T12、27-E2E §三 阶段 3) // ═══════════════════════════════════════ // // 为什么必须新开一个入口:既有 POST /api/agent/task/dispatch 的 from / to 都要求是 // 已存在的 agent 目录,**只支持 agent → agent**(27-E2E §三 阶段 3 的 ❌ 缺口)。 // 用户把一句自然语言任务交给「一家公司」时没有 from agent,走不通那条路。 // 收敛侧的 POST /api/agent/task/report 则已经实现了完整回调链路,本入口复用它 —— // 但只在 **goal 粒度**复用一次,见 `services/task-settle.js` 与下方缺陷 3 那段注释。 /** * v1 约束:一家公司同时只有一个 active root run(27-P3P4 §一非目标)。 * 取值域与 work-graph-db 的唯一索引 idx_graph_runs_one_active_root 严格一致—— * 这里只是提前给出可读的 409,真正的守卫是那条索引(并发下靠它兜底,见下方 catch)。 */ const ACTIVE_ROOT_RUN_STATUS = ['ready', 'running', 'paused']; /** * 「这条 run 还没撒手」的取值域 —— 归档守卫用(27-P3C 第二轮复核 缺陷 1 的连带)。 * * = 上面那个活跃集 **+ `blocked`**,而且必须由它派生、不许再抄一份字面量:§九.1 记着的教训就是 * `ACTIVE_ROOT_RUN_STATUS` 在两个文件里逐字重复,改一处漏一处。 * * 为什么 `blocked` 不直接并进 `ACTIVE_ROOT_RUN_STATUS`:那个常量是 * `idx_graph_runs_one_active_root` 这条唯一索引的镜像(索引里就没有 blocked), * 动它等于悄悄改「一家公司同时只能有一个 active root run」的口径。 * 但对归档来说 blocked 恰恰**不能**放行:run 转 blocked 会把 task 也写成 blocked, * 人加完预算 `POST /api/graph-runs/:id/start` 就接着烧钱,而 task 行仍停在 blocked —— * 只看 `task.status === 'running'` 的旧守卫会放行,用户就把一条正在跑的 run 从界面上藏掉了。 */ const RUN_HOLDING_STATUS = [...ACTIVE_ROOT_RUN_STATUS, 'blocked']; /** * 这条 task 现在能不能被归档掉?两条判据只要中一条就是「不能」: * · task 行本身处于 running / blocked(blocked = 挂起等人,随时可能被恢复); * · 它的 current_run_id 指的 run 还在 RUN_HOLDING_STATUS 里 —— 恢复后 run 已经 running、 * task 行却还留在 blocked(`RUN_TO_TASK_STATUS` 没有 running 这一档,回写只在收敛时发生), * 光看 task 行会漏掉这半截。 */ function taskHoldsRun(task) { if (task.status === 'running' || task.status === 'blocked') return true; if (!task.current_run_id) return false; const run = require('../services/work-graph-db').getRun(task.current_run_id); return !!run && RUN_HOLDING_STATUS.includes(run.run_status); } /** 任务级总预算默认值(27-P3P4 §四.A.3:中等任务粗估 60-100 次调用、1-2 小时) */ const DEFAULT_TASK_BUDGET = { total_agent_calls: 100, total_tokens: 5000000, wallclock_ms: 7200000, spent: { agent_calls: 0, tokens: 0 }, }; /** * run 目录 —— **`graph-engine.runRootDir` 的镜像**(27-P3C §六 缺陷 A)。 * * 为什么这里非有一份不可:`task-goal.json` 的写侧在本文件、读侧在 `graph-engine.describeTask` * 与 `goal-contract.deriveRunDir`,而读侧走 `runRootDir`(认 `GRAPH_RUNS_DIR`)、写侧原先 * 自己拼 `data/companies/…`(不认)。env 一设上两边就分叉,`describeTask` 拿到 null 后 * **静默退回兜底文案「执行图节点任务」** —— agent 从此收不到真实任务描述,而没有任何报错。 * * ponytail: 这是逐字同构的第二份实现,上限就是「改一处漏一处」这个老病。 * 不直接调 `graph-engine.runRootDir` 是因为它没导出、且入参是 run 行对象, * 而这里只有 companyId + rootRunId。收敛路径:在 `company-paths.js` 里加一个 * `runRootDirById(companyId, rootRunId)`,让 engine 的 `runRootDir` 与本函数同时改调它。 * * `GRAPH_RUNS_DIR` **每次调用时读**,照 `company-paths.js` 文件头那条教训: * 模块加载时快照会让「先 require 再设 env」的调用方算出另一个根。 */ function runRootDirById(companyId, rootRunId) { const runsRoot = process.env.GRAPH_RUNS_DIR || null; return runsRoot ? path.join(runsRoot, String(rootRunId)) : path.join(COMPANIES_DIR, String(companyId), 'runs', String(rootRunId)); } /** * 任务描述落盘到 root run 的 artifacts/(§四.A.5 的任务级共享产物区,跨 org node 只读)。 * graph_runs 上没有描述列,而 advanceOne 的任务描述是调用时透传的 opts.task; * 手动模式下每次 /next 由控制台发起,需要能把原始 task-goal 读回来。 */ function writeTaskGoalArtifact(companyId, rootRunId, payload) { const dir = path.join(runRootDirById(companyId, rootRunId), 'artifacts'); fs.mkdirSync(dir, { recursive: true }); const fp = path.join(dir, 'task-goal.json'); fs.writeFileSync(fp, JSON.stringify(payload, null, 2), 'utf-8'); return fp; } /** * ── run 级汇报为什么被摘掉了(27-P3C 第二轮复核 缺陷 3)── * * 这里原先住着 `terminalOrgAgent` + `reportRunOutcome`:auto driver 跑完后往 * `POST /api/agent/task/report` 打一条 run 粒度的汇报。它和 `task-settle.reportGoalOutcome` * 的 goal 粒度汇报会**同时**命中那个端点,而该端点第 5 步会 `setImmediate` 自调 * `/api/agent/{to}/chat` 唤醒上级 agent —— 批 1 的唯一形态是 1 goal : 1 task * (`POST /:cid/tasks` 自动建 goal,`createTask` 继承 `goal.report_to`),于是同一件事 * 把同一个上级叫醒两次、白烧一轮 LLM,其中一次带的还是它从没见过的 `G-` id。 * * 留下的是 goal 级那一条,理由不是「随便留一条」: * · run 级只挂得上 auto 模式的 driver,manual / stop / blocked 全不触发,本来就是半条链路; * · goal 级挂在唯一漏斗 `graph-run-sse.transitionRun` 的收敛钩子上,四种收敛路径全覆盖; * · 汇报的语义本来就是「人提的这个需求算不算做到了」,那是 goal 的粒度,不是 run 的。 * * 交付者身份(汇报的 `from`)随函数一起搬到了 `org-graph-service.terminalAgentId`, * 读侧改成 task-settle —— 判据只留一份,别在两个文件里各存一个末节点算法。 */ // ═══════════════════════════════════════ // 目标 / 任务两级模型(27-P3C §六) // ═══════════════════════════════════════ // // goal(人提的一个需求,description 就是验收边界)→ task(一件能独立跑的活)→ run(一次执行)。 // 这不是新概念,是给 graph_runs.goal_id / task_id 这对**从 P3 起就一直在写、却没有任何表接得住** // 的悬空外键补上它们的表:此前「一个需求拆成几件活」在库里根本不存在,界面上也就画不出来。 // // 本批(批 1)只落地同步的那一半:建行 / 改行 / 归档 / 下达即起 run。 // **排队不在本批**(run_status='queued'、调度器、depends_on 的出队判据都是批 3), // **自动拆分也不在**(task-planning 是批 2)。所以这里一次只起得来一条 run,起不来就是 409 —— // 与既有唯一索引 idx_graph_runs_one_active_root 的语义保持一致,绝不假装「已排上队」: // 仓库里还没有出队的 worker,排进去的任务不会被消费,那是一条会静默丢任务的路。 /** * 数据层的两个专有错误 → HTTP(§四.4 描述冻结 / §六.3 依赖校验)。 * 不是这两个就返回 null,由调用方原样抛出去走 500 —— 把未知错误也翻成 4xx 会让真 bug 变成 * 「用户输入有问题」,那是最难被发现的一种掩盖。 */ function sendDomainError(res, err) { // 判定用 instanceof 而不是 `err.name === '…'`(缺陷 F10): // 字符串比较对**任何**把 name 设成同样字面量的错误都成立(包括 agent 生成代码里随手 // `err.name = 'DependsOnError'` 的那种),而且它让数据层导出的这两个类没有任何调用方 —— // 「导出了、零人使用」正是 §九.4quater 立案的惯犯。全仓 work-graph-db 只有相对路径 require, // 是同一个模块实例,instanceof 成立。 const { FrozenFieldError, DependsOnError } = require('../services/work-graph-db'); if (err instanceof FrozenFieldError) { return res.status(409).json({ error: err.message, frozenFields: err.fields, hint: '描述已被 agent 消费过(写进了 task-goal.json),要改就取消后新建,不要就地改', }); } if (err instanceof DependsOnError) { return res.status(400).json({ error: err.message }); } return null; } /** * mode 的信任边界校验,**三个入口共用这一份**(POST /goals、POST /tasks、PATCH /tasks)。 * * PATCH 侧原先没有这道校验,非法值直送 DB 撞 CHECK 约束 → 500 且把 SQLite 原文回给调用方 * (缺陷 F7)。500 的含义是「服务端出错了」,用户会去重试;正确答案是 400「你传错了」。 * * 返回 undefined 表示**没传**(调用方据此跳过这个字段),null 表示**传了但非法**—— * 两者必须分得开:`{"mode": null}` 走 `!== undefined` 的过滤会被当成没传, * 于是接口回 200 而什么都没改,那是最难被发现的一种半生效。 */ function normalizeMode(...candidates) { const raw = candidates.find((v) => v !== undefined); if (raw === undefined) return undefined; return raw === 'manual' || raw === 'auto' ? raw : null; } /** budget_json 列(TEXT)→ 对象;空 / 脏行返回 null,由调用方退回默认值 */ function parseBudget(raw) { if (!raw) return null; try { const v = JSON.parse(raw); return v && typeof v === 'object' ? v : null; } catch { return null; // 一条脏行不该让下达整个失败:退回 DEFAULT_TASK_BUDGET 至少能跑 } } /** * 一句自然语言 → 列表上的短标题。 * 截断丢信息无所谓:title 只是列表上的一个标签,不进任何 agent 的上下文(§四.4), * 验收边界一律看 description。 */ function deriveTitle(text) { const line = String(text || '').split('\n').find((l) => l.trim()) || ''; const t = line.trim(); return t.length > 60 ? `${t.slice(0, 60)}…` : t; } /** 当前占着坑的那条 root run;没有返回 null */ function activeRootRun(companyId) { const { listCompanyRuns } = require('../services/work-graph-db'); return ( listCompanyRuns(companyId, { rootOnly: true }).find((r) => ACTIVE_ROOT_RUN_STATUS.includes(r.run_status) ) || null ); } /** goal 行 → 对外形状。库里是 snake_case,API 一律 camelCase(同 getRunState 口径) */ function goalView(g, tasks = null) { return { goalId: g.id, companyId: g.company_id, title: g.title, description: g.description, status: g.status, priority: g.priority, okrNodeId: g.okr_node_id, createdBy: g.created_by, reportTo: g.report_to, verdict: g.verdict, // 拆分 / 验收各自烧掉的 token。goal 层的花费不挂在任何 run 的预算池上(那个池按 root run 算), // 所以它只记账不设闸门 —— 记不记这一笔,决定的是这半边花费看不看得见。 planningTokens: g.planning_tokens, validationTokens: g.validation_tokens, createdAt: g.created_at, updatedAt: g.updated_at, dispatchedAt: g.dispatched_at, archivedAt: g.archived_at, ...(tasks ? { tasks } : {}), }; } /** task 行 → 对外形状。progress 由 taskProgress 一条 GROUP BY 批量算好后传进来 */ function taskView(t, progress = null) { let dependsOn = []; try { const v = JSON.parse(t.depends_on || '[]'); if (Array.isArray(v)) dependsOn = v.map(String); } catch { dependsOn = []; // 一条脏行不该让整个列表炸掉 } return { taskId: t.id, goalId: t.goal_id, companyId: t.company_id, seq: t.seq, title: t.title, description: t.description, status: t.status, mode: t.execution_mode, priority: t.priority, // 回出来才看得见:budget 此前只有写侧(缺陷 F3),用户填了什么、最后生效的是不是它, // 在界面上一个字都查不到,直到任务跑到一半 blocked budget: parseBudget(t.budget_json), dependsOn, // 没有 run 或 run 还没有节点行时是 null,前端据此画「未开始」而不是 0/0 progress: progress || null, runId: t.current_run_id, attempt: t.attempt, blockedReason: t.blocked_reason, reportTo: t.report_to, createdAt: t.created_at, queuedAt: t.queued_at, startedAt: t.started_at, finishedAt: t.finished_at, archivedAt: t.archived_at, }; } /** 一批 task 的进度:一条 GROUP BY 出全部(验收 10 点名要挡的就是这里的 N+1) */ function progressOf(tasks) { const { taskProgress } = require('../services/work-graph-db'); return taskProgress(tasks.map((t) => t.current_run_id)); } /** 首个 task 下达时给 goal 盖上 dispatched_at —— 它就是 goal 级的描述冻结点(§四.4) */ function markGoalDispatched(goal) { const { updateGoal } = require('../services/work-graph-db'); if (goal.dispatched_at) return goal; return updateGoal(goal.id, { status: 'active', dispatchedAt: new Date().toISOString() }) || goal; } /** * 给一条 task 起一条 root graph run —— POST /:cid/tasks 与 goal dispatch 共用的那一段。 * * 建 root run(graph_kind='org'、graph_id=company_id、root_run_id=自己)→ 写 task-goal.json * → markRunReady → startRun 点亮入口节点 → **立即返回,不等图跑完**。 * 起不来(唯一索引拦截)就把异常原样抛给调用方翻 409,本函数不吞。 * * @returns {{runId, run, artifact, task}} task 是回写过 current_run_id / status 的新行 */ function launchTaskRun({ companyId, taskRow, budget }) { const wdb = require('../services/work-graph-db'); const engine = require('../services/graph-engine'); const created = wdb.createRun({ graphKind: 'org', graphId: companyId, // kind='org' 时 graph_id 就是 company_id companyId, goalId: taskRow.goal_id, taskId: taskRow.id, // §四.7 禁令一:**不传 okr_node_id**。okr_node_id 只存在 goals 表上。 // 一个 goal 挂一个 OKR 节点、下面 N 个 task 各带一份,收敛汇报就会把同一个节点写 N 次 // 且没有合并逻辑 —— 最后一个收敛的 task 说了算,一条 failed 的尾巴能把已经 done 的 // 节点翻成 failed。OKR 由 goal 收敛(全部 task 终态)时写一次,见 services/task-settle.js。 executionMode: taskRow.execution_mode, budget, }); const runId = created.id; const artifact = writeTaskGoalArtifact(companyId, runId, { runId, companyId, taskId: taskRow.id, goalId: taskRow.goal_id, // artifact 里同样不写 okrNodeId:agent 侧读它只为拿任务描述,多一个会被误当可写的度量目标 task: taskRow.description, createdAt: new Date().toISOString(), }); engine.markRunReady(runId); // startRun:manual 只标 running + 点亮入口节点,停在原地等 /next; // auto 挂一个自我调度的 driver,同样立即返回(一次跑到底是分钟~小时级)。 const { driver } = engine.startRun(runId, { mode: taskRow.execution_mode, task: taskRow.description }); // driver 只剩「别让 rejection 变成 unhandled」这一个用途:收敛后的对外汇报**不再挂在它身上** // (缺陷 3,理由见上方那段注释),状态回写走 transitionRun 的钩子,两者都与 driver 无关。 if (driver) driver.catch((e) => console.error(`[TaskEntry] auto driver 异常: ${e.message}`)); const now = new Date().toISOString(); const task = wdb.updateTask(taskRow.id, { status: 'running', currentRunId: runId, attempt: (taskRow.attempt || 0) + 1, // queued_at 是 task 级的描述冻结点(§四.4)。批 1 没有队列,「下达」即「入队」那一刻, // 描述从这里起被 task-goal.json 消费过了,再改就等于篡改已被 agent 读过的审计输入。 queuedAt: taskRow.queued_at || now, startedAt: now, }); return { runId, run: wdb.getRun(runId) || {}, artifact, task }; } /** 公司存在性 + goal 归属校验,返回 goal 行;不合法时已经 res 过了,调用方直接 return */ function requireGoal(req, res) { const { getGoal } = require('../services/work-graph-db'); const goal = getGoal(req.params.goalId); if (!goal || goal.company_id !== req.params.companyId) { res.status(404).json({ error: `goal ${req.params.goalId} 不存在于公司 ${req.params.companyId}` }); return null; } return goal; } /** 同上,task 版 */ function requireTask(req, res) { const { getTask } = require('../services/work-graph-db'); const task = getTask(req.params.taskId); if (!task || task.company_id !== req.params.companyId) { res.status(404).json({ error: `task ${req.params.taskId} 不存在于公司 ${req.params.companyId}` }); return null; } return task; } /** * GET /api/company/:companyId/goals — goal 列表 * query: status / includeArchived / withTasks=1(带出每个 goal 的 task 摘要) * * withTasks 存在的理由就是**不让前端 N+1**:一次把全公司的 task 拉回来在内存里归组, * 进度另走一条 GROUP BY(验收 10)。 */ router.get('/:companyId/goals', (req, res) => { try { const wdb = require('../services/work-graph-db'); const companyId = req.params.companyId; // 公司不存在 → 404(缺陷 F9)。不查的话打错一个字母就回 200 + 空列表, // 与「这家公司确实还没有目标」完全无法区分 —— 排查会从「为什么目标丢了」开始, // 而真相是 URL 里的 id 拼错了。本文件其它端点都有这道兜底,两个新 GET 漏了。 if (!companyService.get(companyId)) { return res.status(404).json({ error: `公司 ${companyId} 不存在` }); } const includeArchived = req.query.includeArchived === '1' || req.query.includeArchived === 'true'; const goals = wdb.listCompanyGoals(companyId, { status: req.query.status || null, includeArchived }); if (req.query.withTasks !== '1' && req.query.withTasks !== 'true') { return res.json({ goals: goals.map((g) => goalView(g)) }); } const tasks = wdb.listCompanyTasks(companyId, { includeArchived }); const progress = progressOf(tasks); const byGoal = new Map(); for (const t of tasks) { if (!byGoal.has(t.goal_id)) byGoal.set(t.goal_id, []); byGoal.get(t.goal_id).push(t); } res.json({ goals: goals.map((g) => goalView( g, // 两级树的显示顺序 = seq(listGoalTasks 的口径)。队列位次是另一回事,找调度器要。 (byGoal.get(g.id) || []) .sort((a, b) => a.seq - b.seq || a.created_at.localeCompare(b.created_at)) .map((t) => taskView(t, progress.get(t.current_run_id))) ) ), }); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * POST /api/company/:companyId/goals — 新建 goal * * body: { * title?, description | task, priority?, okr_node_id?, report_to?, budget?, * tasks?: [{ title?, description, mode?, priority?, budget?, depends_on? }] * } * * **批 1 一律按 `split: false` 处理**:传了 tasks 就照建,没传就建一条同描述的 task。 * 自动拆分(`split: true` → 异步调 task-planning → goal 短暂停在 'planning')是批 2; * 在它落地之前,本端点绝不返回 'planning' —— 一个没有任何东西会把它推走的中间态, * 就是一个卡死的 goal。响应里显式回 `split: false`,让调用方看得见这次没拆。 * * **`tasks[].depends_on` 的两种引用形态**(缺陷 F5):同一次 POST 里兄弟 task 的 id 由服务端 * 生成,调用方在写请求体时根本无从引用 —— 只认真 id 的话这个入参结构上只有传空数组才可能成功, * 而批 2 的 task-planning 拆分产出的正是「第 2 条依赖第 1 条」这种形状(§四.9 的产出契约就写着 * `depends_on 只引用本次产出的 seq`)。所以这里收两种: * - **数字**(或纯数字字符串)→ 本次 payload 内的 `seq`,1-based,即 `tasks[]` 的下标 + 1; * - **其它字符串** → 既有 task 的真 id(本端点建的是新 goal,同 goal 内没有旧 task, * 所以这条路只会走到数据层的「只能引用同 goal 内已存在的 task」错误上;留着它是为了 * 和 `PATCH /tasks/:id` 的入参形态一致,调用方不必按端点切换写法)。 * 响应里的 `tasks[].dependsOn` 一律是**翻译后的真 id**。 * * 产出一律是 draft,**不自动下达**(下达走 POST .../dispatch)。 */ router.post('/:companyId/goals', (req, res) => { const companyId = req.params.companyId; try { const body = req.body || {}; const description = String(body.description || body.task || '').trim(); if (!description) return res.status(400).json({ error: 'description(需求原文 = 验收边界)为必填项' }); if (!companyService.get(companyId)) { return res.status(404).json({ error: `公司 ${companyId} 不存在` }); } const wdb = require('../services/work-graph-db'); const goalTitle = String(body.title || '').trim() || deriveTitle(description); const priority = body.priority || 'P1'; const createdBy = body.created_by || 'human'; // 没给 tasks 就退化成 1 条同描述的 task —— 这也是批 2 拆分失败时的降级形态, // 两条路径落到同一段代码,免得降级路径自己长出第二套语义。 const specs = Array.isArray(body.tasks) && body.tasks.length ? body.tasks : [{ title: goalTitle, description, mode: body.mode || body.execution_mode }]; // ── 第一遍:**在任何 INSERT 之前**把整份 payload 校验完(缺陷 F4)。 // 原先是边校验边插:第 k 条不合法时 0..k-1 条已各自 INSERT 且 goal 也已提交(没有事务), // 400 之后库里躺着半个 goal + 半批 task,客户端改完重发又是**第二个** goal, // 第一个孤儿 goal 永远留在列表上。校验前置 + 下面的事务,两道一起上。 const plans = []; for (let i = 0; i < specs.length; i += 1) { const s = specs[i] || {}; const d = String(s.description || s.task || '').trim(); if (!d) return res.status(400).json({ error: `tasks[${i}].description 为必填项` }); const mode = normalizeMode(s.mode, s.execution_mode); if (mode === null) { return res.status(400).json({ error: `tasks[${i}].mode 只能是 'manual' 或 'auto',收到: ${JSON.stringify(s.mode ?? s.execution_mode)}` }); } const rawDeps = s.depends_on !== undefined ? s.depends_on : s.dependsOn; if (rawDeps !== undefined && rawDeps !== null && !Array.isArray(rawDeps)) { return res.status(400).json({ error: `tasks[${i}].depends_on 必须是数组` }); } plans.push({ seq: i + 1, // seq 显式给,别靠 MAX+1 —— depends_on 的 seq 引用要能对得上服务端分配的号 title: String(s.title || '').trim() || deriveTitle(d), description: d, mode: mode || 'manual', // undefined = 没传 → 默认 manual;null 在上面已经 400 掉了 priority: s.priority || priority, budget: s.budget !== undefined ? s.budget : body.budget, // 每条可单独给,否则继承 goal 级默认 deps: (rawDeps || []).map(String), }); } // ── 第二遍:建行。整段一个事务 —— depends_on 的环检测要等兄弟行都在库里才跑得了 // (它查的就是同 goal 的 tasks),一旦抛错整批连 goal 一起回滚,不留孤儿。 let goal; let created = []; try { wdb.getDb().transaction(() => { goal = wdb.createGoal({ companyId, title: goalTitle, description, priority, okrNodeId: body.okr_node_id || null, createdBy, reportTo: body.report_to || null, }); created = plans.map((p) => wdb.createTask({ goalId: goal.id, companyId, seq: p.seq, title: p.title, description: p.description, executionMode: p.mode, priority: p.priority, budgetJson: p.budget, // 建行时就存下来:草稿路径上请求体活不到 dispatch(缺陷 F3) createdBy, }) ); // seq → 真 id,再把依赖翻过去。走 updateTask 而不是在这里自己判环: // 环检测的唯一持有者是数据层的 validateDependsOn,路由再抄一份就是第二个持有者。 const bySeq = new Map(created.map((t) => [String(t.seq), t.id])); created = created.map((row, i) => { const deps = plans[i].deps; if (!deps.length) return row; const real = deps.map((d) => bySeq.get(d) || d); // 认不出的原样透传,由数据层报「不存在」 return wdb.updateTask(row.id, { dependsOn: real }); }); })(); } catch (err) { const handled = sendDomainError(res, err); if (handled) return; throw err; } res.status(201).json({ success: true, split: false, // 批 1 不调 task-planning,见上方注释 ...goalView(goal, created.map((t) => taskView(t))), links: { dispatch: `/api/company/${companyId}/goals/${goal.id}/dispatch` }, }); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** GET /api/company/:companyId/goals/:goalId — goal + 全部 task + 每条 task 的当前 run 摘要 */ router.get('/:companyId/goals/:goalId', (req, res) => { try { const wdb = require('../services/work-graph-db'); const goal = requireGoal(req, res); if (!goal) return; const tasks = wdb.listGoalTasks(goal.id, { includeArchived: req.query.includeArchived === '1' || req.query.includeArchived === 'true', }); const progress = progressOf(tasks); res.json( goalView( goal, tasks.map((t) => { const view = taskView(t, progress.get(t.current_run_id)); // run 摘要按主键逐条查:一个 goal 内的 task 是个位数,这里的 N 有硬上限, // 不是列表页那种随公司规模长的 N+1(进度仍然只走一条 GROUP BY)。 const run = t.current_run_id ? wdb.getRun(t.current_run_id) : null; view.run = run ? { runId: run.id, runStatus: run.run_status, executionMode: run.execution_mode, updatedAt: run.updated_at } : null; return view; }) ) ); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * PATCH /api/company/:companyId/goals/:goalId — 改 title / priority / okr_node_id * dispatched_at 非空时带 description 一律 409(§四.4)。 */ router.patch('/:companyId/goals/:goalId', (req, res) => { try { const { updateGoal } = require('../services/work-graph-db'); const goal = requireGoal(req, res); if (!goal) return; const body = req.body || {}; const patch = {}; if (body.title !== undefined) patch.title = String(body.title); if (body.priority !== undefined) patch.priority = String(body.priority); if (body.okr_node_id !== undefined) patch.okrNodeId = body.okr_node_id || null; // description 照传给数据层,由它按冻结规则决定放行还是抛 —— 冻结判据只留数据层一处, // 路由这边再抄一遍 `if (goal.dispatched_at)` 就是第二个持有者。 if (body.description !== undefined) patch.description = String(body.description); try { res.json(goalView(updateGoal(goal.id, patch))); } catch (err) { const handled = sendDomainError(res, err); if (handled) return; throw err; } } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * POST /api/company/:companyId/goals/:goalId/dispatch — 下达这个 goal * * **批 1 的语义 = 下达即执行,不入队**:给 goal 盖上 dispatched_at(描述从此冻结), * 然后按 seq 起**第一条上游就绪的** draft task 的 run。其余 draft 原地不动,响应里如实列出来。 * * 为什么不是「全部入队」:v1 一家公司同时只有一个 active root run(唯一索引 * idx_graph_runs_one_active_root),而出队的 worker 是批 3 才有的东西。把 N 条都标成 * 「已入队」而没有任何东西会把它们推走,就是把「静默丢任务」写进数据 —— 宁可让用户看到 * 「还有 2 条待下达」,也不要给一个不兑现的承诺。 * * **依赖是硬约束**(缺陷 F6 + 第二轮复核 缺陷 4):绝不起一条上游没跑完的 task —— * 「接口收下了 depends_on、返回成功、随后无声地违反它」比不支持依赖更糟:用户设了 * 「部署依赖构建」,dispatch 却起了 seq 最小的部署,图跑完了他也不会知道顺序错了。 * 但「挡」不等于「拒绝整个 goal」:有别的 draft 跑得动就起那一条(见下方挑选逻辑), * 一条都跑不动才 409。批 1 的自救路径:draft 状态可以 `PATCH /tasks/:id` 改 depends_on 或 seq * (两条都真的通,seq 是缺陷 4 一起补上的 —— hint 里写着的自救路径必须存在)。 */ router.post('/:companyId/goals/:goalId/dispatch', (req, res) => { const companyId = req.params.companyId; try { const wdb = require('../services/work-graph-db'); const goal = requireGoal(req, res); if (!goal) return; const drafts = wdb.listGoalTasks(goal.id).filter((t) => t.status === 'draft'); if (!drafts.length) { return res.status(409).json({ error: `goal ${goal.id} 下没有待下达的 task`, hint: `先 POST /api/company/${companyId}/tasks 往这个 goal 里加一条(带 goal_id)`, }); } const graph = orgGraphService.getGraph(companyId); if (!graph.nodes || graph.nodes.length === 0) { return res.status(409).json({ error: `公司 ${companyId} 还没有 org graph,无法接任务`, hint: `先调 POST /api/company/${companyId}/org-graph/replan 让 orggraph-planning 规划组织结构`, }); } const active = activeRootRun(companyId); if (active) { return res.status(409).json({ error: `公司 ${companyId} 已有进行中的任务(v1 约束:一家公司同时只有一个 active root run)`, activeRunId: active.id, activeTaskId: active.task_id, activeRunStatus: active.run_status, hint: `先 POST /api/graph-runs/${active.id}/stop 停止它,或等它收敛后再下达`, }); } // 未完成的上游 = 除 completed 以外的任何状态(含查不到的行:依赖的 task 被归档删号时 // 宁可挡下也不要放行 —— 放行等于把「上游产物已就绪」这个前提凭空当真)。 const blockersOf = (t) => { let deps = []; try { const v = JSON.parse(t.depends_on || '[]'); if (Array.isArray(v)) deps = v.map(String); } catch { deps = []; } return deps.filter((id) => (wdb.getTask(id) || {}).status !== 'completed'); }; // 挑第一条**跑得动**的 draft,而不是恒取 seq 最小那条(第二轮复核 缺陷 4)。 // 原先 `const head = drafts[0]` + 「有阻塞就 409」组合起来是个死结: // `validateDependsOn` 只拒环、不拒正向引用,所以 `tasks[0].depends_on:[2]` // (第 1 条依赖第 2 条)建得出来,而 dispatch 从不换人挑 —— 这个 goal 通过 API // 就**永远下达不了**。批 2 的 task-planning 产出契约正是「depends_on 只引用本次产出的 seq」, // 产出乱序完全在射程内,靠「让用户自己去调 seq」兜底等于把工具的活推给人。 // // 全都跑不动才 409,此时点名的是**最先考察的那条**(drafts 按 seq → created_at 排, // 它就是用户心里的「下一条」)—— 报一个随机的被阻塞者只会让人更迷惑。 // ponytail: 批 3 的调度器会取代这一段,语义从「挑一条能跑的」升级成 // 「按 priority → seq → created_at 排序后挑一条能跑的出队」,位次口径只归调度器持有。 let head = null; let firstBlocked = null; for (const d of drafts) { const blockers = blockersOf(d); if (!blockers.length) { head = d; break; } if (!firstBlocked) firstBlocked = { task: d, blockers }; } if (!head) { const { task, blockers } = firstBlocked; return res.status(409).json({ error: `goal ${goal.id} 下没有一条 task 的上游是就绪的(最先考察的 ${task.id} 被挡住)`, taskId: task.id, blockedBy: blockers, hint: `先让 ${blockers.join(' / ')} 跑到 completed;` + `顺序不对就改依赖或 seq:PATCH /api/company/${companyId}/tasks/${task.id}`, }); } let launched; try { launched = launchTaskRun({ companyId, taskRow: head, // 优先级:本次 dispatch 的 body > 建 task 时存下的 budget_json > 默认值(缺陷 F3)。 // 中间那一环原先根本没读,于是「409 已存为草稿 → 稍后 dispatch」这条被 hint 明确推荐的 // 路径上,用户提交时填的预算被静默丢弃、run 拿着 DEFAULT_TASK_BUDGET 跑到一半 blocked。 // body 覆盖后不回写 task 行:budget 在 queued_at 之后是冻结字段(§四.4), // 草稿行留的是「当初申报的额度」,本次实际用量以 run 的 budget_json 为准。 budget: (req.body && req.body.budget) || parseBudget(head.budget_json) || DEFAULT_TASK_BUDGET, }); } catch (e) { // 并发下唯一索引才是真正的守卫(上面的预检查有竞态窗口) if (/UNIQUE|constraint/i.test(e.message)) { return res.status(409).json({ error: `公司 ${companyId} 已有进行中的任务(唯一索引拦截)` }); } throw e; } const dispatchedGoal = markGoalDispatched(goal); // 不能再写 `drafts.slice(1)`:head 已经不保证是 drafts[0](缺陷 4), // 那样会把真正起了 run 的那条也算进「待下达」、又漏掉被跳过的第一条。 const pending = drafts.filter((t) => t.id !== head.id); res.status(201).json({ success: true, goalId: dispatchedGoal.id, goalStatus: dispatchedGoal.status, started: { taskId: launched.task.id, runId: launched.runId, runStatus: launched.run.run_status }, pendingTasks: pending.map((t) => t.id), ...(pending.length ? { hint: `其余 ${pending.length} 条仍是 draft:v1 一次只跑一条,等这条收敛后再调一次本端点` } : {}), links: { state: `/api/graph-runs/${launched.runId}`, next: `/api/graph-runs/${launched.runId}/next`, stream: `/api/graph-runs/${launched.runId}/stream`, }, }); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * DELETE /api/company/:companyId/goals/:goalId — 归档(连带归档其下 task) * * 归档只是隐藏:行还在,`includeArchived=1` 随时查得回来。有 task 还攥着 run 就先 409 * (判据见 `taskHoldsRun`:running / blocked / run 仍在活跃取值域)—— * 把一条正在烧钱的 run 的 task 藏起来,等于让它在界面上消失却继续跑。 */ router.delete('/:companyId/goals/:goalId', (req, res) => { try { const wdb = require('../services/work-graph-db'); const goal = requireGoal(req, res); if (!goal) return; const tasks = wdb.listGoalTasks(goal.id); const running = tasks.filter(taskHoldsRun); if (running.length) { return res.status(409).json({ error: `goal ${goal.id} 下还有正在执行或挂起的 task`, runningTasks: running.map((t) => t.id), hint: `先停止 ${running[0].id}:POST /api/graph-runs/${running[0].current_run_id}/stop`, }); } const now = new Date().toISOString(); for (const t of tasks) { if (!t.archived_at) wdb.updateTask(t.id, { archivedAt: now }); } res.json({ success: true, goalId: goal.id, archivedTasks: tasks.filter((t) => !t.archived_at).length, goal: goalView(wdb.updateGoal(goal.id, { archivedAt: now })), }); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * GET /api/company/:companyId/tasks — task 列表(新端点:这个路径下此前只有 POST) * query: status / goalId / includeArchived / limit * * 进度走 taskProgress 的一条 GROUP BY,不按行查(验收 10)。 * 排序沿用数据层的 created_at DESC —— **队列位次的口径(priority → seq → created_at) * 只留调度器一处**,这里再写一份就是第二个持有者,canDispatch 被前端复述了一遍还多写一个值、 * 导致公司失败一次后再也下不了任务,就是这么来的。 */ router.get('/:companyId/tasks', (req, res) => { try { const wdb = require('../services/work-graph-db'); // 同 GET /goals:公司不存在要 404,不能拿空列表冒充「这家公司没有任务」(缺陷 F9) if (!companyService.get(req.params.companyId)) { return res.status(404).json({ error: `公司 ${req.params.companyId} 不存在` }); } const limit = parseInt(req.query.limit, 10); const tasks = wdb.listCompanyTasks(req.params.companyId, { status: req.query.status || null, goalId: req.query.goalId || req.query.goal_id || null, includeArchived: req.query.includeArchived === '1' || req.query.includeArchived === 'true', limit: Number.isInteger(limit) ? limit : null, }); const progress = progressOf(tasks); res.json({ tasks: tasks.map((t) => taskView(t, progress.get(t.current_run_id))) }); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * POST /api/company/:companyId/tasks — 用户给公司下达一个任务 * * body: { * task | description, 必填,一句自然语言任务(= task-goal,27-NAMING §四) * goal_id?, 挂到既有 goal 下;**不传则自动建一个同描述的 goal**。 * ⚠️ 对外可见的破坏性变更:旧代码把它原样存进 * graph_runs.goal_id 且不校验,现在它必须是 goals 表里 * 本公司的真行,否则 404。外部 agent 若一直往这里传 * OKR 节点 id 之类的值,会从 201 变 404 —— 那种调用方 * 本来就在制造悬空外键(正是本批要补的窟窿),404 是对的。 * okr_node_id?, 只写进 goals 表,不进 run(§四.7 禁令一) * mode?: 'manual' | 'auto', 默认 manual;auto 前端必须先弹预估成本确认(§四.B.4) * budget?, 覆盖 DEFAULT_TASK_BUDGET,只挂 root run * report_to? 收敛后要唤醒的上级 agent(Master/CEO 代下单时传)—— * 现在会**落库**到 goals/tasks.report_to(§四.7 禁令二) * } * * **行为兼容是硬要求**:存量调用方(DispatchTaskButton、外部 agent 的 curl)一行不用改还能用, * 响应体只是多出 goalId。为什么必须自动建 goal 而不是允许 task 悬空:goal 是验收边界的持有者, * 没有 goal 的 task 在两级树里无处可挂 —— 那正是本次要修的「界面上画不出来」。 */ router.post('/:companyId/tasks', (req, res) => { const companyId = req.params.companyId; try { const body = req.body || {}; const description = String(body.task || body.description || '').trim(); if (!description) return res.status(400).json({ error: 'task(任务描述)为必填项' }); const company = companyService.get(companyId); if (!company) return res.status(404).json({ error: `公司 ${companyId} 不存在` }); const requestedMode = normalizeMode(body.mode, body.execution_mode); if (requestedMode === null) { return res.status(400).json({ error: `mode 只能是 'manual' 或 'auto',收到: ${JSON.stringify(body.mode ?? body.execution_mode)}` }); } const mode = requestedMode || 'manual'; // 没有 org graph 就没有可执行的图(graph_kind='org' 的定义层就是它) const graph = orgGraphService.getGraph(companyId); if (!graph.nodes || graph.nodes.length === 0) { return res.status(409).json({ error: `公司 ${companyId} 还没有 org graph,无法接任务`, hint: `先调 POST /api/company/${companyId}/org-graph/replan 让 orggraph-planning 规划组织结构`, }); } const wdb = require('../services/work-graph-db'); // v1 并发约束:已有 active root run 时**拒绝**(不排队,理由见本节开头)。 // 放在建 goal / task 之前,免得 409 的路径上留一串没人会下达的草稿行。 const active = activeRootRun(companyId); if (active) { return res.status(409).json({ error: `公司 ${companyId} 已有进行中的任务(v1 约束:一家公司同时只有一个 active root run)`, activeRunId: active.id, activeTaskId: active.task_id, activeRunStatus: active.run_status, hint: `先 POST /api/graph-runs/${active.id}/stop 停止它,或等它收敛`, }); } const createdBy = body.created_by || body.from || 'human'; let goal; if (body.goal_id) { goal = wdb.getGoal(body.goal_id); if (!goal || goal.company_id !== companyId) { return res.status(404).json({ error: `goal ${body.goal_id} 不存在于公司 ${companyId}` }); } } else { goal = wdb.createGoal({ companyId, title: deriveTitle(description), description, priority: body.priority || 'P1', okrNodeId: body.okr_node_id || null, createdBy, reportTo: body.report_to || null, }); } let taskRow; try { taskRow = wdb.createTask({ goalId: goal.id, companyId, title: deriveTitle(description), description, executionMode: mode, priority: body.priority || goal.priority, // 落库(缺陷 F3):本次起不来 run 时(唯一索引 409)这行就是草稿,hint 让用户稍后 // dispatch —— 那时请求体早没了,不存下来 dispatch 只能用默认额度,而用户以为自己填的算数。 budgetJson: body.budget !== undefined ? body.budget : null, // 显式传 report_to 优先,其次继承 goal 的(数据层也会兜一次,这里传的是本次请求的意图) reportTo: body.report_to || null, createdBy, }); } catch (err) { const handled = sendDomainError(res, err); if (handled) return; throw err; } let launched; try { launched = launchTaskRun({ companyId, taskRow, budget: body.budget || DEFAULT_TASK_BUDGET }); } catch (e) { // 并发下唯一索引才是真正的守卫(上面的预检查有竞态窗口)。 // task 行已经建出来了,就留着当草稿 —— 比回滚有用:等当前任务收敛后一条 dispatch 就能下达。 if (/UNIQUE|constraint/i.test(e.message)) { return res.status(409).json({ error: `公司 ${companyId} 已有进行中的任务(唯一索引拦截)`, goalId: goal.id, taskId: taskRow.id, hint: `任务已存为草稿,等当前任务收敛后 POST /api/company/${companyId}/goals/${goal.id}/dispatch 下达`, }); } throw e; } markGoalDispatched(goal); res.status(201).json({ success: true, runId: launched.runId, taskId: taskRow.id, goalId: goal.id, companyId, // 从 **goal** 上回,不是从 run 上 —— run 不再带 okr_node_id(§四.7 禁令一) okrNodeId: goal.okr_node_id, executionMode: mode, runStatus: launched.run.run_status, task: description, taskGoalArtifact: path.relative(REPO_ROOT, launched.artifact), budget: body.budget || DEFAULT_TASK_BUDGET, links: { state: `/api/graph-runs/${launched.runId}`, next: `/api/graph-runs/${launched.runId}/next`, stream: `/api/graph-runs/${launched.runId}/stream`, }, }); } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** * PATCH /api/company/:companyId/tasks/:taskId — 改 title / priority / seq / depends_on * * queued_at 非空时带 description / mode / budget 一律 409(§四.4); * depends_on 在 draft 与 queued 都可改(§六.3 定案),跑起来之后不可改。 * 两条判据都在数据层,这里只做入参翻译。 */ router.patch('/:companyId/tasks/:taskId', (req, res) => { try { const { updateTask } = require('../services/work-graph-db'); const task = requireTask(req, res); if (!task) return; const body = req.body || {}; const patch = {}; if (body.title !== undefined) patch.title = String(body.title); if (body.priority !== undefined) patch.priority = String(body.priority); // seq 可改(第二轮复核 缺陷 4):dispatch 的 409 hint 一直写着「顺序不对就改依赖或 seq」, // 而这里从不读 body.seq —— 两条自救路径只有一条通,用户照 hint 做完还是同样的 409, // 且接口回 200 假装改过了。列 TASK_PATCH_COLUMNS.seq 早就在,缺的只是这一行入参翻译。 // 必须挡非整数:seq 直接进 ORDER BY,一个 NaN / 'abc' 会让下达顺序变成谁也说不清的东西。 if (body.seq !== undefined) { const n = Number(body.seq); if (!Number.isInteger(n)) { return res.status(400).json({ error: `seq 必须是整数,收到: ${JSON.stringify(body.seq)}` }); } patch.seq = n; } if (body.depends_on !== undefined) patch.dependsOn = body.depends_on; else if (body.dependsOn !== undefined) patch.dependsOn = body.dependsOn; // 下面三个是冻结字段:照传给数据层,让它按 queued_at 决定放行还是抛 409 if (body.description !== undefined) patch.description = String(body.description); // mode 在这里就要过信任边界校验(缺陷 F7):直送 DB 会撞 tasks.execution_mode 的 CHECK 约束, // 变成 500 + 一句 SQLite 原文 —— 500 的意思是「服务端出错了」,用户会重试;正确答案是 400。 // 值必须显式区分「没传」与「传了 null」:`{"mode": null}` 走 `!== undefined` 过滤会被当没传, // 于是回 200 而什么都没改。 const patchedMode = normalizeMode(body.mode, body.execution_mode); if (patchedMode === null) { return res.status(400).json({ error: `mode 只能是 'manual' 或 'auto',收到: ${JSON.stringify(body.mode ?? body.execution_mode)}` }); } if (patchedMode) patch.executionMode = patchedMode; if (body.budget !== undefined) patch.budgetJson = JSON.stringify(body.budget); try { res.json(taskView(updateTask(task.id, patch))); } catch (err) { const handled = sendDomainError(res, err); if (handled) return; throw err; } } catch (err) { console.error('[TaskEntry] Error:', err.message); res.status(500).json({ error: err.message }); } }); /** DELETE /api/company/:companyId/tasks/:taskId — 归档一条 task(规则同 goal) */ router.delete('/:companyId/tasks/:taskId', (req, res) => { try { const { updateTask } = require('../services/work-graph-db'); const task = requireTask(req, res); if (!task) return; if (taskHoldsRun(task)) { return res.status(409).json({ error: `task ${task.id} 正在执行或挂起`, hint: `先停止它:POST /api/graph-runs/${task.current_run_id}/stop`, }); } res.json({ success: true, task: taskView(updateTask(task.id, { archivedAt: new Date().toISOString() })) }); } catch (err) { console.error('[TaskEntry] Error:', err.message); 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 OKR (公司级 OKR / 度量树) // ═══════════════════════════════════════ const { OkrService } = require('../services/okr-service'); // 公司级 OKR 路由。路径参数统一叫 :objectiveId(原 :goalId)——第 1 层节点已正名为 Objective。 // // 27-P3C §六.1:`/:companyId/goals` 这条向后兼容别名**已退役**(核实过零调用方, // 前端与 bin/lemon.js 走的都是 /okr)。理由不是「清理」,是 `/goals` 这个词在本文件里 // 从此另有所指 —— 它是 goals 表的两级模型端点。一个 URL 两种含义,读的人和写的人 // 迟早对不上;别名活着的每一天都在把两个概念往一起粘。 const okrPath = (suffix = '') => [`/:companyId/okr${suffix}`]; // GET /api/company/:companyId/okr router.get(okrPath(), (req, res) => { const okr = new OkrService(req.params.companyId); res.json(okr.list()); }); // POST /api/company/:companyId/okr router.post(okrPath(), (req, res) => { try { const { title, description, owner } = req.body; if (!title || !owner) { return res.status(400).json({ error: 'title 和 owner 为必填项' }); } const okr = new OkrService(req.params.companyId); res.status(201).json(okr.create({ title, description, owner })); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/:companyId/okr/:objectiveId router.get(okrPath('/:objectiveId'), (req, res) => { const okr = new OkrService(req.params.companyId); const objective = okr.get(req.params.objectiveId); if (!objective) return res.status(404).json({ error: 'Objective not found' }); res.json(objective); }); // PUT /api/company/:companyId/okr/:objectiveId router.put(okrPath('/:objectiveId'), (req, res) => { const okr = new OkrService(req.params.companyId); const result = okr.updateObjective(req.params.objectiveId, req.body); if (!result) return res.status(404).json({ error: 'Objective not found' }); res.json(result); }); // POST /api/company/:companyId/okr/:objectiveId/nodes router.post(okrPath('/:objectiveId/nodes'), (req, res) => { try { const { parentNodeId, title, owner, priority } = req.body; if (!title || !owner) { return res.status(400).json({ error: 'title 和 owner 为必填项' }); } const okr = new OkrService(req.params.companyId); const result = okr.addNode(req.params.objectiveId, parentNodeId || null, { title, owner, priority, }); if (!result) return res.status(404).json({ error: 'Objective not found' }); res.status(201).json({ nodeId: result.nodeId, node: result.objective.nodes[result.nodeId] }); } catch (err) { res.status(500).json({ error: err.message }); } }); // PUT /api/company/:companyId/okr/:objectiveId/nodes/:nodeId router.put(okrPath('/:objectiveId/nodes/:nodeId'), (req, res) => { const okr = new OkrService(req.params.companyId); const result = okr.updateNode(req.params.objectiveId, 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/okr/:objectiveId/progress router.get(okrPath('/:objectiveId/progress'), (req, res) => { const okr = new OkrService(req.params.companyId); const progress = okr.getProgress(req.params.objectiveId); if (!progress) return res.status(404).json({ error: 'Objective 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 }); } }); // ═══════════════════════════════════════ // Company Files — 公司级统一文件树 // ═══════════════════════════════════════ // GET /api/company/:companyId/files — 获取公司下所有 Agent 的文件树 router.get('/:companyId/files', (req, res) => { try { const path = require('path'); const fs = require('fs'); const companyDir = path.join(COMPANIES_DIR, req.params.companyId); if (!fs.existsSync(companyDir)) { return res.json({ tree: [], totalFiles: 0 }); } // 递归扫描目录 function scanDir(dirPath, relativePath = '') { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); const nodes = []; for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name; // 跳过隐藏文件和 node_modules if (entry.name.startsWith('.') || entry.name === 'node_modules') continue; // 跳过 conversations 目录(太大) if (entry.name === 'conversations') continue; if (entry.isDirectory()) { const children = scanDir(fullPath, relPath); nodes.push({ name: entry.name, path: relPath, type: 'directory', children, fileCount: children.reduce((sum, c) => sum + (c.type === 'file' ? 1 : (c.fileCount || 0)), 0), }); } else { const stat = fs.statSync(fullPath); nodes.push({ name: entry.name, path: relPath, type: 'file', size: stat.size, modifiedAt: stat.mtime.toISOString(), }); } } // 目录排前面, 然后按名字排序 return nodes.sort((a, b) => { if (a.type !== b.type) return a.type === 'directory' ? -1 : 1; return a.name.localeCompare(b.name); }); } const tree = scanDir(companyDir); const countFiles = (nodes) => nodes.reduce((sum, n) => sum + (n.type === 'file' ? 1 : countFiles(n.children || [])), 0); res.json({ tree, totalFiles: countFiles(tree) }); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/:companyId/files/content?path=xxx — 读取文件内容 router.get('/:companyId/files/content', (req, res) => { try { const path = require('path'); const fs = require('fs'); const filePath = req.query.path; if (!filePath) return res.status(400).json({ error: 'path 参数为必填' }); // 安全校验:防止路径穿越 const absPath = resolveInside(path.join(COMPANIES_DIR, req.params.companyId), filePath); if (!absPath) { return res.status(403).json({ error: '路径越界' }); } if (!fs.existsSync(absPath)) { return res.status(404).json({ error: '文件不存在' }); } const stat = fs.statSync(absPath); if (stat.size > 512 * 1024) { return res.json({ content: '(文件过大,跳过预览)', truncated: true, size: stat.size }); } const content = fs.readFileSync(absPath, 'utf-8'); res.json({ content, size: stat.size, path: filePath }); } catch (err) { res.status(500).json({ error: err.message }); } }); // PUT /api/company/:companyId/files/content — 保存文件内容 router.put('/:companyId/files/content', (req, res) => { try { const filePath = req.body.path; if (!filePath) return res.status(400).json({ error: 'path 参数为必填' }); const absPath = resolveInside(path.join(COMPANIES_DIR, req.params.companyId), filePath); if (!absPath) { return res.status(403).json({ error: '路径越界' }); } const dir = path.dirname(absPath); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(absPath, req.body.content || '', 'utf-8'); console.log(`[Company] 💾 已保存文件 ${req.params.companyId}/${filePath}`); res.json({ success: true, path: filePath }); } catch (err) { res.status(500).json({ error: err.message }); } }); // ═══════════════════════════════════════ // Company Workspace — 工作区文件管理 // ═══════════════════════════════════════ // GET /api/company/:companyId/workspace/files — 列出 workspace 文件树 router.get('/:companyId/workspace/files', (req, res) => { try { const wsDir = path.join(COMPANIES_DIR, req.params.companyId, 'workspace'); if (!fs.existsSync(wsDir)) { return res.json({ tree: [], totalFiles: 0 }); } function scanDir(dirPath, relativePath = '') { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); const nodes = []; for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name; if (entry.name.startsWith('.') || entry.name === 'node_modules') continue; if (entry.isDirectory()) { const children = scanDir(fullPath, relPath); nodes.push({ name: entry.name, path: relPath, type: 'directory', children, fileCount: children.reduce((sum, c) => sum + (c.type === 'file' ? 1 : (c.fileCount || 0)), 0), }); } else { const stat = fs.statSync(fullPath); nodes.push({ name: entry.name, path: relPath, type: 'file', size: stat.size, createdAt: stat.birthtime.toISOString(), modifiedAt: stat.mtime.toISOString(), }); } } return nodes.sort((a, b) => { if (a.type !== b.type) return a.type === 'directory' ? -1 : 1; return a.name.localeCompare(b.name); }); } const tree = scanDir(wsDir); const countFiles = (nodes) => nodes.reduce((sum, n) => sum + (n.type === 'file' ? 1 : countFiles(n.children || [])), 0); res.json({ tree, totalFiles: countFiles(tree) }); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/:companyId/workspace/files/content?path=xxx — 读取 workspace 文件内容 router.get('/:companyId/workspace/files/content', (req, res) => { try { const filePath = String(req.query.path || ''); if (!filePath) return res.status(400).json({ error: 'path 参数为必填' }); const absPath = resolveInside(path.join(COMPANIES_DIR, req.params.companyId, 'workspace'), filePath); if (!absPath) { return res.status(403).json({ error: '路径越界' }); } if (!fs.existsSync(absPath)) { return res.status(404).json({ error: '文件不存在' }); } const stat = fs.statSync(absPath); if (stat.size > 512 * 1024) { return res.json({ content: '(文件过大,跳过预览)', truncated: true, size: stat.size }); } const content = fs.readFileSync(absPath, 'utf-8'); res.json({ content, size: stat.size, path: filePath, createdAt: stat.birthtime.toISOString(), modifiedAt: stat.mtime.toISOString(), }); } catch (err) { res.status(500).json({ error: err.message }); } }); // PUT /api/company/:companyId/workspace/files/content — 保存 workspace 文件 router.put('/:companyId/workspace/files/content', (req, res) => { try { const filePath = req.body.path; if (!filePath) return res.status(400).json({ error: 'path 参数为必填' }); const absPath = resolveInside(path.join(COMPANIES_DIR, req.params.companyId, 'workspace'), filePath); if (!absPath) { return res.status(403).json({ error: '路径越界' }); } const dir = path.dirname(absPath); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(absPath, req.body.content || '', 'utf-8'); console.log(`[Workspace] 💾 已保存 ${req.params.companyId}/workspace/${filePath}`); res.json({ success: true, path: filePath }); } catch (err) { res.status(500).json({ error: err.message }); } }); // ═══════════════════════════════════════ // Company Messages — 全局消息时间线 // ═══════════════════════════════════════ // GET /api/company/:companyId/messages?limit=100 — 获取公司所有 Agent 的消息时间线 router.get('/:companyId/messages', (req, res) => { try { const path = require('path'); const fs = require('fs'); const limit = Math.min(parseInt(req.query.limit) || 200, 500); const allMessages = []; // 名册查 company_agents,会话在公司态目录 system/agents/{aid}/{cid}/conversations/(28 批次 4-19) for (const row of listCompanyAgents(req.params.companyId)) { const agentId = row.role_name; const convDir = path.join(locator.companyDir(row.system_agent_id, req.params.companyId), 'conversations'); if (!fs.existsSync(convDir)) continue; const conversations = fs.readdirSync(convDir, { withFileTypes: true }).filter(d => d.isDirectory()); for (const conv of conversations) { const convId = conv.name; // 读 meta let meta = null; try { meta = JSON.parse(fs.readFileSync(path.join(convDir, convId, 'meta.json'), 'utf-8')); } catch { continue; } // 读 history let history = []; try { history = JSON.parse(fs.readFileSync(path.join(convDir, convId, 'history.json'), 'utf-8')); } catch { continue; } for (const msg of history) { allMessages.push({ agentId: `${req.params.companyId}:${agentId}`, agentName: agentId, conversationId: convId, conversationTitle: meta?.title || convId, role: msg.role, content: (msg.content || '').slice(0, 800), timestamp: msg.timestamp || meta?.createdAt, messageId: msg.messageId, taskId: convId.startsWith('task-') ? convId.replace('task-', '') : null, }); } } } // 按时间倒序 allMessages.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()); res.json(allMessages.slice(0, limit)); } catch (err) { res.status(500).json({ error: err.message }); } }); // ═══════════════════════════════════════ // Company Stats — 统计 API (skills count, jobs status) // ═══════════════════════════════════════ // GET /api/company/:companyId/stats — 获取公司统计信息 router.get('/:companyId/stats', (req, res) => { try { const path = require('path'); const fs = require('fs'); const companyId = req.params.companyId; // 1. Agents 统计(名册查 company_agents) const agents = companyService.listAgents(companyId); const agentCount = agents.length; // 2. Skills 统计 —— Skill 挂在本体的 `.claude/skills/` 下(28 批次 4-19)。 // 注意这份计数因此是**本体级**的:两家公司雇同一个本体,各自的统计里都算它一次。 let totalSkills = 0; const agentSkills = []; for (const agent of agents) { const skillsDir = path.join(locator.bodyDir(agent.bodyId), '.claude', 'skills'); if (!fs.existsSync(skillsDir)) continue; const skillCount = fs.readdirSync(skillsDir, { withFileTypes: true }).filter(d => d.isDirectory()).length; totalSkills += skillCount; agentSkills.push({ agentId: agent.id, skillCount }); } // 3. Jobs 统计 - 从 jobs 持久化文件读取 let jobsStats = { total: 0, queued: 0, running: 0, completed: 0, failed: 0 }; const jobsFilePath = path.join(DATA_ROOT, '.data', 'jobs-openapi.json'); if (fs.existsSync(jobsFilePath)) { try { const jobsData = JSON.parse(fs.readFileSync(jobsFilePath, 'utf-8')); if (Array.isArray(jobsData)) { jobsStats.total = jobsData.length; for (const job of jobsData) { if (jobsStats[job.status] !== undefined) { jobsStats[job.status]++; } } } } catch (e) { console.warn('[Stats] 读取 Jobs 文件失败:', e.message); } } // 4. Pipelines 统计 const pSvc = new PipelineService(companyId); const pipelines = pSvc.listPipelines(); const runs = pSvc.listRuns(); const pipelinesStats = { total: pipelines.length, active: pipelines.filter(p => p.status === 'active').length, runs: { total: runs.length, running: runs.filter(r => r.status === 'running').length, completed: runs.filter(r => r.status === 'completed').length, failed: runs.filter(r => r.status === 'failed').length, } }; res.json({ companyId, timestamp: new Date().toISOString(), skills: { total: totalSkills, byAgent: agentSkills }, agents: { total: agentCount }, jobs: jobsStats, pipelines: pipelinesStats, }); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/:companyId/jobs — 获取公司相关的 Job 列表 router.get('/:companyId/jobs', (req, res) => { try { const path = require('path'); const fs = require('fs'); const jobsFilePath = path.join(DATA_ROOT, '.data', 'jobs-openapi.json'); if (!fs.existsSync(jobsFilePath)) { return res.json([]); } const jobsData = JSON.parse(fs.readFileSync(jobsFilePath, 'utf-8')); if (!Array.isArray(jobsData)) { return res.json([]); } // 过滤与公司相关的 Jobs (通过 domain 或 conversationId 包含 companyId) const limit = Math.min(parseInt(req.query.limit) || 50, 100); const companyId = req.params.companyId; const filtered = jobsData .filter(job => !job.domain || job.domain.includes(companyId)) .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()) .slice(0, limit); res.json(filtered); } catch (err) { res.status(500).json({ error: err.message }); } }); // GET /api/company/:companyId/jobs/:jobId — 获取 Job 详情 router.get('/:companyId/jobs/:jobId', (req, res) => { try { const path = require('path'); const fs = require('fs'); const jobsFilePath = path.join(DATA_ROOT, '.data', 'jobs-openapi.json'); if (!fs.existsSync(jobsFilePath)) { return res.status(404).json({ error: 'Job 不存在' }); } const jobsData = JSON.parse(fs.readFileSync(jobsFilePath, 'utf-8')); if (!Array.isArray(jobsData)) { return res.status(404).json({ error: 'Job 不存在' }); } const job = jobsData.find(j => j.jobId === req.params.jobId); if (!job) { return res.status(404).json({ error: 'Job 不存在' }); } // 返回安全版本 (隐藏 apiKey, webhookUrl) const { apiKey, webhookUrl, ...safeJob } = job; res.json(safeJob); } catch (err) { res.status(500).json({ error: err.message }); } }); module.exports = router;