File size: 16,079 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
#!/usr/bin/env node
/**

 * frontmatter-touch.js — Nomad Stop hook: keep the `updated` field of

 * charter-schema markdown files honest, without git.

 *

 * WHAT IT DOES

 * At session close-out, every `.md` under the team root whose ON-DISK reality

 * is newer than its DECLARED freshness gets its frontmatter `updated` field

 * refreshed:

 *

 *     file mtime's calendar date  >  frontmatter `updated`

 *     (or `created`, when no `updated` line exists yet)

 *         → set `updated: <mtime date>`

 *

 * WHY NOT `git status` (how the production original finds changed files)

 * The production deployment this ports from lives in a git repository, so

 * "what changed" is one `git status --porcelain` away. A Nomad team is

 * typically a zip-extracted plain folder — no `.git`, no installer-run

 * `git init` — so the discovery mechanism had to be rebuilt, not desensitized.

 * The mtime-vs-frontmatter reconciliation above was chosen over the closer

 * "files modified today" imitation because it is an ASYNC CATCH-UP: edits

 * made on a hookless harness yesterday (see the team charter's "no-hook

 * platforms reconcile on next start" compensation clause) are still caught

 * the next time ANY hook-bearing session closes — `git status` and

 * "today only" both miss that case. Trade-off accepted: mtime is a cruder

 * signal than a git diff (a content-identical rewrite still counts as

 * "changed"); the charter-schema gate below keeps the blast radius to files

 * that opted into this metadata contract.

 *

 * SAFETY RAILS (each one exists because of a concrete failure mode):

 *   1. Charter-schema gate — only files whose frontmatter carries all of

 *      `owner` + `created` + `status` are ever touched. SKILL.md-style files

 *      with their own metadata vocabulary are structurally invisible to this

 *      hook. Malformed date values (anything not YYYY-MM-DD) → skip, never

 *      "fix" (would rather leave a stale field than guess).

 *   2. mtime restore after write — rewriting the file would itself bump

 *      mtime, which next Stop would read as "changed again", re-dating

 *      `updated` to today forever. After a verified write, mtime is restored

 *      to its pre-write value, so the reconciliation converges.

 *   3. Per-run touch cap (default 100, env NOMAD_FMTOUCH_MAX_TOUCH) — a bulk

 *      copy/extraction done with a tool that does NOT preserve mtimes can

 *      make hundreds of files look freshly edited at once. The cap turns

 *      that into bounded work per close-out (progress resumes next Stop —

 *      converges, never deadlocks) instead of an IO storm inside a hook

 *      timeout window.

 *   4. Scan-baseline state file (OS temp dir, keyed by team root) — steady

 *      state, only files whose mtime moved since the last completed run get

 *      their content read at all; everything else is a bare stat() during

 *      the directory walk. Losing the state file (temp cleanup) just means

 *      one full re-read pass, which the idempotent rule then no-ops.

 *   5. Per-file lock + atomic write + read-back verify — same `<file>.lock`

 *      naming as append-log.js, so this hook and a concurrent append can

 *      never interleave a lost update on a shared file. Lock busy → skip,

 *      next Stop catches up (nothing here is worth blocking close-out for).

 *   6. Stop-hook iron rule — every failure path is silent-skip + local log

 *      line (OS temp dir, `nomad_fmtouch.log`); stdout stays empty (this is

 *      pure housekeeping, zero injection budget), close-out is NEVER blocked.

 *

 * ONE DELIBERATE DIVERGENCE from the production original: when a

 * charter-schema file has no `updated` line yet, this version INSERTS one

 * (right after `created`). The production deployment leaves missing fields

 * to its structure-sentinel to report — that sentinel is not part of this

 * portable package, and Nomad-scaffolded teams ship with `updated` absent

 * everywhere (it's optional in the charter), so "replace-only" would make

 * this hook a permanent no-op on exactly the teams it ships to.

 *

 * Usage: node frontmatter-touch.js [--platform claude|codex|cursor]

 *   stdin: hook input JSON (cwd / session_id). Not inside a Nomad team

 *   (no team-config.json up the tree) → exits silently.

 */

