#!/usr/bin/env node /** * PERLER LAB 任务管理系统 * 主代理发布任务 → 实施 Agent 认领/开发 → 提交验收 → 测试 Agent 测试 → 通过/不合格 * 不合格自动生成关联 Bug 任务,修复后重新验收 * * 用法: * node taskboard.js new "<标题>" --desc "<描述>" --priority high|medium|low --assignee "<角色>" * node taskboard.js list [--status pending|in_progress|review|approved|rejected|closed] [--type task|bug] [--all] * node taskboard.js claim --agent "" * node taskboard.js submit --note "<提交说明>" * node taskboard.js test --pass --note "<验收备注>" * node taskboard.js test --fail --note "<不合格原因>" [--priority high|medium|low] * node taskboard.js close --note "<关闭说明>" * node taskboard.js board # 生成 board.md + board.html(HTML 每 5 秒自动刷新) * node taskboard.js watch # 监视 tasks.json 变更,自动重建看板(常驻) * node taskboard.js serve [port] # 启动实时看板服务器,浏览器 2 秒轮询刷新(默认 8787) * node taskboard.js stats */ 'use strict'; const fs = require('fs'); const path = require('path'); const DATA_FILE = path.join(__dirname, 'tasks.json'); const BOARD_MD = path.join(__dirname, 'board.md'); const BOARD_HTML = path.join(__dirname, 'board.html'); const STATUS = { PENDING: 'pending', // 待处理(已发布,未被认领) IN_PROGRESS: 'in_progress', // 开发中(已被 Agent 认领) REVIEW: 'review', // 待验收(实施完成,提交测试) APPROVED: 'approved', // 验收通过 REJECTED: 'rejected', // 不合格(测试未通过) CLOSED: 'closed', // 已关闭 }; const STATUS_LABEL = { pending: '待处理', in_progress: '开发中', review: '待验收', approved: '验收通过', rejected: '不合格', closed: '已关闭', }; const PRIORITY = { HIGH: 'high', MEDIUM: 'medium', LOW: 'low' }; const PRIORITY_LABEL = { high: '高', medium: '中', low: '低' }; const PRIORITY_RANK = { high: 0, medium: 1, low: 2 }; const TZ_OFFSET_MS = 8 * 60 * 60 * 1000; // 中国标准时间 UTC+8(北京/上海) function now() { // 返回中国时区 ISO 格式,如 2026-08-13T17:30:00+08:00 return new Date(Date.now() + TZ_OFFSET_MS).toISOString().replace('Z', '+08:00'); } function load() { if (!fs.existsSync(DATA_FILE)) return { tasks: [], seq: 0, agents: {} }; const db = JSON.parse(fs.readFileSync(DATA_FILE, 'utf8')); if (!db.agents) db.agents = {}; return db; } function save(db) { fs.writeFileSync(DATA_FILE, JSON.stringify(db, null, 2), 'utf8'); } /* ---------- Agent 人力管理 ---------- */ function registerAgent(db, name) { if (!db.agents[name]) { db.agents[name] = { role: '未定岗', status: 'active', // active 在职 | standby 待命 | laid_off 已裁员 joinedAt: now(), lastActiveAt: now(), note: '', }; } db.agents[name].lastActiveAt = now(); if (db.agents[name].status === 'laid_off') db.agents[name].status = 'active'; return db.agents[name]; } function agentLoad(db) { // 反向补录:任务中存在但未注册的 agent 自动入册(并持久化,否则 serve 模式重新读文件时丢失) let dirty = false; for (const t of db.tasks) { if (t.agent && !db.agents[t.agent]) { registerAgent(db, t.agent); dirty = true; } } if (dirty) save(db); const roster = {}; for (const name of Object.keys(db.agents)) { const a = db.agents[name]; const mine = db.tasks.filter(t => t.agent === name); roster[name] = { role: a.role, status: a.status, active: mine.filter(t => [STATUS.IN_PROGRESS, STATUS.REVIEW].includes(t.status)).length, current: mine.filter(t => t.status === STATUS.IN_PROGRESS).map(t => t.id), reviewing: mine.filter(t => t.status === STATUS.REVIEW).map(t => t.id), done: mine.filter(t => [STATUS.APPROVED, STATUS.CLOSED].includes(t.status)).length, rejected: mine.filter(t => t.status === STATUS.REJECTED).length, total: mine.length, lastActiveAt: a.lastActiveAt, joinedAt: a.joinedAt, }; } return roster; } function cmdAgents(args) { const db = load(); const pending = db.tasks.filter(t => t.status === STATUS.PENDING).length; const roster = agentLoad(db); const names = Object.keys(roster).sort((a, b) => roster[b].active - roster[a].active); if (!names.length) { console.log('(无 Agent 在册)'); return; } console.log('=== Agent 火力面板 ==='); console.log(`待处理任务池: ${pending} | 在册 Agent: ${names.length}`); for (const n of names) { const r = roster[n]; const cur = r.current.concat(r.reviewing).join(',') || '-'; console.log(` [${r.status === 'active' ? '🔥在职' : r.status === 'standby' ? '💤待命' : '⚰️裁员'}] ${n} (${r.role}) 在办:${r.active} 完成:${r.done} 不合格:${r.rejected} 累计:${r.total} | 当前任务: ${cur} | 活跃:${(r.lastActiveAt || '').slice(5, 16)}`); } // 负载建议 const activeAgents = names.filter(n => roster[n].status === 'active').length; const idleAgents = names.filter(n => roster[n].status === 'active' && roster[n].active === 0 && roster[n].reviewing.length === 0); console.log('\n=== 负载分析 ==='); if (activeAgents === 0) { console.log('⚠️ 人手不足:0 名在职 Agent,待处理任务池 ' + pending + ' 个 → 建议立即扩招'); } else if (pending >= activeAgents * 1.5) { console.log(`⚠️ 人手不足:${activeAgents} 名 Agent vs ${pending} 个待处理任务(阈值${Math.floor(activeAgents * 1.5)}) → 建议扩招 ${Math.max(1, Math.ceil(pending / 2) - activeAgents)} 名`); } else if (idleAgents.length >= 2 || (idleAgents.length >= 1 && pending <= Math.floor(activeAgents * 0.5))) { const idleName = idleAgents.map(a => a + '(闲置)').join(', '); console.log(`💤 活不够:${idleAgents.length} 名 Agent 闲置,待处理任务仅 ${pending} 个`); console.log(` 建议裁员/转待命: ${idleName}`); console.log(` 执行: node taskboard.js standby "" 转待命 | node taskboard.js layoff "" --note "<原因>" 裁员`); } else if (idleAgents.length === 1 && pending > activeAgents * 0.5) { console.log(`🔶 观察期:${idleAgents[0]} 暂闲置,待处理任务 ${pending} 个尚可消化,先不裁员`); } else { console.log(`✅ 负载均衡:${activeAgents} 名 Agent 对 ${pending} 个待处理任务,全员饱和,维持现状`); } } function cmdHire(args) { const db = load(); const name = args._[0]; if (!name) { console.error('[错误] 用法: hire "" --role "<岗位>"'); process.exit(1); } const a = registerAgent(db, name); a.role = args.role || a.role || '未定岗'; a.status = 'active'; a.note = args.note || ''; save(db); console.log(`[已招聘] ${name} (${a.role}) 入职时间: ${a.joinedAt}`); } function cmdLayoff(args) { const db = load(); const name = args._[0]; if (!name) { console.error('[错误] 用法: layoff "" [--note "<原因>"]'); process.exit(1); } if (!db.agents[name]) { console.error(`[错误] Agent ${name} 不在册`); process.exit(1); } const roster = agentLoad(db)[name]; if (roster.active > 0) { console.error(`[拒绝裁员] ${name} 仍有 ${roster.active} 个在办/待验收任务 (${roster.current.concat(roster.reviewing).join(',')}),先移交或完成任务`); process.exit(1); } db.agents[name].status = 'laid_off'; db.agents[name].note = args.note || '人力过剩裁员'; db.agents[name].laidOffAt = now(); save(db); console.log(`[已裁员] ${name} 状态→laid_off | 原因: ${args.note || '人力过剩'} | 累计完成 ${roster.done} 个任务`); } function cmdStandby(args) { const db = load(); const name = args._[0]; if (!name) { console.error('[错误] 用法: standby ""'); process.exit(1); } if (!db.agents[name]) { console.error(`[错误] Agent ${name} 不在册`); process.exit(1); } const roster = agentLoad(db)[name]; if (roster.active > 0) { console.error(`[拒绝] ${name} 仍有在办任务,不能转待命`); process.exit(1); } db.agents[name].status = 'standby'; save(db); console.log(`[已转待命] ${name} 状态→standby(活多了随时召回)`); } function cmdRehireAll(args) { const db = load(); const names = Object.keys(db.agents); if (!names.length) { console.error('[错误] 无在册 Agent'); process.exit(1); } let count = 0; for (const n of names) { const before = db.agents[n].status; db.agents[n].status = 'active'; db.agents[n].lastActiveAt = now(); db.agents[n].rehiredAt = now(); db.agents[n].note = args.note || '全员重新入职'; if (before !== 'active') { console.log(`[重新入职] ${n}: ${before} → active`); count++; } else { console.log(`[在职确认] ${n}: active(无需变更)`); } } save(db); console.log(`\n[完成] ${names.length} 名 Agent 全部在职(${count} 名状态变更)`); } function genId(db, type) { db.seq += 1; return (type === 'bug' ? 'BUG-' : 'T-') + String(db.seq).padStart(3, '0'); } function findTask(db, id) { const t = db.tasks.find(x => x.id.toUpperCase() === String(id).toUpperCase()); if (!t) { console.error(`[错误] 任务 ${id} 不存在`); process.exit(1); } return t; } function fmt(t) { const claimed = t.claimedAt ? ` | 认领:${t.agent || '?'}@${t.claimedAt.slice(5, 16)}` : ''; const note = t.note ? ` | 备注:${t.note}` : ''; return `[${t.id}] (${STATUS_LABEL[t.status]} | ${PRIORITY_LABEL[t.priority]}) ${t.title}${claimed}${note}`; } /* ---------- 命令实现 ---------- */ function cmdNew(args) { const db = load(); const title = args._[0]; if (!title) { console.error('[错误] 需要标题: new "<标题>"'); process.exit(1); } // 任务粒度规范:禁止拼接式任务(+、、和中文顿号等),必须单一目标 if (!args.force) { const bad = title.match(/[++、&]/); if (bad) { console.error(`[粒度规范] 任务标题含「${bad[0]}」拼接符,禁止一个任务包含多个目标。`); console.error(` 请拆分为独立任务分别发布(如确需合并请加 --force)`); process.exit(1); } } const id = genId(db, 'task'); const task = { id, type: 'task', title, desc: args.desc || '', priority: args.priority || PRIORITY.MEDIUM, status: STATUS.PENDING, assignee: args.assignee || null, // 期望角色 agent: null, // 认领的 Agent createdAt: now(), claimedAt: null, submittedAt: null, testedAt: null, note: null, // 提交说明 testNote: null, // 测试备注 parentId: null, // bug 关联的原始任务 linkedBugs: [], // 任务关联的 bug 列表 closedAt: null, }; db.tasks.push(task); save(db); console.log(`[已发布] ${fmt(task)}`); console.log(` 创建时间: ${task.createdAt}`); return task; } function cmdClaim(args) { const db = load(); const t = findTask(db, args._[0]); const agent = args.agent || args._[1]; if (!agent) { console.error('[错误] 需要 --agent ""'); process.exit(1); } if (t.status !== STATUS.PENDING) { console.error(`[错误] 任务 ${t.id} 当前状态为「${STATUS_LABEL[t.status]}」,只能认领「待处理」任务`); process.exit(1); } t.status = STATUS.IN_PROGRESS; t.agent = agent; t.claimedAt = now(); registerAgent(db, agent); save(db); console.log(`[已认领] ${fmt(t)}`); console.log(` 认领时间: ${t.claimedAt}`); } function cmdSubmit(args) { const db = load(); const t = findTask(db, args._[0]); if (t.status !== STATUS.IN_PROGRESS) { console.error(`[错误] 任务 ${t.id} 当前状态为「${STATUS_LABEL[t.status]}」,只有「开发中」任务可提交验收`); process.exit(1); } t.status = STATUS.REVIEW; t.submittedAt = now(); if (args.note) t.note = args.note; save(db); console.log(`[已提交验收] ${fmt(t)}`); console.log(` 提交时间: ${t.submittedAt}`); } function cmdTest(args) { const db = load(); const t = findTask(db, args._[0]); if (t.status !== STATUS.REVIEW) { console.error(`[错误] 任务 ${t.id} 当前状态为「${STATUS_LABEL[t.status]}」,只有「待验收」任务可测试`); process.exit(1); } const pass = !!args.pass; const fail = !!args.fail; if (pass === fail) { console.error('[错误] 必须指定 --pass 或 --fail'); process.exit(1); } t.status = pass ? STATUS.APPROVED : STATUS.REJECTED; t.testedAt = now(); t.testNote = args.note || (pass ? '测试通过' : '测试不合格'); if (pass) { // 验收通过:如果有关联的未关闭 bug,提示先关闭 const openBugs = (t.linkedBugs || []).filter(id => { const b = db.tasks.find(x => x.id === id); return b && b.status !== STATUS.CLOSED && b.status !== STATUS.APPROVED; }); if (openBugs.length) { console.log(`[警告] 任务 ${t.id} 仍有未关闭的关联 Bug: ${openBugs.join(', ')}`); } // 规则:bug 修复验收通过 → 立即联动父任务重新进入验收(无需等 close) if (t.type === 'bug' && t.parentId) { const parent = db.tasks.find(x => x.id === t.parentId); if (parent && parent.status === STATUS.REJECTED) { parent.status = STATUS.REVIEW; parent.testedAt = null; parent.testNote = `Bug ${t.id} 已修复并验收通过,重新进入验收`; console.log(`[联动] 原始任务 ${parent.id} 已从「不合格」重置为「待验收」`); } } save(db); console.log(`[测试通过] ${fmt(t)}`); console.log(` 验收时间: ${t.testedAt} | 备注: ${t.testNote}`); console.log(` 提示: 验收通过任务保留在「验收通过」通道,如需归档再执行 close`); } else { // 不合格 → 自动生成 bug 任务并关联 const bugPriority = args.priority || (t.priority === PRIORITY.LOW ? PRIORITY.MEDIUM : t.priority); const bugId = genId(db, 'bug'); const bug = { id: bugId, type: 'bug', title: `[BUG] ${t.title} 验收不合格`, desc: `原始任务: ${t.id}「${t.title}」\n不合格原因: ${t.testNote}\n建议修复人: ${t.agent || '未指定'}`, priority: bugPriority, status: STATUS.PENDING, // 必须进入待处理通道,等待 Agent 主动认领 assignee: null, // 不预设认领人,避免误以为已分配 agent: null, // 未被认领 createdAt: now(), claimedAt: null, submittedAt: null, testedAt: null, note: null, testNote: null, parentId: t.id, // 关联不合格的任务 linkedBugs: [], closedAt: null, }; db.tasks.push(bug); t.linkedBugs = t.linkedBugs || []; t.linkedBugs.push(bugId); save(db); console.log(`[测试不合格] ${fmt(t)}`); console.log(` 不合格备注: ${t.testNote}`); console.log(` 测试时间: ${t.testedAt}`); console.log(`[自动生成 Bug → 待处理通道] ${fmt(bug)}`); console.log(` 关联任务: ${t.id} | 优先级: ${PRIORITY_LABEL[bugPriority]}`); console.log(` 状态: 待处理(未认领,等待 Agent 主动领取,建议修复人: ${t.agent || '未指定'})`); console.log(` 创建时间: ${bug.createdAt}`); } } function cmdClose(args) { const db = load(); const t = findTask(db, args._[0]); if (![STATUS.REJECTED, STATUS.APPROVED, STATUS.CLOSED].includes(t.status)) { console.error(`[错误] 只有「不合格/验收通过」任务可关闭,当前: ${STATUS_LABEL[t.status]}`); process.exit(1); } t.status = STATUS.CLOSED; t.closedAt = now(); if (args.note) t.testNote = (t.testNote ? t.testNote + ' | ' : '') + args.note; // 注:bug→父任务联动已移至 test --pass 时执行,close 仅归档 save(db); console.log(`[已关闭] ${fmt(t)}`); console.log(` 提示: close 仅用于归档;验收通过的任务应保留在「验收通过」通道`); } function cmdCancel(args) { const db = load(); const t = findTask(db, args._[0]); if (t.status === STATUS.CLOSED) { console.error(`[错误] 任务 ${t.id} 已关闭`); process.exit(1); } t.status = STATUS.CLOSED; t.closedAt = now(); t.note = args.note || '任务被取消/拆分'; save(db); console.log(`[已取消] ${fmt(t)}`); console.log(` 取消原因: ${t.note}`); } function cmdReopen(args) { const db = load(); const t = findTask(db, args._[0]); if (t.status !== STATUS.CLOSED) { console.error(`[错误] 任务 ${t.id} 未关闭,无需恢复`); process.exit(1); } // 依据验收记录决定恢复到哪一列 if (t.testedAt && (t.testNote || '').includes('通过')) { t.status = STATUS.APPROVED; console.log(`[已恢复] ${t.id} → 「验收通过」(依据验收记录)`); } else if (t.claimedAt && !t.submittedAt) { t.status = STATUS.IN_PROGRESS; console.log(`[已恢复] ${t.id} → 「开发中」`); } else if (t.note && t.note.includes('取消')) { console.log(`[跳过] ${t.id} 是取消/拆分记录,保持关闭`); } else { t.status = STATUS.PENDING; console.log(`[已恢复] ${t.id} → 「待处理」`); } t.closedAt = null; save(db); console.log(`[已恢复] ${fmt(t)}`); } function cmdList(args) { const db = load(); let tasks = db.tasks; if (args.status) tasks = tasks.filter(t => t.status === args.status); if (args.type) tasks = tasks.filter(t => t.type === args.type); const sortKey = t => `${PRIORITY_RANK[t.priority]}_${t.createdAt}`; const grouped = {}; for (const t of tasks) { const st = args.status || t.status; (grouped[st] = grouped[st] || []).push(t); } for (const [st, list] of Object.entries(grouped)) { list.sort((a, b) => sortKey(a).localeCompare(sortKey(b))); console.log(`\n=== ${STATUS_LABEL[st]} (${list.length}) ===`); list.forEach(t => console.log(' ' + fmt(t))); } if (!Object.keys(grouped).length) console.log('(无任务)'); } function cmdBoard() { const db = load(); const { md, html } = buildBoard(db); fs.writeFileSync(BOARD_MD, md, 'utf8'); fs.writeFileSync(BOARD_HTML, html, 'utf8'); console.log(`[看板已生成] ${BOARD_MD}`); console.log(`[看板已生成] ${BOARD_HTML}`); console.log(`任务总数: ${db.tasks.length} | 未关闭 Bug: ${db.tasks.filter(t => t.type === 'bug' && t.status !== STATUS.CLOSED && t.status !== STATUS.APPROVED).length}`); } /* ---------- 看板渲染(MD + HTML 复用) ---------- */ const RENDER_JS = String.raw` const LABEL={pending:'待处理',in_progress:'开发中',review:'待验收',approved:'验收通过',rejected:'不合格',closed:'已关闭'}; const PRIO={high:'高',medium:'中',low:'低'}; const ORDER=['pending','in_progress','review','approved','rejected','closed']; const PAGE_SIZE=5; const esc=s=>String(s==null?'':s).replace(/&/g,'&').replace(//g,'>'); let state={page:{}}; function cardHTML(t,db){ db=db||window.__DB__; let bugsHtml=''; if(t.linkedBugs&&t.linkedBugs.length){ const bs=t.linkedBugs.map(id=>db.tasks.find(x=>x.id===id)).filter(Boolean); bugsHtml='
' +bs.map(b=>{ const stL=LABEL[b.status]||b.status; const stC=b.status==='approved'||b.status==='closed'?'ok':(b.status==='rejected'?'bad':'wip'); return '
' +'🐛 '+esc(b.id)+'' +''+stL+'' +(b.agent?''+esc(b.agent)+'':'') +(b.testedAt?'验收 '+esc(b.testedAt.slice(5,16))+'':'') +(b.testNote?'
'+esc(b.testNote)+'
':'') +'
'; }).join('') +'
'; } return '
' +'
'+esc(t.id)+''+(t.type==='bug'?'BUG':'')+''+PRIO[t.priority]+'' +(bugsHtml?'🐛 '+t.linkedBugs.length+'':'') +'
' +'
'+esc(t.title)+'
' +(t.desc?'
'+esc(t.desc.split('\n')[0])+'
':'') +'
👤 '+(t.agent?esc(t.agent):(t.status==='pending'?'⏳ 待认领':esc(t.assignee||'未分配')))+'
' +'
🕐 '+esc((t.createdAt||'').slice(0,19).replace('T',' '))+'
' +(t.claimedAt?'
✋ 认领 '+esc(t.claimedAt.slice(0,19).replace('T',' '))+'
':'') +(t.submittedAt?'
📤 提交 '+esc(t.submittedAt.slice(0,19).replace('T',' '))+'
':'') +(t.testedAt?'
🧪 测试 '+esc(t.testedAt.slice(0,19).replace('T',' '))+'
':'') +(t.parentId?'
🔗 关联 '+esc(t.parentId)+'
':'') +(t.testNote?'
'+esc(t.testNote)+'
':'') +(t.parentId?'
🔗 关联需求 '+esc(t.parentId)+'
':'') +bugsHtml +'
'; } document.addEventListener('click',e=>{ const card=e.target.closest('.card.has-bugs'); if(!card)return; card.classList.toggle('expanded'); }); function renderBoard(db, via){ const agents=db.agents||{}; const act=Object.keys(agents).filter(n=>agents[n].status==='active').length; const bugs=db.tasks.filter(t=>t.type==='bug'&&t.status!=='closed'&&t.status!=='approved').length; document.querySelector('.live i').style.background=bugs?'#e04f4f':'#3daf80'; document.querySelector('.live').innerHTML=''+(via==='live'?'实时 · 2s 刷新':'每 5 秒自动刷新')+' · 未关闭 Bug '+bugs; document.querySelector('h2').innerHTML='更新 '+new Date().toLocaleTimeString('zh-CN',{timeZone:'Asia/Shanghai'})+' · 任务总数 '+db.tasks.length+' · 未关闭 Bug '+bugs+' · 在职 Agent '+act+''; // 监督状态条(仅 serve 实时模式拉取 /api/health) const healthEl = document.getElementById('healthBar'); if(healthEl && via==='live'){ fetch('/api/health').then(r=>r.json()).then(h=>{ const p = (h.problems||[]).length; healthEl.innerHTML = p>0 ? '🛡️ 监督: 发现 '+p+' 个问题'+h.problems.map(x=>x.task+': '+x.detail.slice(0,30)).join(' | ')+'' : '🛡️ 监督: 全部 Agent 正常(巡检 '+(h.last?h.last.time:'-')+')'; }).catch(()=>{}); } const roster={}; for(const n of Object.keys(agents)){roster[n]={status:agents[n].status,role:agents[n].role,lastActiveAt:agents[n].lastActiveAt,current:[],reviewing:[],active:0,done:0,total:0};} for(const t of db.tasks){if(t.agent&&roster[t.agent]){const r=roster[t.agent];r.total++;if(t.status==='in_progress'){r.active++;r.current.push(t.id);}if(t.status==='review'){r.active++;r.reviewing.push(t.id);}if(t.status==='approved'||t.status==='closed')r.done++;}} document.querySelector('.agents').innerHTML='

