#!/usr/bin/env node /** * 追加团队日志.js — 团队动态日志并发安全追加工具 * (住在 91_团队工具/;team-skeleton spec §4 可选增强件,v0.4.0 起随包接入) * * 为什么有这个工具(来自源头团队的真实生产教训,已脱敏): * 十几个 agent 无锁并发直接编辑同一个日志文件顶部,实际用出过 5 条粘连损坏—— * 一个 harness 的并发追加和另一个会话的写入互相穿插,把条目黏在一起(署名头 * 被吞掉半截)。"大家都直接编辑同一个文件顶部"在多会话并发时代活不下去。 * 本工具用「锁文件排队 + 原子替换 + 写后回读验证」根治。 * 这也是团队宪章(团队根《团队结构宪章.md》§2.1)那句话的来历:团队配有本 * 工具时,写日志**一律走工具**——永远不要手工编辑日志头部。 * * 用法(三选一): * 1) argv 直传(bash 类 shell 稳;Windows PowerShell 5.1 勿用——旧码页会把 * 非 ASCII argv 搅坏): * node 追加团队日志.js "- 【2026-01-01】@建造岗:干了 X → 结论(带路径)" * 2) 文件传入(PowerShell 用户/超长条目走这个;UTF-8,BOM 可容忍): * node 追加团队日志.js --file C:\某路径\entry.txt * 3) stdin(管道): * cat entry.txt | node 追加团队日志.js --stdin * * 行为: * - 条目必须符合团队日志的格式铁律 `- 【YYYY-MM-DD】@名字:…`,不合格直接 * 拒收(防呆;你的团队想放宽格式就改 validate() 的正则)。 * - 原子创建 `<日志>.lock` 拿锁;已有锁 = 有人在写 → 每秒重试,最多 30 次。 * - 锁 mtime 超 30 秒判定为崩溃残留,强制清除接管(死锁自愈)。 * - 拿锁后:读文件 → 插到追加锚点(日志模板自带的 `▼▼▼` 注释行)正下方, * 无锚点时退回"跳过 frontmatter 后的标题行之后" → 写临时文件 → rename * 原子替换 → 回读验证条目真在。 * - 任何失败:非 0 退出码 + stderr 说明。没有静默失败。 * * 第二条留在代码里的教训(同样已脱敏):早期版本硬编码"第 0 行是标题行"。 * 日志文件加上 YAML frontmatter 块的那一天,当天每一次追加(6 次全中)都插进 * 了 frontmatter 内部、反复撑坏文件结构。computeInsertIndex() 现在先探测 * frontmatter 块——它看起来比活儿本身多疑,原因在此。 * * 下方锁/原子写辅助函数是从源头团队的公共 file-lock 模块内联进来的,让本工具 * 以**单个零依赖文件**随包分发(只用 Node 标准库,无需 npm install)。 */ 'use strict'; const fs = require('fs'); const path = require('path'); // 默认目标:本脚本住在 <团队根>/91_团队工具/,日志在 <团队根>/02_共享知识库/。 // TEAMLOG_PATH 环境变量可覆盖(仅供测试;日常勿设)。 const LOG = process.env.TEAMLOG_PATH || path.join(__dirname, '..', '02_共享知识库', '团队动态日志.md'); const LOCK = LOG + '.lock'; // die() 抛错而不是 process.exit():exit() 会跳过 finally 里的锁释放,在校验 // 失败时残留锁文件(源头团队踩过的真实 bug 类——"拿锁后回读验证失败"曾经 // 把锁留在原地,卡住其他所有写入者 30 秒等陈锁自愈)。 class DieError extends Error { constructor(msg, code) { super(msg); this.name = 'DieError'; this.exitCode = code || 1; } } function die(msg, code) { throw new DieError(msg, code); } /* ------------------------------------------------------------------ * * 内联的锁辅助函数(单一事实源:只留在本文件这一份) * * ------------------------------------------------------------------ */ class LockError extends Error { constructor(message, code) { super(message); this.name = 'LockError'; this.code = code || 'LOCK_ERROR'; } } /** 同步睡眠,不吃 CPU(Atomics.wait 阻塞当前线程但不忙等)。 */ function sleepSync(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } /** * 原子创建锁文件排队;已有锁超过 staleMs 判定为崩溃残留,强制清除接管。 */ function acquireLockSync(lockPath, opts) { opts = opts || {}; const staleMs = opts.staleMs != null ? opts.staleMs : 30 * 1000; const retryMax = opts.retryMax != null ? opts.retryMax : 30; const retryIntervalMs = opts.retryIntervalMs != null ? opts.retryIntervalMs : 1000; let transientWithoutPathRetries = 0; for (let i = 0; i < retryMax; i++) { try { fs.writeFileSync(lockPath, process.pid + ' ' + new Date().toISOString(), { flag: 'wx' }); return; // 拿到锁 } catch (e) { let contended = e.code === 'EEXIST'; if (!contended && (e.code === 'EPERM' || e.code === 'EACCES' || e.code === 'EBUSY')) { // Windows 高频创建/删除同一路径时,真实竞争偶尔不是 EEXIST 而是短暂 // EPERM。路径存在可按竞争处理;路径暂不可见只短探测 3 次,持续失败仍 // 保留权限错误真相。 if (fs.existsSync(lockPath)) { contended = true; } else if (transientWithoutPathRetries < 3) { transientWithoutPathRetries++; sleepSync(Math.min(retryIntervalMs, 20)); continue; } } if (!contended) throw new LockError('创建锁文件出错:' + e.message, 'LOCK_CREATE_FAIL'); try { const age = Date.now() - fs.statSync(lockPath).mtimeMs; if (age > staleMs) { fs.unlinkSync(lockPath); // 残留锁,清除后下一轮重试拿 if (opts.onStaleClear) opts.onStaleClear(age); continue; } } catch (e2) { /* 锁刚好被对方释放,下一轮直接拿 */ } if (i === 0 && opts.onWait) opts.onWait(); sleepSync(retryIntervalMs); } } throw new LockError('排队 ' + retryMax + ' 秒仍拿不到锁。若确认没人在写,手动删掉 ' + lockPath + ' 后重试', 'LOCK_TIMEOUT'); } /** * 释放锁。不存在视为幂等成功;其余删除错误短暂重试后必须显式失败, * 不能把残留锁伪报成已释放。 */ function releaseLockFile(lockPath, opts) { opts = opts || {}; const retryMax = opts.retryMax != null ? opts.retryMax : 5; const retryIntervalMs = opts.retryIntervalMs != null ? opts.retryIntervalMs : 20; for (let i = 0; i < retryMax; i++) { try { fs.unlinkSync(lockPath); return { released: true, existed: true }; } catch (e) { if (e.code === 'ENOENT') return { released: false, existed: false }; if (i < retryMax - 1) { sleepSync(retryIntervalMs); continue; } throw new LockError('释放锁文件失败,锁可能仍残留:' + lockPath + '(' + e.message + ')', 'LOCK_RELEASE_FAIL'); } } throw new LockError('释放锁文件失败:' + lockPath, 'LOCK_RELEASE_FAIL'); } /** * 回收同一目标的陈旧原子写临时文件。只认本模块的严格命名,且只删超过阈值的 * 普通文件;新鲜 temp 可能属于仍在运行的写者,必须保留。 */ function cleanupStaleAtomicTempsSync(targetPath, opts) { opts = opts || {}; const staleTempMs = opts.staleTempMs != null ? opts.staleTempMs : 5 * 60 * 1000; const dir = path.dirname(targetPath); const namePrefix = path.basename(targetPath) + '.tmp_'; const removed = []; const kept = []; let entries; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { if (e.code === 'ENOENT') return { removed, kept }; throw e; } for (const entry of entries) { if (!entry.isFile() || !entry.name.startsWith(namePrefix)) continue; const suffix = entry.name.slice(namePrefix.length); if (!/^\d+_\d+$/.test(suffix)) continue; const candidate = path.join(dir, entry.name); let age; try { age = Date.now() - fs.statSync(candidate).mtimeMs; } catch (e) { if (e.code === 'ENOENT') continue; throw e; } if (age <= staleTempMs) { kept.push(candidate); continue; } let removedThis = false; for (let i = 0; i < 5; i++) { try { fs.unlinkSync(candidate); removedThis = true; break; } catch (e) { if (e.code === 'ENOENT') { removedThis = true; break; } if (i < 4) { sleepSync(20); continue; } throw new LockError('清理陈旧原子写临时文件失败:' + candidate + '(' + e.message + ')', 'ATOMIC_TEMP_CLEANUP_FAIL'); } } if (removedThis) removed.push(candidate); } return { removed, kept }; } /** 临时文件 + rename 原子替换(Windows Node rename 可覆盖已存在目标)。UTF-8 无 BOM。 */ function atomicWriteSync(targetPath, content, opts) { cleanupStaleAtomicTempsSync(targetPath, opts); const tmp = targetPath + '.tmp_' + process.pid + '_' + Date.now(); try { fs.writeFileSync(tmp, content, 'utf8'); fs.renameSync(tmp, targetPath); } catch (e) { try { fs.unlinkSync(tmp); } catch (cleanupError) { if (cleanupError.code !== 'ENOENT') e.cleanupError = cleanupError; } throw e; } } /* ------------------------------------------------------------------ * * 工具本体 * * ------------------------------------------------------------------ */ function readEntry() { const args = process.argv.slice(2); if (args[0] === '--file') { if (!args[1]) die('--file 后面要跟文件路径'); if (!fs.existsSync(args[1])) die('条目文件不存在:' + args[1]); let t = fs.readFileSync(args[1], 'utf8'); if (t.charCodeAt(0) === 0xFEFF) t = t.slice(1); // 容忍 BOM return t.trim(); } if (args[0] === '--stdin') { try { return fs.readFileSync(0, 'utf8').trim(); } catch (e) { die('读 stdin 失败:' + e.message); } } if (args.length === 0) die('没给条目。用法见文件头注释(argv / --file / --stdin 三选一)'); return args.join(' ').trim(); } function validate(entry) { if (!/^- 【\d{4}-\d{2}-\d{2}】@\S+[::]/.test(entry)) { die('条目格式不对。必须以 `- 【YYYY-MM-DD】@名字:` 开头(团队日志的格式铁律),收到的是:' + entry.slice(0, 50) + '…'); } if (entry.includes('\n')) { // 多行条目压成一行(日志一条=一行的惯例;换行会破坏 diff 和条目计数) entry = entry.split('\n').map(s => s.trim()).filter(Boolean).join(' '); } return entry; } function acquireLock() { try { acquireLockSync(LOCK, { onWait: () => process.stderr.write('[追加团队日志] 有人正在写日志,排队等待…\n'), onStaleClear: (age) => process.stderr.write( '[追加团队日志] 清除了 ' + Math.round(age / 1000) + 's 前的残留锁(持锁进程疑似已崩溃)\n' ), }); } catch (e) { if (e instanceof LockError) { die(e.message, e.code === 'LOCK_TIMEOUT' ? 2 : 1); } die('拿锁出错:' + e.message); } } function releaseLock() { releaseLockFile(LOCK); } /** * 插入点计算,按优先级: * 1. 追加锚点——日志模板自带一行含 `▼▼▼` 的注释("最新的条目直接加在这一行 * 下面");有锚点就插在它正下方(倒序"最新在上"由构造保证)。 * 2. 无锚点:文件若以 YAML frontmatter 块开头(`---` … `---`)先整块跳过, * 找到第一个非空行(标题行),插到其后(其后紧跟空行则插空行之后,保持 * "标题、空行、最新条目"结构)。 * frontmatter 块不完整(找不到第二个 `---`)时保守当作"无 frontmatter"处理—— * 不猜、不越界扫描全文,正文深处孤立的 `---` 分隔线永远不会被误判成 frontmatter。 */ function computeInsertIndex(lines) { // 1. 锚点行 for (let i = 0; i < lines.length; i++) { if (lines[i].includes('▼▼▼')) return i + 1; } // 2. frontmatter 感知的标题行兜底 let bodyStart = 0; if (lines[0] !== undefined && lines[0].trim() === '---') { let fmEnd = -1; for (let i = 1; i < lines.length; i++) { if (lines[i].trim() === '---') { fmEnd = i; break; } } if (fmEnd !== -1) bodyStart = fmEnd + 1; } let titleAt = bodyStart; while (lines[titleAt] !== undefined && lines[titleAt].trim() === '') titleAt++; let insertAt = titleAt + 1; if (lines[insertAt] !== undefined && lines[insertAt].trim() === '') insertAt++; return insertAt; } function main() { const entry = validate(readEntry()); if (!fs.existsSync(LOG)) die('日志文件不存在:' + LOG); acquireLock(); try { const before = fs.readFileSync(LOG, 'utf8'); const lines = before.split('\n'); const insertAt = computeInsertIndex(lines); lines.splice(insertAt, 0, entry); const after = lines.join('\n'); // 原子替换:写临时文件再 rename atomicWriteSync(LOG, after); // 写后回读验证(probe 到≠生效:认落盘不认内存) const verify = fs.readFileSync(LOG, 'utf8'); if (!verify.includes(entry)) die('写入后回读没找到刚写的条目——文件可能被并发破坏,请人工检查!', 3); const nBefore = before.split('\n').filter(l => l.startsWith('- 【')).length; const nAfter = verify.split('\n').filter(l => l.startsWith('- 【')).length; if (nAfter !== nBefore + 1) die('条目数异常:写前 ' + nBefore + ' 条、写后 ' + nAfter + ' 条(应 +1)——请人工检查!', 3); process.stdout.write('[追加团队日志] OK 已追加(当前 ' + nAfter + ' 条):' + entry.slice(0, 60) + '…\n'); // 软提醒(全部非阻断;本工具从不自动轮转——稳定>聪明) const nLines = verify.split(/\r\n|\r|\n/).length; if (nLines > 400) { process.stderr.write('[追加团队日志] 提示:日志已 ' + nLines + ' 行(>400)。可考虑把旧月份条目移进 98_归档/,保持主文件轻量\n'); } if (entry.length > 600) { process.stderr.write('[追加团队日志] 提示:本条 ' + entry.length + ' 字超建议值 600——日志一行说完,细节放产物文件\n'); } const oldestMonths = new Set((verify.match(/^- 【(\d{4}-\d{2})/gm) || []).map(s => s.slice(3))); if (oldestMonths.size > 2) { process.stderr.write('[追加团队日志] 提示:日志已跨 ' + oldestMonths.size + ' 个月,可考虑把旧月份归档进 98_归档/\n'); } } finally { releaseLock(); } } if (require.main === module) { // 运行时版本门(护栏不阻断):直接 CLI 运行且 Node 低于 18 时给一句提示;被 require 时 // 不检查、不影响 module.exports 正常路径。 if (parseInt(process.versions.node.split('.')[0], 10) < 18) { process.stderr.write('[追加团队日志] 提示:当前 Node ' + process.versions.node + ',建议 18 或更高;低版本可能在较新语法上报错,请升级 Node。\n'); } try { main(); } catch (e) { if (e instanceof DieError) { process.stderr.write('[追加团队日志] 失败:' + e.message + '\n'); } else { process.stderr.write('[追加团队日志] 未预期错误:' + ((e && e.stack) || e) + '\n'); } process.exitCode = (e && e.exitCode) || 1; } } module.exports = { computeInsertIndex, validate };