nomad / scripts /append-log.js
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
Raw
History Blame Contribute Delete
9.76 kB
#!/usr/bin/env node
/**
* append-log.js — concurrency-safe append tool for the shared team log (and,
* generically, any "top-insert or bottom-append a line" markdown file).
*
* Ported from a production teamlog module, deployed at `91-team-tools/teamlog/append-teamlog.js`, +
* a production concurrency module, deployed at `91-team-tools/concurrency/safe-append.js`, merged into one tool and
* desensitized. Same core guarantee as both originals: atomic lock-file
* queueing + atomic temp-file-then-rename replace + read-back verification —
* this is what makes "many agents append to one shared log concurrently"
* safe instead of a corruption risk (the production deployment this was
* distilled from hit real concurrent-write corruption before this existed —
* see scripts/README.md).
*
* Deliberate difference from the production append-teamlog.js: THIS tool does
* NOT enforce a specific entry format (no forced `- 【YYYY-MM-DD】@name:`
* pattern). A portable template can't assume every deployment's team log uses
* that exact convention — team-skeleton.md only specifies "append-only,
* reverse-chronological", not a literal entry grammar. Format discipline is
* the caller's responsibility (same design choice as production's
* concurrency/safe-append.js, which this tool's --mode/--anchor options are
* ported from).
*
* Usage (target file resolution: --target overrides > team-config.json's
* shared_paths.team_log resolved from the team root found by walking up from
* cwd):
* node append-log.js "<entry text>" [--target <path>] [--mode top|bottom] [--anchor <regex>]
* node append-log.js --file <entry-file-path> [--target <path>] [--mode top|bottom] [--anchor <regex>]
* node append-log.js --stdin [--target <path>] [--mode top|bottom] [--anchor <regex>]
*
* Modes:
* --mode top (default):
* - no --anchor: classic team-log insert point — right after the title
* line (line 1); if line 2 is blank, insert after that blank line
* instead (preserves a "title, blank line, newest entry" shape).
* - --anchor "<regex>": insert after the FIRST line matching the regex
* (e.g. inserting under a specific "## Unread" heading in an inbox
* file). No match = hard error, never silently falls back elsewhere.
* --mode bottom: append a line at end of file (adds a trailing newline
* first if the file didn't already end with one, without touching the
* existing last line's content).
*
* Behavior:
* - Entry content with embedded newlines gets collapsed to one line (a
* multi-line entry would break the "one line = one entry" convention).
* - Atomically creates `<target>.lock` to queue writers; a lock older than
* 30s is treated as a crashed holder's leftover and force-cleared.
* - After acquiring the lock: read file → insert per mode → write to a
* temp file → atomic rename → read back and verify the entry is actually
* there + line count is consistent with the insert.
* - Any failure: non-zero exit code + a stderr message. No silent failures.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const flock = require('./lib/file-lock');
const cfg = require('./lib/config');
/**
* die() THROWS rather than calling process.exit() directly — this is
* deliberate, not an oversight. Several die() call sites (notably
* computeTopInsertIndex on an --anchor miss) run *after* the lock has already
* been acquired, inside a try/finally whose finally block releases it. A bare
* process.exit() would skip that finally entirely and leak the lock file,
* wedging every subsequent writer until the 30s stale-lock self-heal kicks in.
* Throwing lets the existing try/finally run normally; main() below has a
* single top-level catch that turns a DieError back into the same
* "[append-log] failed: ...; non-zero exit" contract callers expect.
*/
class DieError extends Error {
constructor(message, code) {
super(message);
this.name = 'DieError';
this.code = code || 1;
}
}
function die(msg, code) {
throw new DieError(msg, code);
}
function parseArgs(argv) {
const args = { targetFile: null, mode: 'top', anchor: null, entry: null, entryFile: null, useStdin: false };
const rest = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === '--target') args.targetFile = argv[++i];
else if (a === '--mode') args.mode = argv[++i];
else if (a === '--anchor') args.anchor = argv[++i];
else if (a === '--file') args.entryFile = argv[++i];
else if (a === '--stdin') args.useStdin = true;
else rest.push(a);
}
if (!args.entry && rest.length) args.entry = rest.join(' ');
return args;
}
function readEntry(args) {
if (args.entryFile) {
if (!fs.existsSync(args.entryFile)) die('--file points to a file that does not exist: ' + args.entryFile);
return cfg.readTextFileStripBOM(args.entryFile).trim();
}
if (args.useStdin) {
try {
return fs.readFileSync(0, 'utf8').trim();
} catch (e) {
die('failed to read stdin: ' + e.message);
}
}
if (args.entry != null) return args.entry.trim();
die('no entry content given. Use one of: "<text>" as a positional arg / --file <path> / --stdin');
}
function normalizeEntry(entry) {
if (!entry) die('entry content is empty');
if (entry.includes('\n')) {
entry = entry.split('\n').map((s) => s.trim()).filter(Boolean).join(' ');
}
return entry;
}
/** top-mode insert index: returns the index to splice the new line in before. */
function computeTopInsertIndex(lines, anchorPattern) {
if (anchorPattern) {
const re = new RegExp(anchorPattern);
for (let i = 0; i < lines.length; i++) {
if (re.test(lines[i])) return i + 1;
}
die('--anchor "' + anchorPattern + '" matched no line in the target file — refusing to silently insert elsewhere');
}
let insertAt = 1;
if (lines[1] !== undefined && lines[1].trim() === '') insertAt = 2;
return insertAt;
}
/** Resolve the target file: --target (as-is if absolute, else relative to cwd) > team-config.json shared_paths.team_log. */
function resolveTargetFile(args) {
if (args.targetFile) return path.resolve(args.targetFile);
const cwd = process.cwd();
const teamRoot = cfg.resolveTeamRoot(cwd);
const config = cfg.loadTeamConfig(teamRoot);
const p = cfg.resolveSharedPath(teamRoot, config, 'team_log');
if (!p) {
die(
'no --target given, and could not resolve shared_paths.team_log from team-config.json ' +
'(team root search started at ' + cwd + '). Pass --target explicitly, or run this from ' +
'somewhere under the team root / an agent home.'
);
}
return p;
}
function runMain() {
const args = parseArgs(process.argv.slice(2));
if (args.mode !== 'top' && args.mode !== 'bottom') die('--mode only supports top or bottom, got: ' + args.mode);
const targetFile = resolveTargetFile(args);
if (!fs.existsSync(targetFile)) die('target file does not exist: ' + targetFile);
const entry = normalizeEntry(readEntry(args));
const lockPath = targetFile + '.lock';
flock.acquireLockSync(lockPath, {
onWait: () => process.stderr.write('[append-log] someone else is writing ' + path.basename(targetFile) + ', waiting...\n'),
onStaleClear: (age) =>
process.stderr.write('[append-log] cleared a ' + Math.round(age / 1000) + 's-old stale lock (holder likely crashed)\n'),
});
try {
const before = fs.readFileSync(targetFile, 'utf8');
const hadTrailingNewline = before.endsWith('\n');
const lines = before.split('\n');
let after;
if (args.mode === 'bottom') {
if (before.length === 0) after = entry + '\n';
else if (hadTrailingNewline) after = before + entry + '\n';
else after = before + '\n' + entry + '\n';
} else {
const insertAt = computeTopInsertIndex(lines, args.anchor);
lines.splice(insertAt, 0, entry);
after = lines.join('\n');
}
flock.atomicWriteSync(targetFile, after);
const verify = fs.readFileSync(targetFile, 'utf8');
if (!verify.includes(entry)) die('read-back after write did not find the entry just written — file may have been corrupted by a race, please check manually!', 3);
const linesBefore = before.split('\n').length;
const linesAfter = verify.split('\n').length;
if (linesAfter < linesBefore) die('line count decreased after write (before ' + linesBefore + ', after ' + linesAfter + ') — please check manually!', 3);
process.stdout.write(
'[append-log] OK ' + (args.mode === 'top' ? 'inserted' : 'appended') + ' into ' + path.basename(targetFile) +
': ' + entry.slice(0, 60) + (entry.length > 60 ? '...' : '') + '\n'
);
} finally {
flock.releaseLock(lockPath);
}
}
/** Top-level error boundary: turns a DieError/LockError back into "[append-log] failed: ...; non-zero exit". */
function main() {
try {
runMain();
} catch (e) {
if (e instanceof DieError) {
process.stderr.write('[append-log] failed: ' + e.message + '\n');
process.exitCode = e.code;
return;
}
if (e instanceof flock.LockError) {
process.stderr.write('[append-log] failed: ' + e.message + '\n');
process.exitCode = e.code === 'LOCK_TIMEOUT' ? 2 : 1;
return;
}
throw e; // genuinely unexpected — surface the real stack trace, don't swallow it
}
}
if (require.main === module) {
main();
}
module.exports = { computeTopInsertIndex, normalizeEntry, resolveTargetFile };