'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const emit = require('./lib/emit');
const cfg = require('./lib/config');
const fm = require('./lib/frontmatter');
const flock = require('./lib/file-lock');

const LOG_FILE = path.join(os.tmpdir(), 'nomad_fmtouch.log');
const STATE_FILE_PREFIX = 'nomad_fmtouch_state_';
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const DEFAULT_MAX_TOUCH_PER_RUN = 100;

function log(msg) {
  try {
    fs.appendFileSync(LOG_FILE, '[' + new Date().toISOString() + '] ' + msg + '\n', 'utf8');
  } catch (e) {
    /* logging must never hurt */
  }
}

/** Local-calendar date string (YYYY-MM-DD) for an epoch-ms timestamp. */
function dateStrFromMs(ms) {
  const d = new Date(ms);
  return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}

// ── exclusion rules (pure functions, exported for tests) ──────────────────
//
// Deliberately structural, never one deployment's folder names:
//   - dot-directories (.git/.claude/.codex/...) — tool internals
//   - node_modules — dependency trees are nobody's team documents
//   - 97/98/99-prefixed slots — the team-skeleton convention numbers its
//     inbox-misc / archive / recycle-bin slots 97/98/99 in BOTH the English
//     and native-language layouts, so the digits are the stable signal while
//     the human-readable part varies by language.
// Everything else is left to the charter-schema gate: a file that carries
// owner+created+status has opted into this metadata contract wherever it
// lives; one that doesn't is invisible regardless of directory.

function isExcludedDirName(name) {
  if (!name) return true;
  if (name.charAt(0) === '.') return true;
  if (name === 'node_modules') return true;
  if (/^9[789]([-_ ]|$)/.test(name)) return true;
  return false;
}

function isExcludedFileName(name) {
  if (!name) return true;
  if (name.charAt(0) === '~') return true;
  if (/\.bak(\.|_|$)/i.test(name)) return true;
  return false;
}

/**

 * Recursively collect candidate .md files under rootDir (exclusion-pruned).

 * Returns [{abs, mtimeMs}]. Symlinked directories are not followed

 * (readdirSync dirents report them as symlinks, not directories). Never throws.

 */
function collectMdFiles(rootDir) {
  const out = [];
  function walk(dir) {
    let entries;
    try {
      entries = fs.readdirSync(dir, { withFileTypes: true });
    } catch (e) {
      return;
    }
    for (const ent of entries) {
      if (ent.isDirectory()) {
        if (!isExcludedDirName(ent.name)) walk(path.join(dir, ent.name));
      } else if (ent.isFile()) {
        if (isExcludedFileName(ent.name)) continue;
        if (!/\.md$/i.test(ent.name)) continue;
        const abs = path.join(dir, ent.name);
        try {
          out.push({ abs, mtimeMs: fs.statSync(abs).mtimeMs });
        } catch (e) {
          /* raced deletion etc. — skip */
        }
      }
    }
  }
  walk(rootDir);
  return out;
}

// ── core decision (pure function, exported for tests) ─────────────────────

/**

 * Decide whether/how to refresh `updated` for one file's content.

 *

 * @param {string} content full file text

 * @param {string} fileDate the file's mtime as YYYY-MM-DD

 * @returns {null|{content:string, date:string, inserted:boolean}}

 *   null = leave the file alone (no frontmatter / broken block / not

 *   charter-schema / malformed dates / already up to date).

 */
