File size: 16,413 Bytes
0110783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#!/usr/bin/env node
/**

 * append-team-log.js — concurrency-safe append tool for the team log

 * (lives in 91-team-tools/; team-skeleton spec §4 optional enhancement,

 *  wired into the modpack since v0.4.0)

 *

 * WHY THIS EXISTS (real production lesson from the source team, sanitized):

 * a dozen-plus agents all editing the top of the same team-log file with no

 * lock corrupted 5 entries in real use — one harness's concurrent appends

 * interleaved with another session's and glued entries together (signature

 * headers swallowed mid-line). "Everyone edits the top of the same file"

 * does not survive the concurrent-session era. This tool fixes it for good:

 * lock-file queueing + atomic replace + read-back verification.

 * That is also why the team constitution (team-root ARCHITECTURE.md §2.1)

 * says: when the team ships this tool, ALWAYS write through it — never edit

 * the log head by hand.

 *

 * USAGE (three ways, pick one):

 *   1) argv, direct (fine in bash-like shells; avoid in Windows PowerShell 5.1 —

 *      its legacy codepage mangles non-ASCII argv):

 *      node append-team-log.js "- 【2026-01-01】@builder: did X → conclusion (path)"

 *   2) file (PowerShell users / long entries; UTF-8, BOM tolerated):

 *      node append-team-log.js --file C:\path\entry.txt

 *   3) stdin (pipe):

 *      cat entry.txt | node append-team-log.js --stdin

 *

 * BEHAVIOR:

 *   - The entry must match the team log's format contract

 *     `- 【YYYY-MM-DD】@name: …` — anything else is rejected up front

 *     (foolproofing; if your team relaxes the format, adjust validate()).

 *   - Takes the lock by atomically creating `<log>.lock`; if someone else holds

 *     it, retries once per second, up to 30 times.

 *   - A lock older than 30s counts as a crash leftover and is force-cleared

 *     (deadlock self-healing).

 *   - With the lock held: read file → insert right below the append anchor

 *     (the `▼▼▼` comment line the log template ships with), or below the title

 *     line when no anchor exists → write temp file → atomic rename → read back

 *     and verify the entry actually landed.

 *   - Any failure: non-zero exit + a stderr explanation. No silent failure.

 *

 * SECOND LESSON kept in code (also sanitized): an earlier version hardcoded

 * "line 0 is the title line". The day a YAML frontmatter block was added to

 * the log file, every append that day (6 out of 6) inserted INTO the

 * frontmatter and repeatedly broke the file structure. computeInsertIndex()

 * now probes for the frontmatter block first — that is why it looks more

 * paranoid than the job sounds.

 *

 * The lock/atomic-write helpers below were inlined from the source team's

 * shared file-lock module so this ships as ONE dependency-free file (Node

 * standard library only, no npm install).

 */

'use strict';
const fs = require('fs');
const path = require('path');

// Default target: this script lives in <team-root>/91-team-tools/, the log in
// <team-root>/02-shared-knowledge/. TEAMLOG_PATH env var overrides (tests only;
// don't set it in daily use).
const LOG = process.env.TEAMLOG_PATH
  || path.join(__dirname, '..', '02-shared-knowledge', 'team-log.md');
const LOCK = LOG + '.lock';

// die() throws instead of process.exit(): exit() would skip the finally-block
// lock release and leave a stale lock behind on validation failures (a real
// bug class the source team hit — "read-back verification failed after taking
// the lock" used to strand the lock and stall every other writer for 30s).
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); }

/* ------------------------------------------------------------------ *

 * Inlined lock helpers (single source: keep them in this file only)  *

 * ------------------------------------------------------------------ */

class LockError extends Error {
  constructor(message, code) {
    super(message);
    this.name = 'LockError';
    this.code = code || 'LOCK_ERROR';
  }
}

/** Synchronous sleep without busy-waiting (Atomics.wait blocks, no CPU spin). */
function sleepSync(ms) {
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}

/**

 * Queue on the lock file (atomic create). An existing lock older than staleMs

 * is treated as a crash leftover and force-cleared.

 */
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; // got the lock
    } catch (e) {
      let contended = e.code === 'EEXIST';
      if (!contended && (e.code === 'EPERM' || e.code === 'EACCES' || e.code === 'EBUSY')) {
        // On Windows, high-frequency create/delete on the same path sometimes
        // surfaces real contention as a transient EPERM instead of EEXIST.
        // If the path exists, treat it as contention; if not, probe briefly
        // (3x) before letting the genuine permission error through.
        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); // stale leftover — clear it and retry next round
          if (opts.onStaleClear) opts.onStaleClear(age);
          continue;
        }
      } catch (e2) {
        /* lock was released right under us — next round takes it */
      }
      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');
}

/**

 * Release the lock. Missing file = idempotent success; any other unlink error

 * is retried briefly, then MUST fail loudly — never report a stranded lock as

 * released.

 */
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');
}

/**

 * Sweep stale atomic-write temp files for the same target. Only this module's

 * strict naming pattern, only regular files older than the threshold — a fresh

 * temp may belong to a writer that is still running and must be kept.

 */
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 };
}

/** Temp file + rename = atomic replace (Windows Node rename overwrites). UTF-8, no 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;
  }
}

/* ------------------------------------------------------------------ *

 * Tool body                                                          *

 * ------------------------------------------------------------------ */

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); // tolerate BOM
    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')) {
    // One entry = one line (the log convention); newlines break diffs and entry counting.
    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);
}

/**

 * Insert-point computation, in priority order:

 *   1. Append anchor — the log template ships a `▼▼▼` comment line reading

 *      "append the newest entry directly below this line"; if present, insert

 *      right below it (newest-on-top stays true by construction).

 *   2. No anchor: skip a YAML frontmatter block if the file starts with one

 *      (`---` … `---`), find the first non-blank line (the title), insert after

 *      it (and after one following blank line, keeping "title, blank, newest").

 * An unterminated frontmatter block (no second `---`) is conservatively treated

 * as "no frontmatter" — no guessing, no full-file scanning, so a stray `---`

 * divider deep in the body can never be misread as a frontmatter fence.

 */
function computeInsertIndex(lines) {
  // 1. anchor line
  for (let i = 0; i < lines.length; i++) {
    if (lines[i].includes('▼▼▼')) return i + 1;
  }
  // 2. frontmatter-aware title fallback
  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');

    // Atomic replace: temp file + rename.
    atomicWriteSync(LOG, after);

    // Read-back verification ("probed" is not "landed": trust disk, not memory).
    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');

    // Soft reminders (all non-blocking; this tool never auto-rotates — stable beats clever)
    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) {
  // Runtime version gate (a guardrail, not a gate): if run directly on Node < 18, print a
  // note; skipped when require()'d, so module.exports stays unaffected.
  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 };