🤖 Agent 火力面板(在职 '+act+')

' +Object.keys(roster).sort((a,b)=>roster[b].active-roster[a].active).map(n=>{ const r=roster[n];const st=r.status==='active'?'🔥':r.status==='standby'?'💤':'⚰️'; return '
'+st+''+esc(n)+''+esc(r.role||'未定岗')+'在办 '+r.active+' · 完成 '+r.done+' · 累计 '+r.total+''+esc(r.current.concat(r.reviewing).join(',')||'-')+''+esc((r.lastActiveAt||'').slice(5,16))+'
'; }).join(''); let board=''; // 移动端通道导航条 const navHtml = ORDER.map(st=>{ const n=db.tasks.filter(t=>t.status===st).length; return ''; }).join(''); document.querySelector('.colNav').innerHTML = navHtml; for(const st of ORDER){ const list=db.tasks.filter(t=>{ if(t.status!==st)return false; if(t.type==='bug'&&t.parentId){ const parent=db.tasks.find(x=>x.id===t.parentId); if(parent)return false; } return true; }).sort((a,b)=>(PRIO[a.priority]>PRIO[b.priority]?1:-1)||(a.createdAt>b.createdAt?1:-1)); const totalPages=Math.max(1,Math.ceil(list.length/PAGE_SIZE)); if(!state.page[st]||state.page[st]>=totalPages)state.page[st]=0; const page=state.page[st]; const slice=list.slice(page*PAGE_SIZE,(page+1)*PAGE_SIZE); board+='

