| #!/usr/bin/env node
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 'use strict';
|
| const fs = require('fs');
|
| const path = require('path');
|
|
|
|
|
|
|
|
|
| const LOG = process.env.TEAMLOG_PATH
|
| || path.join(__dirname, '..', '02-shared-knowledge', 'team-log.md');
|
| const LOCK = LOG + '.lock';
|
|
|
|
|
|
|
|
|
|
|
| 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';
|
| }
|
| }
|
|
|
|
|
| function sleepSync(ms) {
|
| Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
| }
|
|
|
| |
| |
| |
|
|
| 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')) {
|
|
|
|
|
|
|
|
|
| if (fs.existsSync(lockPath)) {
|
| contended = true;
|
| } else if (transientWithoutPathRetries < 3) {
|
| transientWithoutPathRetries++;
|
| sleepSync(Math.min(retryIntervalMs, 20));
|
| continue;
|
| }
|
| }
|
| if (!contended) throw new LockError('Failed to create lock file: ' + 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(
|
| 'Still could not take the lock after queueing ' + retryMax + ' s. If you are '
|
| + 'sure nobody is writing, delete ' + lockPath + ' by hand and retry.',
|
| '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(
|
| 'Failed to release the lock file; it may still be stranded: '
|
| + lockPath + ' (' + e.message + ')', 'LOCK_RELEASE_FAIL');
|
| }
|
| }
|
| throw new LockError('Failed to release the lock file: ' + lockPath, 'LOCK_RELEASE_FAIL');
|
| }
|
|
|
| |
| |
| |
| |
|
|
| 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(
|
| 'Failed to sweep a stale atomic-write temp file: ' + candidate
|
| + ' (' + e.message + ')', 'ATOMIC_TEMP_CLEANUP_FAIL');
|
| }
|
| }
|
| if (removedThis) removed.push(candidate);
|
| }
|
| return { removed, kept };
|
| }
|
|
|
|
|
| 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 needs a file path after it');
|
| if (!fs.existsSync(args[1])) die('Entry file does not exist: ' + args[1]);
|
| let t = fs.readFileSync(args[1], 'utf8');
|
| if (t.charCodeAt(0) === 0xFEFF) t = t.slice(1);
|
| return t.trim();
|
| }
|
| if (args[0] === '--stdin') {
|
| try {
|
| return fs.readFileSync(0, 'utf8').trim();
|
| } catch (e) {
|
| die('Failed to read stdin: ' + e.message);
|
| }
|
| }
|
| if (args.length === 0) die('No entry given. See the usage block in this file header (argv / --file / --stdin).');
|
| return args.join(' ').trim();
|
| }
|
|
|
| function validate(entry) {
|
| if (!/^- 【\d{4}-\d{2}-\d{2}】@\S+[::]/.test(entry)) {
|
| die('Entry format mismatch. It must start with `- 【YYYY-MM-DD】@name: ` '
|
| + '(the team log format contract); got: ' + entry.slice(0, 50) + '…');
|
| }
|
| if (entry.includes('\n')) {
|
|
|
| entry = entry.split('\n').map(s => s.trim()).filter(Boolean).join(' ');
|
| }
|
| return entry;
|
| }
|
|
|
| function acquireLock() {
|
| try {
|
| acquireLockSync(LOCK, {
|
| onWait: () => process.stderr.write('[append-team-log] Someone is writing the log; queueing…\n'),
|
| onStaleClear: (age) =>
|
| process.stderr.write(
|
| '[append-team-log] Cleared a stale lock from ' + Math.round(age / 1000)
|
| + 's ago (its holder likely crashed)\n'
|
| ),
|
| });
|
| } catch (e) {
|
| if (e instanceof LockError) {
|
| die(e.message, e.code === 'LOCK_TIMEOUT' ? 2 : 1);
|
| }
|
| die('Error taking the lock: ' + e.message);
|
| }
|
| }
|
|
|
| function releaseLock() {
|
| releaseLockFile(LOCK);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| function computeInsertIndex(lines) {
|
|
|
| for (let i = 0; i < lines.length; i++) {
|
| if (lines[i].includes('▼▼▼')) return i + 1;
|
| }
|
|
|
| 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('Team log file does not exist: ' + 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');
|
|
|
|
|
| atomicWriteSync(LOG, after);
|
|
|
|
|
| const verify = fs.readFileSync(LOG, 'utf8');
|
| if (!verify.includes(entry)) die('Read-back after writing did not find the new entry — the file may have been corrupted by a concurrent writer. Inspect it by hand!', 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('Entry count anomaly: ' + nBefore + ' before, ' + nAfter + ' after (expected +1) — inspect the file by hand!', 3);
|
|
|
| process.stdout.write('[append-team-log] OK, appended (' + nAfter + ' entries now): ' + entry.slice(0, 60) + '…\n');
|
|
|
|
|
| const nLines = verify.split(/\r\n|\r|\n/).length;
|
| if (nLines > 400) {
|
| process.stderr.write('[append-team-log] Note: the log is ' + nLines + ' lines now (>400). Consider moving old months into 98-archive/ to keep the head light.\n');
|
| }
|
| if (entry.length > 600) {
|
| process.stderr.write('[append-team-log] Note: this entry is ' + entry.length + ' chars (>600 suggested) — one line says it, details belong in an artifact file.\n');
|
| }
|
| const oldestMonths = new Set((verify.match(/^- 【(\d{4}-\d{2})/gm) || []).map(s => s.slice(3)));
|
| if (oldestMonths.size > 2) {
|
| process.stderr.write('[append-team-log] Note: the log now spans ' + oldestMonths.size + ' months — consider archiving the older months into 98-archive/.\n');
|
| }
|
| } finally {
|
| releaseLock();
|
| }
|
| }
|
|
|
| if (require.main === module) {
|
|
|
|
|
| if (parseInt(process.versions.node.split('.')[0], 10) < 18) {
|
| process.stderr.write('[append-team-log] Note: Node ' + process.versions.node + ' detected; 18+ recommended. Older versions may hit newer-syntax errors; please upgrade Node.\n');
|
| }
|
| try {
|
| main();
|
| } catch (e) {
|
| if (e instanceof DieError) {
|
| process.stderr.write('[append-team-log] FAILED: ' + e.message + '\n');
|
| } else {
|
| process.stderr.write('[append-team-log] Unexpected error: ' + ((e && e.stack) || e) + '\n');
|
| }
|
| process.exitCode = (e && e.exitCode) || 1;
|
| }
|
| }
|
|
|
| module.exports = { computeInsertIndex, validate };
|
|
|