- 前端: React+Vite 首页/AI专区, 算法库(MARD色板/量化/背景去除), API对接 - 后端: Express+SQLite, 兑换码/订单/支付/chibi生成, 风控+云端同步 - CI/CD: GitHub Actions + Docker + nginx 配置 - 文档: PRD/DESIGN/LAUNCH/ROADMAP/E2E/竞品对照等 15 份 - 工程: 任务看板(taskboard) + 健康巡检(agent-health) + Git流程(gitflow)
879 lines
42 KiB
JavaScript
879 lines
42 KiB
JavaScript
#!/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 <id> --agent "<Agent名>"
|
||
* node taskboard.js submit <id> --note "<提交说明>"
|
||
* node taskboard.js test <id> --pass --note "<验收备注>"
|
||
* node taskboard.js test <id> --fail --note "<不合格原因>" [--priority high|medium|low]
|
||
* node taskboard.js close <id> --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 "<Agent名>" 转待命 | node taskboard.js layoff "<Agent名>" --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 "<Agent名>" --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 "<Agent名>" [--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 "<Agent名>"'); 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 "<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,'<').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='<div class="card-bugs">'
|
||
+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 '<div class="bug-item '+stC+'">'
|
||
+'<span class="bug-id">🐛 '+esc(b.id)+'</span>'
|
||
+'<span class="bug-state">'+stL+'</span>'
|
||
+(b.agent?'<span class="bug-agent">'+esc(b.agent)+'</span>':'')
|
||
+(b.testedAt?'<span class="bug-time">验收 '+esc(b.testedAt.slice(5,16))+'</span>':'')
|
||
+(b.testNote?'<div class="bug-note">'+esc(b.testNote)+'</div>':'')
|
||
+'</div>';
|
||
}).join('')
|
||
+'</div>';
|
||
}
|
||
return '<div class="card '+t.status+(bugsHtml?' has-bugs':'')+'" data-id="'+esc(t.id)+'">'
|
||
+'<div class="card-head"><b>'+esc(t.id)+'</b>'+(t.type==='bug'?'<span class="tag bug-tag">BUG</span>':'')+'<span class="tag prio-'+t.priority+'">'+PRIO[t.priority]+'</span>'
|
||
+(bugsHtml?'<span class="tag bug-count">🐛 '+t.linkedBugs.length+'</span>':'')
|
||
+'</div>'
|
||
+'<div class="card-title">'+esc(t.title)+'</div>'
|
||
+(t.desc?'<div class="card-desc">'+esc(t.desc.split('\n')[0])+'</div>':'')
|
||
+'<div class="card-meta">👤 '+(t.agent?esc(t.agent):(t.status==='pending'?'<span class="unclaimed">⏳ 待认领</span>':esc(t.assignee||'未分配')))+'</div>'
|
||
+'<div class="card-meta">🕐 '+esc((t.createdAt||'').slice(0,19).replace('T',' '))+'</div>'
|
||
+(t.claimedAt?'<div class="card-meta">✋ 认领 '+esc(t.claimedAt.slice(0,19).replace('T',' '))+'</div>':'')
|
||
+(t.submittedAt?'<div class="card-meta">📤 提交 '+esc(t.submittedAt.slice(0,19).replace('T',' '))+'</div>':'')
|
||
+(t.testedAt?'<div class="card-meta">🧪 测试 '+esc(t.testedAt.slice(0,19).replace('T',' '))+'</div>':'')
|
||
+(t.parentId?'<div class="card-meta">🔗 关联 '+esc(t.parentId)+'</div>':'')
|
||
+(t.testNote?'<div class="card-note '+t.status+'">'+esc(t.testNote)+'</div>':'')
|
||
+(t.parentId?'<div class="card-meta">🔗 关联需求 '+esc(t.parentId)+'</div>':'')
|
||
+bugsHtml
|
||
+'</div>';
|
||
}
|
||
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='<i></i>'+(via==='live'?'实时 · 2s 刷新':'每 5 秒自动刷新')+' · 未关闭 Bug '+bugs;
|
||
document.querySelector('h2').innerHTML='更新 '+new Date().toLocaleTimeString('zh-CN',{timeZone:'Asia/Shanghai'})+' · 任务总数 <b>'+db.tasks.length+'</b> · 未关闭 Bug <b>'+bugs+'</b> · 在职 Agent <b>'+act+'</b>';
|
||
// 监督状态条(仅 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
|
||
? '<span class="h-bad">🛡️ 监督: 发现 '+p+' 个问题</span><span class="h-detail">'+h.problems.map(x=>x.task+': '+x.detail.slice(0,30)).join(' | ')+'</span>'
|
||
: '<span class="h-good">🛡️ 监督: 全部 Agent 正常(巡检 '+(h.last?h.last.time:'-')+')</span>';
|
||
}).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='<h3>🤖 Agent 火力面板(在职 <b>'+act+'</b>)</h3>'
|
||
+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 '<div class="agent '+r.status+'"><span class="a-status">'+st+'</span><b>'+esc(n)+'</b><span class="a-role">'+esc(r.role||'未定岗')+'</span><span class="a-load">在办 <b>'+r.active+'</b> · 完成 '+r.done+' · 累计 '+r.total+'</span><span class="a-cur">'+esc(r.current.concat(r.reviewing).join(',')||'-')+'</span><span class="a-time">'+esc((r.lastActiveAt||'').slice(5,16))+'</span></div>';
|
||
}).join('');
|
||
let board='';
|
||
// 移动端通道导航条
|
||
const navHtml = ORDER.map(st=>{
|
||
const n=db.tasks.filter(t=>t.status===st).length;
|
||
return '<button data-nav="'+st+'">'+LABEL[st]+' <span class="cnt">'+n+'</span></button>';
|
||
}).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+='<div class="col" id="col-'+st+'"><h3>'+LABEL[st]+' <span class="cnt">'+list.length+'</span></h3><div class="colBody">'
|
||
+slice.map(t=>cardHTML(t,db)).join('')
|
||
+'</div><div class="pager">'
|
||
+'<button class="pgBtn" data-st="'+st+'" data-dir="-1" '+(page===0?'disabled':'')+'>‹ 上一页</button>'
|
||
+'<span class="pgInfo">'+(page+1)+' / '+totalPages+'</span>'
|
||
+'<button class="pgBtn" data-st="'+st+'" data-dir="1" '+(page>=totalPages-1?'disabled':'')+'>下一页 ›</button>'
|
||
+'</div></div>';
|
||
}
|
||
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('<br>');
|
||
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, '<').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 `<div class="agent ${r.status}"><span class="a-status">${stIcon}</span><b>${esc(n)}</b><span class="a-role">${esc(r.role || '未定岗')}</span><span class="a-load">在办 <b>${r.active}</b> · 完成 ${r.done} · 累计 ${r.total}</span><span class="a-cur">${esc(cur)}</span><span class="a-time">${(r.lastActiveAt || '').slice(5, 16)}</span></div>`;
|
||
}).join('');
|
||
const activeCount = Object.values(roster).filter(r => r.status === 'active').length;
|
||
const boardData = JSON.stringify({ tasks: db.tasks, agents: db.agents }).replace(/</g, '\\u003c');
|
||
const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>PERLER LAB 任务看板</title>
|
||
<meta http-equiv="refresh" content="5">
|
||
<style>
|
||
*{box-sizing:border-box}
|
||
html,body{height:100%;overflow:hidden}
|
||
body{font-family:system-ui,'Segoe UI',sans-serif;background:#f4f3ef;margin:0;padding:16px 24px;color:#171713;display:flex;flex-direction:column}
|
||
h1{font-size:19px;margin:0 0 2px}h2{font-size:12px;font-weight:400;color:#66645d;margin:0 0 10px;flex-shrink:0}
|
||
.agents{background:#fff;border:1px solid #e6e3d9;border-radius:12px;padding:10px 14px;margin-bottom:10px;flex-shrink:0;max-height:26%;overflow-y:auto}
|
||
.agents h3{font-size:13px;margin:0 0 6px}
|
||
.agent{display:flex;align-items:center;gap:10px;padding:4px 8px;border-radius:8px;font-size:12px;border-bottom:1px solid #f2efe7}
|
||
.agent:last-child{border-bottom:none}
|
||
.agent.standby{opacity:.5}.agent.laid_off{opacity:.35;text-decoration:line-through}
|
||
.a-status{width:18px}.a-role{color:#8a877d;font-size:11px;background:#f0ede4;border-radius:10px;padding:1px 8px}
|
||
.a-load{color:#55534e}.a-cur{color:#3677d2;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}.a-time{color:#b0aca0;font-size:11px;margin-left:auto}
|
||
.board{display:grid;grid-template-columns:repeat(6,1fr);gap:12px;flex:1;min-height:0}
|
||
.col{background:#fff;border-radius:12px;padding:10px;border:1px solid #e6e3d9;display:flex;flex-direction:column;min-height:0;min-width:0}
|
||
.col h3{font-size:13px;margin:0 0 8px;display:flex;justify-content:space-between;align-items:center;flex-shrink:0}
|
||
.cnt{background:#f0ede4;border-radius:20px;padding:2px 8px;font-size:12px}
|
||
.colBody{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:8px}
|
||
.pager{display:flex;align-items:center;justify-content:space-between;margin-top:8px;flex-shrink:0}
|
||
.pgBtn{border:1px solid #e0dccd;background:#faf9f4;border-radius:8px;padding:3px 10px;font-size:11px;cursor:pointer;color:#55534e}
|
||
.pgBtn:hover:not(:disabled){background:#f0ede4}
|
||
.pgBtn:disabled{opacity:.4;cursor:default}
|
||
.pgInfo{font-size:11px;color:#8a877d}
|
||
.card{background:#fff;border:1px solid #e8e5db;border-radius:10px;padding:9px 10px;box-shadow:0 1px 2px rgba(0,0,0,.04);flex-shrink:0}
|
||
.card.review{border-left:4px solid #edb045}.card.rejected{border-left:4px solid #e04f4f}
|
||
.card.approved{border-left:4px solid #3daf80}.card.in_progress{border-left:4px solid #3677d2}
|
||
.card.pending{border-left:4px solid #b6b1ba}.card.closed{opacity:.55}
|
||
.card-head{display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:4px}
|
||
.card-title{font-size:12.5px;font-weight:600;line-height:1.35;margin-bottom:4px}
|
||
.card-desc{font-size:11px;color:#77746c;margin-bottom:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.card-meta{font-size:11px;color:#8a877d;margin-top:1px}
|
||
.card-note{font-size:11px;margin-top:4px;padding:4px 8px;border-radius:6px;background:#f7f5ef}
|
||
.card-note.rejected{background:#fdeaea;color:#a83434}
|
||
.card-note.approved{background:#e9f7ef;color:#1e6b45}
|
||
/* 需求卡片展开区:关联 Bug 列表 */
|
||
.card.has-bugs{cursor:pointer}
|
||
.card.has-bugs .card-title::after{content:'▾';float:right;color:#b0aca0;font-size:11px;transition:transform .2s}
|
||
.card.has-bugs.expanded .card-title::after{transform:rotate(180deg)}
|
||
.card-bugs{display:none;margin-top:6px;border-top:1px dashed #e0dccd;padding-top:6px}
|
||
.card.expanded .card-bugs{display:block}
|
||
.bug-item{background:#faf9f4;border:1px solid #ece8dc;border-radius:8px;padding:6px 8px;margin-bottom:6px;font-size:11px}
|
||
.bug-item.ok{border-left:3px solid #3daf80}
|
||
.bug-item.bad{border-left:3px solid #e04f4f}
|
||
.bug-item.wip{border-left:3px solid #edb045}
|
||
.bug-id{font-weight:700;color:#8a4526}
|
||
.bug-state{display:inline-block;margin:0 6px;padding:0 6px;border-radius:8px;background:#f0ede4;font-size:10px}
|
||
.bug-item.ok .bug-state{background:#e9f7ef;color:#1e6b45}
|
||
.bug-item.bad .bug-state{background:#fdeaea;color:#a83434}
|
||
.bug-agent{color:#3677d2;margin-left:6px}
|
||
.bug-time{color:#b0aca0;margin-left:6px}
|
||
.bug-note{margin-top:3px;color:#66645d}
|
||
.bug-count{cursor:pointer}
|
||
.tag{cursor:default}
|
||
.tag{font-size:10px;padding:1px 6px;border-radius:10px;background:#f0ede4;color:#66645d}
|
||
.bug-tag{background:#fdeaea;color:#c03939}.prio-high{background:#fdeaea;color:#c03939}.prio-medium{background:#fdf3dc;color:#9a6a00}.prio-low{background:#e9f7ef;color:#1e6b45}
|
||
.live{position:fixed;top:12px;right:16px;font-size:11px;color:#66645d;background:#fff;border:1px solid #e6e3d9;border-radius:20px;padding:4px 10px;z-index:9}
|
||
.live i{display:inline-block;width:8px;height:8px;border-radius:50%;background:#3daf80;margin-right:6px;animation:blink 1.2s infinite}
|
||
@keyframes blink{0%,100%{opacity:1}50%{opacity:.3}}
|
||
/* ===== 移动端适配 (≤768px) ===== */
|
||
@media (max-width:768px){
|
||
body{padding:10px 10px;overflow:hidden}
|
||
h1{font-size:16px}
|
||
h2{font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:60px}
|
||
.live{top:8px;right:10px;font-size:10px;padding:3px 8px}
|
||
.agents{max-height:20%;padding:8px 10px}
|
||
.agent{flex-wrap:wrap;gap:4px 8px;padding:5px 6px;font-size:11px}
|
||
.a-role{white-space:nowrap}
|
||
.a-time{margin-left:0;width:100%;font-size:10px}
|
||
.a-cur{max-width:none;order:5;width:100%}
|
||
/* 看板改为横向滑动通道 */
|
||
.board{display:flex;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch;scroll-snap-type:x proximity;gap:10px;padding-bottom:4px}
|
||
.col{min-width:80vw;max-width:88vw;flex:0 0 80vw;scroll-snap-align:start}
|
||
.col h3{font-size:12px}
|
||
.card-title{font-size:12px}
|
||
.pager .pgBtn{padding:8px 16px;font-size:12px;min-height:40px}
|
||
.colBody{gap:6px}
|
||
/* 通道导航条:点击直达对应列 */
|
||
.colNav{display:flex;gap:6px;overflow-x:auto;padding:2px 0 8px;flex-shrink:0;-webkit-overflow-scrolling:touch;scrollbar-width:none}
|
||
.colNav::-webkit-scrollbar{display:none}
|
||
.colNav button{flex-shrink:0;border:1px solid #e0dccd;background:#fff;border-radius:16px;padding:6px 12px;font-size:12px;color:#55534e;cursor:pointer;min-height:34px}
|
||
.colNav button:active{background:#f0ede4}
|
||
}
|
||
@media (min-width:769px){
|
||
.colNav{display:none}
|
||
}
|
||
@media (max-width:420px){
|
||
.col{min-width:88vw;max-width:94vw;flex-basis:88vw}
|
||
.agent .a-load{width:100%}
|
||
}
|
||
</style></head><body>
|
||
<span class="live"><i></i>自动刷新</span>
|
||
<h1>PERLER LAB 任务看板</h1>
|
||
<h2>生成时间 ${esc(now())} · 任务总数 <b>${total}</b> · 未关闭 Bug <b>${bugs.length}</b> · 在职 Agent <b>${activeCount}</b></h2>
|
||
<div class="agents">${rosterHtml}</div>
|
||
<div class="colNav"></div>
|
||
<div class="board"></div>
|
||
<script>window.__DB__=${boardData};</script>
|
||
<script>${RENDER_JS}</script>
|
||
<script>renderBoard(window.__DB__,false);</script>
|
||
</body></html>`;
|
||
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('<meta http-equiv="refresh" content="5">', '').replace(
|
||
'</head>',
|
||
`<script>
|
||
// 实时模式:每 2 秒拉取 /api/tasks,复用 RENDER_JS 的 renderBoard(含分页/滚动/Agent面板)
|
||
async function tick(){
|
||
try{
|
||
const r = await fetch('/api/tasks');
|
||
if(!r.ok) throw 0;
|
||
window.__DB__ = await r.json();
|
||
renderBoard(window.__DB__, 'live');
|
||
}catch(e){}
|
||
setTimeout(tick, 2000);
|
||
}
|
||
tick();
|
||
</script></head>`
|
||
);
|
||
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);
|