function computeNext(content, fileDate) {
  if (!DATE_RE.test(fileDate)) return null;
  const parsed = fm.parse(content);
  if (!parsed || !parsed.complete) return null;

  const f = parsed.fields;
  // Charter-schema gate: owner + created + status must all be present (non-empty).
  if (!f.owner || !f.created || !f.status) return null;

  const hasUpdated = Object.prototype.hasOwnProperty.call(f, 'updated');
  let baseline;
  if (hasUpdated) {
    if (!DATE_RE.test(f.updated)) return null; // malformed — never "fix" by guessing
    baseline = f.updated;
  } else {
    if (!DATE_RE.test(f.created)) return null;
    baseline = f.created;
  }
  // YYYY-MM-DD strings compare correctly as strings.
  if (!(fileDate > baseline)) return null;

  // Surgical single-line edit: split preserving separators so the file's
  // newline style (and any mixed usage) survives byte-for-byte elsewhere.
  const body = parsed.hasBom ? content.slice(1) : content;
  const parts = body.split(/(\r\n|\r|\n)/); // [line0, sep0, line1, sep1, ...]
  const dominantSep = parts.length > 1 ? parts[1] : '\n';

  // blockLines index → physical logical-line index: block starts after the
  // opening fence (logical line 0), so blockLines[i] is logical line i+1.
  const targetKey = hasUpdated ? 'updated' : 'created';
  const blockIdx = parsed.lineIndexByKey[targetKey];
  if (blockIdx === undefined) return null; // defensive — fields came from these lines
  const logicalIdx = blockIdx + 1;
  const partsIdx = logicalIdx * 2;
  if (partsIdx >= parts.length) return null;

  if (hasUpdated) {
    parts[partsIdx] = 'updated: ' + fileDate;
  } else {
    // Insert a brand-new `updated` line right after the `created` line,
    // reusing that line's own separator so CRLF files stay CRLF.
    const sep = partsIdx + 1 < parts.length ? parts[partsIdx + 1] : dominantSep;
    parts.splice(partsIdx + 2, 0, 'updated: ' + fileDate, sep);
  }
  return {
    content: (parsed.hasBom ? '' : '') + parts.join(''),
    date: fileDate,
    inserted: !hasUpdated,
  };
}

// ── per-file processing ────────────────────────────────────────────────────

/**

 * Lock → re-read → re-decide → atomic write → verify → restore mtime.

 * @returns {'touched'|'skipped'|'locked'|'failed'}

 */
function touchFile(absPath) {
  const lockPath = absPath + '.lock';
  try {
    // Short retry only: lock busy means someone (e.g. append-log.js) is
    // writing right now — skip, next Stop catches up. Not worth waiting on.
    flock.acquireLockSync(lockPath, { retryMax: 3, retryIntervalMs: 500 });
  } catch (e) {
    return 'locked';
  }
  try {
    // Re-stat and re-read AFTER acquiring the lock — the pre-lock snapshot
    // may be stale by the time we hold exclusivity.
    const st = fs.statSync(absPath);
    const content = fs.readFileSync(absPath, 'utf8');
    const next = computeNext(content, dateStrFromMs(st.mtimeMs));
    if (next === null) return 'skipped';

    flock.atomicWriteSync(absPath, next.content);
    const verify = fs.readFileSync(absPath, 'utf8');
    if (verify.indexOf('updated: ' + next.date) === -1) {
      log('VERIFY-FAIL ' + absPath);
      return 'failed';
    }
    // Restore mtime so this write doesn't read as a fresh edit next run
    // (safety rail #2 in the header). utimesSync takes seconds.
    try {
      fs.utimesSync(absPath, st.atimeMs / 1000, st.mtimeMs / 1000);
    } catch (e) {
      // Non-fatal: worst case is one extra (idempotent, hence no-op) check
      // next run — computeNext will see updated == fileDate and skip.
      log('MTIME-RESTORE-FAIL ' + absPath + ' :: ' + e.message);
    }
    return 'touched';
  } catch (e) {
    log('ERR ' + absPath + ' :: ' + e.message);
    return 'failed';
  } finally {
    flock.releaseLock(lockPath);
  }
}

// ── scan-baseline state (perf only — correctness never depends on it) ─────