'+LABEL[st]+' '+list.length+'

' +slice.map(t=>cardHTML(t,db)).join('') +'
' +'' +''+(page+1)+' / '+totalPages+'' +'' +'
'; } document.querySelector('.board').innerHTML=board; } document.addEventListener('click',e=>{ const nav=e.target.closest('.colNav button'); if(nav){ const col=document.getElementById('col-'+nav.dataset.nav); if(col) col.scrollIntoView({behavior:'smooth',inline:'start',block:'nearest'}); return; } const b=e.target.closest('.pgBtn'); if(!b)return; const st=b.dataset.st;const dir=Number(b.dataset.dir); const list=window.__DB__.tasks.filter(t=>t.status===st); const totalPages=Math.max(1,Math.ceil(list.length/PAGE_SIZE)); state.page[st]=Math.min(Math.max(0,(state.page[st]||0)+dir),totalPages-1); renderBoard(window.__DB__,false); }); `; function buildBoard(db) { const order = [STATUS.PENDING, STATUS.IN_PROGRESS, STATUS.REVIEW, STATUS.APPROVED, STATUS.REJECTED, STATUS.CLOSED]; const groups = order.map(st => ({ st, list: db.tasks.filter(t => t.status === st) })); for (const g of groups) { g.list.sort((a, b) => PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority] || a.createdAt.localeCompare(b.createdAt)); } const counts = {}; for (const t of db.tasks) counts[t.status] = (counts[t.status] || 0) + 1; const total = db.tasks.length; const bugs = db.tasks.filter(t => t.type === 'bug' && t.status !== STATUS.CLOSED && t.status !== STATUS.APPROVED); /* --- Markdown --- */ const rosterMD = agentLoad(db); let md = `# PERLER LAB 任务看板\n\n`; md += `> 生成时间: ${now()} · 任务总数: **${total}** · 未关闭 Bug: **${bugs.length}**\n\n`; md += `## 🤖 Agent 火力面板\n\n`; md += `| Agent | 状态 | 在办 | 完成 | 累计 | 当前任务 | 活跃时间 |\n|---|---|---|---|---|---|---|\n`; for (const n of Object.keys(rosterMD).sort((a, b) => rosterMD[b].active - rosterMD[a].active)) { const r = rosterMD[n]; const st = r.status === 'active' ? '🔥在职' : r.status === 'standby' ? '💤待命' : '⚰️裁员'; md += `| ${n} | ${st} | ${r.active} | ${r.done} | ${r.total} | ${r.current.concat(r.reviewing).join(',') || '-'} | ${(r.lastActiveAt || '').slice(5, 16)} |\n`; } md += `\n---\n\n`; md += `| 状态 | 数量 |\n|---|---|\n`; for (const st of order) md += `| ${STATUS_LABEL[st]} | ${counts[st] || 0} |\n`; md += `\n---\n\n`; for (const g of groups) { md += `## 📋 ${STATUS_LABEL[g.st]} (${g.list.length})\n\n`; if (!g.list.length) { md += `_空_\n\n`; continue; } md += `| ID | 优先级 | 标题 | 实施 | 创建时间 | 认领/提交/测试 | 备注 |\n|---|---|---|---|---|---|---|\n`; for (const t of g.list) { const timeline = [t.claimedAt ? `认领 ${t.claimedAt.slice(5, 16)}` : '', t.submittedAt ? `提交 ${t.submittedAt.slice(5, 16)}` : '', t.testedAt ? `测试 ${t.testedAt.slice(5, 16)}` : ''].filter(Boolean).join('
'); const note = (t.testNote || t.note || '') || (t.type === 'bug' && t.parentId ? `关联 ${t.parentId}` : ''); const bugsTag = t.linkedBugs && t.linkedBugs.length ? ` 🔗${t.linkedBugs.join(',')}` : ''; md += `| **${t.id}**${t.type === 'bug' ? ' 🐛' : ''} | ${PRIORITY_LABEL[t.priority]} | ${t.title}${bugsTag} | ${t.agent || t.assignee || '-'} | ${t.createdAt.slice(5, 16)} | ${timeline || '-'} | ${String(note).slice(0, 60)} |\n`; } md += `\n`; } /* --- HTML(内嵌 JS 自动刷新 + 100vh 无滚动 + 分页版) --- */ const esc = s => String(s || '').replace(/&/g, '&').replace(//g, '>'); // Agent 火力面板数据 const roster = agentLoad(db); const rosterHtml = Object.keys(roster) .sort((a, b) => roster[b].active - roster[a].active) .map(n => { const r = roster[n]; const stIcon = r.status === 'active' ? '🔥' : r.status === 'standby' ? '💤' : '⚰️'; const cur = r.current.concat(r.reviewing).join(',') || '-'; return `
${stIcon}${esc(n)}${esc(r.role || '未定岗')}在办 ${r.active} · 完成 ${r.done} · 累计 ${r.total}${esc(cur)}${(r.lastActiveAt || '').slice(5, 16)}
`; }).join(''); const activeCount = Object.values(roster).filter(r => r.status === 'active').length; const boardData = JSON.stringify({ tasks: db.tasks, agents: db.agents }).replace(/PERLER LAB 任务看板 自动刷新

PERLER LAB 任务看板

生成时间 ${esc(now())} · 任务总数 ${total} · 未关闭 Bug ${bugs.length} · 在职 Agent ${activeCount}

${rosterHtml}
`; return { md, html }; } /* ---------- watch:监控 tasks.json,变更自动重建看板 ---------- */ function cmdWatch(args) { const interval = Number(args.interval) || 500; const rebuild = (why) => { try { const db = load(); const { md, html } = buildBoard(db); fs.writeFileSync(BOARD_MD, md, 'utf8'); fs.writeFileSync(BOARD_HTML, html, 'utf8'); const open = db.tasks.filter(t => t.status !== STATUS.CLOSED && t.status !== STATUS.APPROVED).length; console.log(`[${now().slice(5, 19)}] ${why} → 看板已重建 (总 ${db.tasks.length} 任务, 未完成 ${open})`); } catch (e) { console.error(`[watch] 重建失败: ${e.message}`); } }; let lastMtime = 0; try { lastMtime = fs.statSync(DATA_FILE).mtimeMs; } catch (e) { /* 首次 */ } rebuild('启动监视'); console.log(`[watch] 正在监视 ${DATA_FILE} (间隔 ${interval}ms),Ctrl+C 停止`); fs.watchFile(DATA_FILE, { interval }, (cur, prev) => { if (cur.mtimeMs !== prev.mtimeMs && cur.mtimeMs !== lastMtime) { lastMtime = cur.mtimeMs; rebuild(`tasks.json 已变更`); } }); } /* ---------- serve:本地实时看板服务器(浏览器自动刷新) ---------- */ function cmdServe(args) { const http = require('http'); const port = Number(args.port) || 8787; const { md, html } = buildBoard(load()); const liveHtml = html.replace('', '').replace( '', `` ); const server = http.createServer((req, res) => { if (req.url === '/api/tasks') { res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(load())); return; } if (req.url === '/api/health') { // 监督状态:读巡检历史 + 实时跑一次 const { execSync } = require('child_process'); let last = null; try { const hf = path.join(__dirname, 'health-history.json'); if (fs.existsSync(hf)) { const h = JSON.parse(fs.readFileSync(hf, 'utf8')); if (h.length) last = h[0]; } } catch (e) { /* 忽略 */ } res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify({ supervisor: '主代理', last, problems: last ? last.problems : [] })); return; } res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(liveHtml); }); server.listen(port, '0.0.0.0', () => { // 获取本机局域网 IP(供手机/其他设备访问) let lanIp = 'localhost'; try { const nets = require('os').networkInterfaces(); for (const name of Object.keys(nets)) { for (const net of nets[name] || []) { if (net.family === 'IPv4' && !net.internal) { lanIp = net.address; break; } } if (lanIp !== 'localhost') break; } } catch (e) { /* 忽略 */ } console.log(`[serve] 实时看板已启动 (监听 0.0.0.0:${port})`); console.log(`[serve] 本机访问: http://localhost:${port}`); console.log(`[serve] 局域网访问: http://${lanIp}:${port} (手机需同一 WiFi)`); console.log(`[serve] 浏览器每 2 秒自动刷新任务数据,Ctrl+C 停止`); }); fs.watchFile(DATA_FILE, { interval: 500 }, () => { // 数据变更无需重启服务,前端轮询即可 }); } function cmdStats() { const db = load(); const count = {}; for (const t of db.tasks) count[t.status] = (count[t.status] || 0) + 1; console.log('=== 任务统计 ==='); for (const st of Object.values(STATUS)) { console.log(` ${STATUS_LABEL[st]}: ${count[st] || 0}`); } console.log(` 合计: ${db.tasks.length} (任务 ${db.tasks.filter(t => t.type === 'task').length} / Bug ${db.tasks.filter(t => t.type === 'bug').length})`); } /* ---------- 参数解析 ---------- */ function parseArgs(argv) { const args = { _: [] }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a.startsWith('--')) { const key = a.slice(2); const next = argv[i + 1]; if (next && !next.startsWith('--')) { args[key] = next; i++; } else { args[key] = true; } } else { args._.push(a); } } return args; } /* ---------- 入口 ---------- */ const argv = process.argv.slice(2); const cmd = argv[0]; const args = parseArgs(argv.slice(1)); const CMDS = { new: cmdNew, claim: cmdClaim, submit: cmdSubmit, test: cmdTest, close: cmdClose, cancel: cmdCancel, reopen: cmdReopen, list: cmdList, board: cmdBoard, stats: cmdStats, watch: cmdWatch, serve: cmdServe, agents: cmdAgents, hire: cmdHire, layoff: cmdLayoff, standby: cmdStandby, rehire: cmdRehireAll, }; if (!CMDS[cmd]) { console.log(`用法: node taskboard.js <${Object.keys(CMDS).join('|')}> [参数]`); process.exit(1); } CMDS[cmd](args);