function stateFilePath(teamRoot) {
  const key = crypto.createHash('sha256').update(String(teamRoot).toLowerCase(), 'utf8').digest('hex').slice(0, 12);
  return path.join(os.tmpdir(), STATE_FILE_PREFIX + key + '.txt');
}

function readScanBaseline(teamRoot) {
  try {
    const raw = fs.readFileSync(stateFilePath(teamRoot), 'utf8');
    const ms = parseInt(raw, 10);
    return Number.isFinite(ms) && ms > 0 ? ms : 0;
  } catch (e) {
    return 0; // no/broken state = full pass (safe: rule is idempotent)
  }
}

function writeScanBaseline(teamRoot, ms) {
  try {
    fs.writeFileSync(stateFilePath(teamRoot), String(ms), 'utf8');
  } catch (e) {
    /* perf optimization only — losing it is harmless */
  }
}

function maxTouchPerRun() {
  const raw = parseInt(process.env.NOMAD_FMTOUCH_MAX_TOUCH || '', 10);
  return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_MAX_TOUCH_PER_RUN;
}

// ── main ───────────────────────────────────────────────────────────────────

async function main() {
  const platform = emit.getPlatform();
  try {
    const raw = await emit.readStdin();
    const sid = emit.extractSessionId(raw);
    if (sid && emit.isDuplicateInvocation('FmTouch', sid)) {
      process.exit(0);
      return;
    }

    const cwd = emit.resolveCwd(raw, platform);
    const teamRoot = cfg.resolveTeamRoot(cwd || process.cwd());
    if (!teamRoot) {
      process.exit(0); // not inside a Nomad team — none of our business
      return;
    }

    const baseline = readScanBaseline(teamRoot);
    const scanStartMs = Date.now();
    const files = collectMdFiles(teamRoot);
    // Only files whose mtime moved since the last COMPLETED run need their
    // content read; on a first run (baseline 0) that's everything.
    const candidates = files.filter((f) => f.mtimeMs > baseline);

    const cap = maxTouchPerRun();
    let touched = 0;
    let skipped = 0;
    let locked = 0;
    let failed = 0;
    let capped = 0;
    for (const f of candidates) {
      if (touched >= cap) {
        capped++;
        continue;
      }
      const r = touchFile(f.abs);
      if (r === 'touched') touched++;
      else if (r === 'locked') locked++;
      else if (r === 'failed') failed++;
      else skipped++;
    }

    // Advance the baseline only when this run actually processed everything —
    // capped/locked leftovers stay visible to the next run. Baseline is the
    // scan START time so edits landing mid-run are re-checked next time
    // (over-checking is a no-op; under-checking would be a miss).
    if (capped === 0 && locked === 0) writeScanBaseline(teamRoot, scanStartMs);

    // One line per run even when nothing happened — "did the host actually
    // invoke this hook" is the #1 debugging question, and a temp-dir log
    // line per close-out is cheap.
    log(
      'done root=' + teamRoot + ' scanned=' + files.length + ' candidates=' + candidates.length +
      ' touched=' + touched + ' skipped=' + skipped + ' locked=' + locked +
      ' failed=' + failed + ' capped=' + capped
    );
    // stdout stays empty by design: pure housekeeping, zero injection budget.
  } catch (e) {
    // Stop-hook iron rule: never block close-out. stderr trace only.
    try {
      process.stderr.write('[frontmatter-touch] non-fatal error, close-out not blocked: ' + ((e && e.stack) || e) + '\n');
    } catch (e2) {
      /* nothing left to do */
    }
  }
  process.exit(0);
}

if (require.main === module) {
  main();
}

module.exports = {
  dateStrFromMs,
  isExcludedDirName,
  isExcludedFileName,
  collectMdFiles,
  computeNext,
  touchFile,
  stateFilePath,
  readScanBaseline,
  writeScanBaseline,
  DATE_RE,
  DEFAULT_MAX_TOUCH_PER_RUN,
};