hypomnema 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,13 +17,15 @@ import {
17
17
  readdirSync,
18
18
  realpathSync,
19
19
  openSync,
20
- closeSync,
21
20
  unlinkSync,
22
21
  renameSync,
22
+ linkSync,
23
23
  } from 'fs';
24
- import { join, relative, basename, dirname } from 'path';
24
+ import { join, relative, basename, dirname, isAbsolute } from 'path';
25
25
  import { homedir, hostname, tmpdir } from 'os';
26
26
  import { spawnSync } from 'child_process';
27
+ import { randomBytes } from 'crypto';
28
+ import { fileURLToPath } from 'url';
27
29
 
28
30
  const HOME = homedir();
29
31
 
@@ -94,19 +96,196 @@ export const LOG_PATH = join(HYPO_DIR, 'log.md');
94
96
  export const HOT_PATH = join(HYPO_DIR, 'hot.md');
95
97
  export const GUIDE_PATH = join(HYPO_DIR, 'hypo-guide.md');
96
98
 
97
- // Package root: written by init/upgrade to ~/.claude/hypo-pkg.json
98
- function resolvePkgRoot() {
99
- const p = join(HOME, '.claude', 'hypo-pkg.json');
100
- if (!existsSync(p)) return null;
99
+ // Package root: written by init/upgrade to ~/.claude/hypo-pkg.json.
100
+ //
101
+ // The plugin channel is the primary distribution path, and
102
+ // Claude Code's own plugin manager updates hooks WITHOUT ever touching
103
+ // hypo-pkg.json — only our own init/upgrade write it. So after a plugin
104
+ // auto-update this file can point at a stale pkgRoot indefinitely with no
105
+ // signal to the user, and PKG_ROOT (resolved here) is what lint/feedback
106
+ // scripts get resolved through — a hook can run at the new version while the
107
+ // script it shells out to still runs from the old one.
108
+ //
109
+ // An earlier version of this cross-check queried ~/.claude/settings.json's
110
+ // `enabledPlugins` + the plugin registry to positively attribute an active
111
+ // install. That was wrong: Claude Code layers `enabledPlugins` across
112
+ // user/project/local/managed settings (project overrides user), and a plugin
113
+ // with no explicit key is enabled by default — so a single-file read of the
114
+ // user settings can neither prove "enabled" nor "disabled". Querying it was
115
+ // certain to misjudge some real layout.
116
+ //
117
+ // This code already knows the one thing that can't be wrong: where IT is
118
+ // running from. `import.meta.url`, walked up to the nearest package.json,
119
+ // names the actual root of the code executing right now — no
120
+ // settings/registry guessing needed. That's `selfLocationPkgRoot()` below.
121
+ //
122
+ // Never throw: this runs at hook-module load time (`export const PKG_ROOT =
123
+ // resolvePkgRoot()`), so a throw here takes the whole hook process down.
124
+ // Every read below is try/caught and every helper fails open to null.
125
+
126
+ /** Non-mutating read of the cached pointer, or null on any absence/corruption. */
127
+ function readCachedPkgRoot() {
101
128
  try {
129
+ const p = join(HOME, '.claude', 'hypo-pkg.json');
130
+ if (!existsSync(p)) return null;
102
131
  const v = JSON.parse(readFileSync(p, 'utf-8')).pkgRoot;
103
132
  return typeof v === 'string' && v ? v : null;
104
133
  } catch {
105
134
  return null;
106
135
  }
107
136
  }
137
+
138
+ // A pkgRoot is usable only as an ABSOLUTE path to a real package directory
139
+ // whose package.json carries a version. A relative path (e.g. ".") resolves
140
+ // against whatever cwd the reading process happens to have; a directory that
141
+ // merely EXISTS but carries no versioned package.json is a pointer nothing
142
+ // can actually resolve scripts through. Same contract for every source of a
143
+ // pkgRoot value in this file — the cache included (a cached `pkgRoot: "."`
144
+ // used to pass on directory-existence alone).
145
+ //
146
+ // NOT sufficient by itself for self-location (see selfLocationPkgRoot below):
147
+ // "absolute path + a package.json with SOME version" is true of any Node
148
+ // package anywhere on disk, including one that has nothing to do with
149
+ // Hypomnema — e.g. `$HOME/package.json` from an unrelated project. This
150
+ // contract answers "is this a real, resolvable directory", not "is this OUR
151
+ // package". Callers that need the latter also require self-containment.
152
+ function isUsablePkgRootLocal(pkgRoot) {
153
+ if (typeof pkgRoot !== 'string' || !pkgRoot || !isAbsolute(pkgRoot)) return false;
154
+ try {
155
+ const v = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf-8')).version;
156
+ return typeof v === 'string' && v.length > 0;
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+
162
+ // True iff `candidateRoot` actually CONTAINS the module that is running right
163
+ // now — i.e. `<candidateRoot>/hooks/hypo-shared.mjs` is, on disk, the exact
164
+ // same file as `ownRealPath` (this module's own realpath). This is the
165
+ // decisive check self-location needs and isUsablePkgRootLocal alone cannot
166
+ // give it: a versioned package.json only proves SOME package lives at
167
+ // `candidateRoot`, not that it is the Hypomnema install this code is part of.
168
+ // Without this, walking up from an unrelated location (a standalone-copied
169
+ // hooks/ dir sitting under a directory that happens to have its own,
170
+ // unrelated package.json a few levels up — e.g. `$HOME/package.json`) would
171
+ // silently adopt that unrelated tree as PKG_ROOT, and every script path built
172
+ // from it (`join(PKG_ROOT, 'scripts', 'lint.mjs')`, the crystallize recovery
173
+ // command in hypo-auto-minimal-crystallize.mjs, etc.) would point at files
174
+ // that were never shipped there.
175
+ //
176
+ // Both paths are realpath'd before comparing so a symlinked candidate or a
177
+ // symlinked ancestor of the running module (macOS's /var → /private/var, a
178
+ // symlinked plugin cache dir) still compares correctly. Fails closed (false)
179
+ // on any read error — a candidate this can't positively confirm is never
180
+ // adopted.
181
+ function candidateContainsRunningModule(candidateRoot, ownRealPath) {
182
+ try {
183
+ return realpathSync(join(candidateRoot, 'hooks', 'hypo-shared.mjs')) === ownRealPath;
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+
189
+ // Walk up from the PARENT of the directory this module (hooks/hypo-shared.mjs)
190
+ // is actually running from, looking for the nearest ancestor that is (a) a
191
+ // usable package root AND (b) actually contains this exact running module —
192
+ // that IS the package root of the code currently executing, regardless of
193
+ // which channel put it there (plugin, npm, dev checkout).
194
+ //
195
+ // Plugin mode runs hooks straight out of the plugin's own cache directory
196
+ // (`${CLAUDE_PLUGIN_ROOT}/hooks/...`), so this resolves directly to whatever
197
+ // the plugin loader most recently updated — exactly the channel that can
198
+ // silently drift ahead of hypo-pkg.json. A manual/npm install COPIES hooks
199
+ // standalone into ~/.claude/hooks/ with no package.json alongside (the "hooks
200
+ // import only Node built-ins, nothing outside the hooks dir" contract), so
201
+ // this correctly finds nothing self-containing there and resolvePkgRoot()
202
+ // falls through to the cache — which IS authoritative for that channel, since
203
+ // our own init/upgrade own writing it. And even if SOME unrelated ancestor
204
+ // happens to carry its own versioned package.json (a plain "usable" root),
205
+ // candidateContainsRunningModule rejects it: that ancestor's own hooks/
206
+ // subdirectory (if it even has one) is not this file.
207
+ //
208
+ // Bounded walk: up to 6 candidate ancestors above hooks/'s own parent (the
209
+ // ordinary root sits at the very first one; a few extra levels tolerate an
210
+ // unusual nesting depth). Never throws, fails open to null on any error.
211
+ function selfLocationPkgRoot() {
212
+ let hooksDir, ownRealPath;
213
+ try {
214
+ hooksDir = dirname(fileURLToPath(import.meta.url));
215
+ ownRealPath = realpathSync(join(hooksDir, 'hypo-shared.mjs'));
216
+ } catch {
217
+ return null; // can't even resolve our own path — nothing to self-contain against
218
+ }
219
+ try {
220
+ let dir = dirname(hooksDir); // first candidate: the ordinary root, one level above hooks/
221
+ for (let i = 0; i < 6; i++) {
222
+ if (isUsablePkgRootLocal(dir) && candidateContainsRunningModule(dir, ownRealPath)) {
223
+ return dir;
224
+ }
225
+ const parent = dirname(dir);
226
+ if (parent === dir) break; // reached filesystem root
227
+ dir = parent;
228
+ }
229
+ return null;
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ // Resolution order: self-location wins whenever it resolves — it is a direct,
236
+ // self-containment-verified fact about the code currently running, not an
237
+ // inference. Only when it cannot resolve (the standalone-copied hooks case
238
+ // above, or a genuine read failure) does the cache get to answer, and only
239
+ // after passing the same usable-root contract as everything else here.
240
+ function resolvePkgRoot() {
241
+ const self = selfLocationPkgRoot();
242
+ if (self) return self;
243
+ const cached = readCachedPkgRoot();
244
+ return isUsablePkgRootLocal(cached) ? cached : null;
245
+ }
108
246
  export const PKG_ROOT = resolvePkgRoot();
109
247
 
248
+ // realpath a path for comparison, falling back to the raw value on any error
249
+ // (missing/unreadable/etc — the comparison then just degrades to a literal
250
+ // string compare, same as before this existed). Never throws.
251
+ function canonicalPath(p) {
252
+ if (typeof p !== 'string' || !p) return p;
253
+ try {
254
+ return realpathSync(p);
255
+ } catch {
256
+ return p;
257
+ }
258
+ }
259
+
260
+ // Tri-state comparison between the cache and the code's own resolved
261
+ // location, for the SURFACING decision only (resolvePkgRoot() above already
262
+ // self-corrects PKG_ROOT in memory regardless of this). Three outcomes:
263
+ // 'match' — cache and self-location agree (or both resolve to nothing
264
+ // comparable) → any earlier drift mark should be CLEARED.
265
+ // 'drift' — self-location resolves and DISAGREES with the cache → notify.
266
+ // 'unknown' — self-location could not be resolved at all → leave any
267
+ // existing mark untouched. This is the PERMANENT steady state
268
+ // for the npm/manual channel (no package.json ships next to the
269
+ // standalone-copied hooks), not a rare hiccup — collapsing it
270
+ // into 'match' would let that channel silently clear a mark it
271
+ // never had grounds to judge, and collapsing it into 'drift'
272
+ // would falsely warn a channel with nothing to compare against.
273
+ //
274
+ // The equality check canonicalizes BOTH sides first: the cache may record a
275
+ // symlink alias of the very same physical root selfLocationPkgRoot() just
276
+ // walked to (a symlinked plugin cache dir, or the same /var vs /private/var
277
+ // split candidateContainsRunningModule already has to handle) — a literal
278
+ // string compare would misreport that as drift.
279
+ //
280
+ // Never throws (every helper it calls already fails open).
281
+ export function pkgRootDriftStatus() {
282
+ const self = selfLocationPkgRoot();
283
+ if (!self) return { status: 'unknown' };
284
+ const cached = readCachedPkgRoot();
285
+ if (canonicalPath(self) === canonicalPath(cached)) return { status: 'match' };
286
+ return { status: 'drift', cached, self };
287
+ }
288
+
110
289
  // Optional H2 allowlist for hot.md validation.
111
290
  // Set HYPO_ALLOWED_HOT_H2=comma,separated,headings to enable.
112
291
  const _allowedH2Env = process.env.HYPO_ALLOWED_HOT_H2;
@@ -334,18 +513,30 @@ export function hasAnyTodayLogEntry(hypoDir) {
334
513
  }
335
514
 
336
515
  /**
337
- * Date strings that count as "today" for freshness checks. Both the local and
338
- * UTC dates are accepted: Claude writes file dates in the user's local zone,
339
- * while hypo-hot-rebuild stamps root hot.md with the UTC date. Accepting both
340
- * removes the ~timezone-offset window where a correctly closed session would
341
- * otherwise false-block.
516
+ * Local and UTC calendar-day strings for a given instant. Both matter because
517
+ * some writers stamp a date in the user's local zone (Claude writing file
518
+ * content) while others stamp UTC (hypo-hot-rebuild, the session-closed
519
+ * marker's `closed_at`) — comparing only one representation opens a
520
+ * ~timezone-offset window where a same-moment date-comparison reads as two
521
+ * different days. Shared by `freshDates()` (today) and any caller comparing
522
+ * against an arbitrary past timestamp (e.g. doctor correlating a marker's
523
+ * `closed_at` against an artifact's local-dated heading).
524
+ * @param {Date} [date]
525
+ * @returns {string[]} 1-2 ISO dates (YYYY-MM-DD), local first.
526
+ */
527
+ export function localAndUtcDates(date = new Date()) {
528
+ const local = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
529
+ const utc = date.toISOString().slice(0, 10);
530
+ return local === utc ? [local] : [local, utc];
531
+ }
532
+
533
+ /**
534
+ * Date strings that count as "today" for freshness checks. See
535
+ * {@link localAndUtcDates} for why both representations are accepted.
342
536
  * @returns {string[]} 1-2 ISO dates (YYYY-MM-DD), most-relevant first.
343
537
  */
344
538
  export function freshDates() {
345
- const d = new Date();
346
- const local = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
347
- const utc = d.toISOString().slice(0, 10);
348
- return local === utc ? [local] : [local, utc];
539
+ return localAndUtcDates(new Date());
349
540
  }
350
541
 
351
542
  // Parse a single frontmatter scalar (mirrors hypo-session-start.mjs /
@@ -422,7 +613,11 @@ export function pageUsageGuardCachePath(sessionId, hypoDir) {
422
613
  return join(tmpdir(), `hypo-pageusage-guard-${safe}-${h.toString(36)}.json`);
423
614
  }
424
615
 
425
- export function pageUsageLoggingAllowed(hypoDir, sessionId) {
616
+ // `probeFn` is test-only: tests inject a fake to control the "did git answer"
617
+ // outcome deterministically instead of racing a real subprocess under shard
618
+ // load. Production callers never pass it, so they always get `runGitCheckIgnore`
619
+ // below, byte-for-byte the same spawnSync call this file always made.
620
+ export function pageUsageLoggingAllowed(hypoDir, sessionId, probeFn) {
426
621
  // The load-bearing commit gate is .hypoignore: it is what hypo-auto-stage and
427
622
  // commitWikiChanges actually filter on. Re-check it FRESH on every call (it is
428
623
  // cheap, no subprocess) so that if coverage is removed mid-session the guard
@@ -439,38 +634,96 @@ export function pageUsageLoggingAllowed(hypoDir, sessionId) {
439
634
  }
440
635
  if (!hypoIgnored) return false;
441
636
 
442
- return gitIgnoresPageUsageCached(hypoDir, sessionId);
637
+ return gitIgnoresPageUsageCached(hypoDir, sessionId, probeFn);
443
638
  }
444
639
 
445
640
  // git check-ignore is the belt signal (defends a manual `git add`); it spawns a
446
641
  // subprocess, so cache its result per session. The verdict cached here is only
447
642
  // the git signal, never the composite allow decision, so the fresh .hypoignore
448
643
  // re-check above always still runs.
449
- function gitIgnoresPageUsageCached(hypoDir, sessionId) {
644
+ // How long an unanswered probe suppresses the next one. Long enough that a git
645
+ // that is genuinely wedged costs one 10s wait per half-minute instead of one per
646
+ // prompt, short enough that a blip clears on its own well inside a session.
647
+ const PROBE_BACKOFF_MS = 30000;
648
+
649
+ // The real probe: check-ignore answers with an exit code, 0 = ignored, 1 = not
650
+ // ignored. Split out to a named function so `gitIgnoresPageUsageCached` can take
651
+ // a substitute in tests without touching what production actually spawns.
652
+ function runGitCheckIgnore(hypoDir) {
653
+ return spawnSync('git', ['-C', hypoDir, 'check-ignore', '-q', '--', PAGE_USAGE_REL], {
654
+ timeout: 10000,
655
+ });
656
+ }
657
+
658
+ function gitIgnoresPageUsageCached(hypoDir, sessionId, probeFn = runGitCheckIgnore) {
659
+ // Without a session id every caller lands on the same `default` cache file, so
660
+ // one session's verdict would answer for the next one — and the file outlives
661
+ // both, sitting in tmpdir with nothing to expire it. A verdict that cannot be
662
+ // scoped to a session is not cached at all: re-probe every time instead of
663
+ // serving a stale `true` after .gitignore coverage has been removed.
664
+ const scoped = Boolean(sessionId);
450
665
  const cachePath = pageUsageGuardCachePath(sessionId, hypoDir);
451
- try {
452
- if (existsSync(cachePath)) {
453
- const cached = JSON.parse(readFileSync(cachePath, 'utf-8'));
454
- if (typeof cached.gitIgnored === 'boolean') return cached.gitIgnored;
666
+ if (scoped) {
667
+ try {
668
+ if (existsSync(cachePath)) {
669
+ const cached = JSON.parse(readFileSync(cachePath, 'utf-8'));
670
+ if (typeof cached.gitIgnored === 'boolean') return cached.gitIgnored;
671
+ // A recorded outage still stands until it expires. This is what keeps a
672
+ // wedged git off the UserPromptSubmit path: hypo-lookup calls this before
673
+ // it prints, so a 10s wait here is 10s of dead prompt, every prompt.
674
+ if (typeof cached.unavailableUntil === 'number' && Date.now() < cached.unavailableUntil) {
675
+ return false;
676
+ }
677
+ }
678
+ } catch {
679
+ // corrupt cache → recompute below
455
680
  }
456
- } catch {
457
- // corrupt cache → recompute below
458
681
  }
459
682
 
460
- let gitIgnored = false;
683
+ // check-ignore answers with an exit code: 0 = ignored, 1 = not ignored. Every
684
+ // other outcome means the probe never got to answer — 128 for a fatal git
685
+ // error (hypoDir not a repo yet), or a null status when the timeout below
686
+ // fired or the spawn itself failed, which is what a machine under heavy
687
+ // process load produces. Treating those as a plain `false` is the bug this guards
688
+ // against: it is indistinguishable from git actually saying "not ignored",
689
+ // and the verdict then gets cached, so one blip keeps logging disabled for
690
+ // the rest of the session even after the condition clears.
691
+ // The bound is here to survive a git that never returns (an index.lock held by
692
+ // a dead process, a corrupt repo), not to race a busy machine. It used to be
693
+ // 2s, which a loaded box clears by a hair: instrumenting a one-process-per-suite
694
+ // run produced eight ETIMEDOUT probes, every one of them landing between 2011ms
695
+ // and 2254ms. check-ignore on a real vault costs single-digit milliseconds, so
696
+ // the old bound was three orders of magnitude tighter than the work and was
697
+ // measuring scheduler latency instead of git. 10s still catches a true hang.
698
+ let probe = null;
461
699
  try {
462
- gitIgnored =
463
- spawnSync('git', ['-C', hypoDir, 'check-ignore', '-q', '--', PAGE_USAGE_REL], {
464
- timeout: 2000,
465
- }).status === 0;
700
+ probe = probeFn(hypoDir);
466
701
  } catch {
467
- gitIgnored = false;
702
+ probe = null;
468
703
  }
469
704
 
470
- try {
471
- writeFileSync(cachePath, JSON.stringify({ gitIgnored }));
472
- } catch {
473
- // cache write failure is non-fatal; the git probe just reruns next prompt
705
+ // Inconclusive → fail closed for this call. The verdict is never cached as an
706
+ // answer; what gets recorded is that the probe is down, and only until the
707
+ // backoff expires. So a scheduler blip self-heals within the session, while a
708
+ // wedged git is waited on once per backoff window rather than once per prompt.
709
+ if (!probe || (probe.status !== 0 && probe.status !== 1)) {
710
+ if (scoped) {
711
+ try {
712
+ writeFileSync(cachePath, JSON.stringify({ unavailableUntil: Date.now() + PROBE_BACKOFF_MS }));
713
+ } catch {
714
+ // non-fatal; the probe just runs again next prompt
715
+ }
716
+ }
717
+ return false;
718
+ }
719
+
720
+ const gitIgnored = probe.status === 0;
721
+ if (scoped) {
722
+ try {
723
+ writeFileSync(cachePath, JSON.stringify({ gitIgnored }));
724
+ } catch {
725
+ // cache write failure is non-fatal; the git probe just reruns next prompt
726
+ }
474
727
  }
475
728
  return gitIgnored;
476
729
  }
@@ -1270,22 +1523,75 @@ function atomicWriteShared(path, content) {
1270
1523
  renameSync(tmp, path);
1271
1524
  }
1272
1525
 
1526
+ // Read the pid the current holder recorded in its lockfile (see withFileLock).
1527
+ // Returns null for anything we can't trust as a pid: empty/missing content (a
1528
+ // lock written before this pid-recording existed, or already gone), or content
1529
+ // that doesn't parse as a positive integer. null means "unknown holder" and the
1530
+ // caller falls back to the pre-liveness, mtime-only steal rule.
1531
+ function readLockHolderPid(lockPath) {
1532
+ let raw;
1533
+ try {
1534
+ raw = readFileSync(lockPath, 'utf-8').trim();
1535
+ } catch {
1536
+ return null; // vanished/unreadable mid-check — let the caller's own catch handle it
1537
+ }
1538
+ // Canonical decimal only. `Number()` would accept '1e3' and '0x10' as pids,
1539
+ // which contradicts what this function promises its callers: anything we
1540
+ // can't trust is null, not a number we guessed at.
1541
+ if (!/^[1-9][0-9]*$/.test(raw)) return null;
1542
+ const pid = Number(raw);
1543
+ return Number.isSafeInteger(pid) ? pid : null;
1544
+ }
1545
+
1546
+ // Is `pid` still running? EPERM means it exists but we can't signal it (e.g. a
1547
+ // different user) — treat that as alive too, since "can't prove it's dead" must
1548
+ // not be steal-eligible.
1549
+ function isPidAlive(pid) {
1550
+ try {
1551
+ process.kill(pid, 0);
1552
+ return true;
1553
+ } catch (err) {
1554
+ return err.code === 'EPERM';
1555
+ }
1556
+ }
1557
+
1273
1558
  /**
1274
1559
  * Run `fn` while holding an exclusive lock on `<targetPath>.lock`.
1275
1560
  *
1276
- * Acquire is a spin on `openSync(lock, 'wx')`: EEXIST means another writer holds
1277
- * it, so poll until it frees. A lock whose holder looks dead (mtime older than
1278
- * `staleMs`) is stolen. Steal is recoverable friction in the normal case (the
1279
- * stealer re-reads the committed bytes before writing), but NOT loss-free in two
1280
- * edge cases, both requiring the lock to sit untouched for `staleMs`: (1) a LIVE
1281
- * holder preempted past `staleMs` gets stolen from, so two writers run the
1282
- * critical section and one update is lost; (2) between the stale `statSync` and
1283
- * the `unlinkSync`, the holder can release and a fresh holder grab the same path,
1284
- * whose lock we then remove. `staleMs` is set well above a normal close (seconds)
1285
- * to make both extreme-low-probability. If the lock cannot be acquired within
1286
- * `timeoutMs`, throw so the caller can fall back to the write=proposal gate — for
1287
- * an append that means blocking the close (proposal-pending) with no artifact; the
1288
- * next close re-appends (architecturally consistent with the existing fail-safe).
1561
+ * Acquire is a spin on `linkSync(tmp, lock)`, where `tmp` already holds this
1562
+ * process's pid in full: EEXIST means another writer holds it, so poll until it
1563
+ * frees. Linking a complete file is what makes the lock's content trustworthy —
1564
+ * a lock is never observable in a half-written state, so "no pid in there" always
1565
+ * means a genuine pre-liveness lockfile and never a holder mid-acquire. The lock
1566
+ * file's content is therefore the holder's own pid,
1567
+ * so a lock whose mtime is older than `staleMs` is only stolen once we can also
1568
+ * confirm the recorded holder is no longer running (`process.kill(pid, 0)`). A
1569
+ * LIVE holder preempted past `staleMs` is therefore left alone — its lock is not
1570
+ * stolen, so the second writer instead polls through to `timeoutMs` and throws,
1571
+ * falling back to the write=proposal gate instead of racing the live holder's
1572
+ * critical section (this was case (1) of the old mtime-only rule, and it's what
1573
+ * closes it). A lock with no readable/parseable pid (written before this
1574
+ * recording existed) falls back to the old mtime-only rule so pre-existing
1575
+ * lockfiles from a live process on disk still get treated as steal-eligible once
1576
+ * stale — see `readLockHolderPid`. Every steal, and every steal we refuse because
1577
+ * the holder is alive, is logged to stderr so a preemption or an actual steal is
1578
+ * never silent. One edge remains, unrelated to holder liveness: between the
1579
+ * stale `statSync` and the `unlinkSync`, the holder can release and a fresh
1580
+ * holder grab the same path, whose lock we then remove — `staleMs` is set well
1581
+ * above a normal close (seconds) to make that extreme-low-probability, and it is
1582
+ * out of scope here. Release is symmetric: we only unlink the lock while it still
1583
+ * records OUR pid, so a writer that WAS stolen from never removes the lock of the
1584
+ * holder that replaced it. If the lock cannot be acquired within `timeoutMs`,
1585
+ * throw so the caller can fall back to the write=proposal gate — for an append
1586
+ * that means blocking the close (proposal-pending) with no artifact; the next
1587
+ * close re-appends (architecturally consistent with the existing fail-safe).
1588
+ *
1589
+ * Note what refusing to steal from a live holder trades away: a holder that is
1590
+ * alive but permanently hung is now never stolen from, so every later close
1591
+ * times out too. That is availability loss, not a deadlock (`timeoutMs` still
1592
+ * bounds each attempt), but unlike an ordinary lock timeout it does NOT self-heal
1593
+ * on the next close — it needs the hung process to go away. Losing an append is
1594
+ * silent; blocking one is visible, so this is the direction to fail in.
1289
1595
  *
1290
1596
  * @param {string} targetPath file being guarded (lock is a sibling `.lock`)
1291
1597
  * @param {() => T} fn critical section
@@ -1298,10 +1604,49 @@ export function withFileLock(targetPath, fn, opts = {}) {
1298
1604
  const lockPath = `${targetPath}.lock`;
1299
1605
  mkdirSync(dirname(lockPath), { recursive: true });
1300
1606
  const start = Date.now();
1301
- let fd;
1607
+ // Publish the lock ATOMICALLY: write the whole pid into a private sibling
1608
+ // first, then `linkSync` it into place. `openSync(lockPath,'wx')` followed by
1609
+ // a write cannot do this — it publishes an EMPTY lock and fills it in after,
1610
+ // and a holder preempted inside that window looks exactly like a pid-less
1611
+ // legacy lock, so a second writer steals it and both run the critical section.
1612
+ // That is the very bug the liveness check exists to close, so the acquire has
1613
+ // to be atomic for the check to mean anything. `link` also gives us the same
1614
+ // EEXIST-if-taken primitive `wx` did, and it leaves nothing behind when the
1615
+ // write fails: no link, no lock.
1616
+ // The staging name is per-call random, and the staging write is exclusive.
1617
+ // A predictable `<lock>.<pid>.tmp` would be reachable again by a later run of
1618
+ // the same pid, and a crash between the link and the staging unlink leaves tmp
1619
+ // and lock as two names for ONE inode — writing the staging file would then
1620
+ // rewrite the live lock's bytes and mtime, resurrecting a dead lock under a
1621
+ // live pid that the liveness check would then protect. Random + `wx` removes
1622
+ // both the collision and the symlink it could otherwise be pointed through.
1623
+ const tmpPath = `${lockPath}.${randomBytes(8).toString('hex')}.tmp`;
1624
+ let staged = false;
1625
+ // The live-holder refusal is re-evaluated on every poll, but it is one event,
1626
+ // not `timeoutMs / pollMs` of them. Log each once per acquire or a single
1627
+ // preemption buries the hook's stderr under ~100 identical lines.
1628
+ let loggedLiveHolder = false;
1629
+ let loggedSteal = false;
1630
+ try {
1302
1631
  for (;;) {
1303
1632
  try {
1304
- fd = openSync(lockPath, 'wx');
1633
+ if (!staged) {
1634
+ try {
1635
+ writeFileSync(tmpPath, String(process.pid), { flag: 'wx' });
1636
+ staged = true;
1637
+ } catch (stageErr) {
1638
+ // Staging fails for the same reason acquisition does — an unwritable
1639
+ // directory — and `openSync(lock,'wx')` used to report exactly that as
1640
+ // EEXIST whenever a lock was already sitting there, sending it down the
1641
+ // contention path. Preserve that: contend if a lock exists, and surface
1642
+ // a genuine write failure otherwise rather than masking it as a timeout.
1643
+ if (!existsSync(lockPath)) throw stageErr;
1644
+ throw Object.assign(new Error('lock-contended'), { code: 'EEXIST' });
1645
+ }
1646
+ }
1647
+ // Kept separate from staging on purpose: EPERM/EMLINK from the link are
1648
+ // real failures, not contention, and must not decay into ELOCKTIMEOUT.
1649
+ linkSync(tmpPath, lockPath);
1305
1650
  break;
1306
1651
  } catch (err) {
1307
1652
  if (err.code !== 'EEXIST') throw err;
@@ -1313,13 +1658,38 @@ export function withFileLock(targetPath, fn, opts = {}) {
1313
1658
  // the timeoutMs → ELOCKTIMEOUT contract (caller falls to the proposal gate).
1314
1659
  let stale = false;
1315
1660
  try {
1316
- // Steal a lock whose holder looks dead. Loss-free unless the holder is
1317
- // actually live-but-preempted past staleMs (see JSDoc edge cases).
1661
+ // Steal-eligible by age alone; liveness is checked separately below
1662
+ // before we actually act on it.
1318
1663
  stale = Date.now() - statSync(lockPath).mtimeMs > staleMs;
1319
1664
  } catch (statErr) {
1320
1665
  if (statErr.code === 'ENOENT') continue; // lock vanished; retry create now
1321
1666
  throw statErr; // unexpected stat failure — surface it, don't mask
1322
1667
  }
1668
+ if (stale) {
1669
+ const holderPid = readLockHolderPid(lockPath);
1670
+ if (holderPid !== null && isPidAlive(holderPid)) {
1671
+ // LIVE holder preempted past staleMs: do NOT steal. Surface it so the
1672
+ // preemption is visible, then fall through to the poll/timeout path
1673
+ // below instead of racing a second writer into the critical section.
1674
+ if (!loggedLiveHolder) {
1675
+ console.error(
1676
+ `[hypomnema] withFileLock: NOT stealing ${lockPath} — holder pid ${holderPid} is still alive past staleMs=${staleMs}`,
1677
+ );
1678
+ loggedLiveHolder = true;
1679
+ }
1680
+ stale = false;
1681
+ } else if (!loggedSteal) {
1682
+ // Also once per acquire: an un-removable stale lock re-enters this
1683
+ // branch on every poll, and the steal is one event either way.
1684
+ console.error(
1685
+ `[hypomnema] withFileLock: stealing stale lock ${lockPath}` +
1686
+ (holderPid !== null
1687
+ ? ` (holder pid ${holderPid} is no longer running)`
1688
+ : ' (no readable holder pid — pre-liveness lockfile)'),
1689
+ );
1690
+ loggedSteal = true;
1691
+ }
1692
+ }
1323
1693
  if (stale) {
1324
1694
  try {
1325
1695
  unlinkSync(lockPath);
@@ -1341,16 +1711,33 @@ export function withFileLock(targetPath, fn, opts = {}) {
1341
1711
  sleepSync(pollMs);
1342
1712
  }
1343
1713
  }
1344
- try {
1345
- return fn();
1346
1714
  } finally {
1715
+ // The sibling is only ever a staging file: once linked, the lock IS the
1716
+ // link, and on every failure path it must not survive as litter.
1347
1717
  try {
1348
- closeSync(fd);
1718
+ unlinkSync(tmpPath);
1349
1719
  } catch {
1350
- /* fd already gone */
1720
+ /* never created, or already gone */
1351
1721
  }
1722
+ }
1723
+ try {
1724
+ return fn();
1725
+ } finally {
1726
+ // Only remove the lock if it is still OURS. Recording the pid makes this
1727
+ // checkable: if we were stolen from (a legacy pid-less lock of ours, or the
1728
+ // stat/unlink window below), the path now holds a DIFFERENT holder's lock and
1729
+ // unlinking it unconditionally would hand a third writer the critical section
1730
+ // while that holder is still inside it. Leaving a foreign lock alone costs
1731
+ // nothing — its own holder releases it, or it goes stale.
1352
1732
  try {
1353
- unlinkSync(lockPath);
1733
+ const stillOurs = readLockHolderPid(lockPath);
1734
+ if (stillOurs === process.pid) unlinkSync(lockPath);
1735
+ else if (existsSync(lockPath))
1736
+ console.error(
1737
+ `[hypomnema] withFileLock: not releasing ${lockPath} — it now holds ${
1738
+ stillOurs === null ? 'no readable pid' : `pid ${stillOurs}`
1739
+ }, so ours was stolen`,
1740
+ );
1354
1741
  } catch {
1355
1742
  /* lock already stolen/removed */
1356
1743
  }
@@ -1464,6 +1851,39 @@ function syncStatePath(hypoDir) {
1464
1851
  return join(hypoDir, '.cache', 'sync-state.json');
1465
1852
  }
1466
1853
 
1854
+ /**
1855
+ * Classify a sync-state `op` into the guidance branch it needs. Centralized
1856
+ * here — rather than each surface repeating its own string check — because
1857
+ * hypo-session-start.mjs's syncStateNotice and doctor.mjs's checkSyncState
1858
+ * used to each carry their own comparison, and drifted: session-start's
1859
+ * exact `=== 'conflict'` check silently missed 'conflict-unresolved' (the
1860
+ * MORE dangerous op, since the abort itself failed and the tree may still be
1861
+ * half-merged) and fell through to the generic "last sync failed" line,
1862
+ * while doctor's `startsWith('conflict')` already caught it. Both
1863
+ * callers now branch on this single function's return value, so they cannot
1864
+ * silently diverge on WHICH op gets which treatment again — only on the
1865
+ * prose each renders for a given branch.
1866
+ *
1867
+ * Both known ops are matched by EXACT string, not startsWith: a future
1868
+ * `conflict-*` value this function has never seen (e.g. a new syncRemote
1869
+ * failure mode added later) must not silently fall into either known
1870
+ * bucket. 'conflict' asserts the abort succeeded and local work is safely
1871
+ * committed; 'conflict-unresolved' asserts the abort itself failed. Neither
1872
+ * claim is known to hold for an op nobody has written a branch for yet, so
1873
+ * it gets its own conservative 'unknown-conflict' bucket instead of
1874
+ * inheriting either surface's reassurance by accident.
1875
+ *
1876
+ * @param {string} op
1877
+ * @returns {'conflict-unresolved'|'conflict'|'unknown-conflict'|'other'}
1878
+ */
1879
+ export function classifySyncOp(op) {
1880
+ const s = String(op || '');
1881
+ if (s === 'conflict-unresolved') return 'conflict-unresolved';
1882
+ if (s === 'conflict') return 'conflict';
1883
+ if (s.startsWith('conflict')) return 'unknown-conflict';
1884
+ return 'other';
1885
+ }
1886
+
1467
1887
  /**
1468
1888
  * Append a sync failure entry. Best-effort — never throws, since a failed
1469
1889
  * failure-log must not break the Stop hook that calls it.
@@ -1528,6 +1948,7 @@ export function syncRemote(hypoDir) {
1528
1948
  const pull = git('pull', '--no-rebase', '-q');
1529
1949
  if (pull.status === 0) {
1530
1950
  result.pulled = true;
1951
+ recordSyncSuccess(hypoDir, 'pull');
1531
1952
  } else {
1532
1953
  // A merge conflict leaves unmerged index entries; a network/auth failure
1533
1954
  // leaves none. Only the former must be aborted to keep the tree clean.
@@ -1552,39 +1973,390 @@ export function syncRemote(hypoDir) {
1552
1973
  appendSyncFailure(hypoDir, 'pull', pull.stderr || pull.stdout);
1553
1974
  }
1554
1975
  const push = git('push');
1555
- if (push.status === 0) result.pushed = true;
1556
- else appendSyncFailure(hypoDir, 'push', push.stderr || push.stdout);
1976
+ if (push.status === 0) {
1977
+ result.pushed = true;
1978
+ recordSyncSuccess(hypoDir, 'push');
1979
+ } else appendSyncFailure(hypoDir, 'push', push.stderr || push.stdout);
1557
1980
  } catch {
1558
1981
  // best-effort — never break the Stop hook
1559
1982
  }
1560
1983
  return result;
1561
1984
  }
1562
1985
 
1986
+ // ── touched-paths (scope the auto-commit to session-touched paths) ───────────
1987
+ //
1988
+ // The old commitWikiChanges swept the ENTIRE working tree: in a shared
1989
+ // multi-project vault with concurrent Claude Code sessions, another session's
1990
+ // staged/dirty files got committed and pushed by THIS session's Stop hook, and
1991
+ // the human-authored commit message was clobbered. The fix is to accumulate,
1992
+ // per session_id, the vault-relative paths this session actually touched, and
1993
+ // have commitWikiChanges commit only that scope.
1994
+ //
1995
+ // Sources that feed the accumulator:
1996
+ // - hypo-auto-stage.mjs (PostToolUse): every Write/Edit/MultiEdit to a file
1997
+ // under the vault.
1998
+ // - hypo-hot-rebuild.mjs (Stop, runs BEFORE auto-commit): hot.md and log.md,
1999
+ // which are hook-generated, not user Write/Edit — without this a scope
2000
+ // built from Write/Edit alone would drop them from the scoped commit.
2001
+ //
2002
+ // No session_id → never accumulate, and never fall back to a shared "default"
2003
+ // bucket: a path recorded under the wrong key could leak between sessions.
2004
+
2005
+ /** Directory holding one session's cache artifacts, incl. touched-paths.json. */
2006
+ function sessionCacheDir(hypoDir, sessionId) {
2007
+ return join(hypoDir, '.cache', 'sessions', sanitizeSessionId(sessionId));
2008
+ }
2009
+
2010
+ /** @returns {string} path to a session's accumulated touched-paths JSON array. */
2011
+ export function touchedPathsPath(hypoDir, sessionId) {
2012
+ return join(sessionCacheDir(hypoDir, sessionId), 'touched-paths.json');
2013
+ }
2014
+
2015
+ /**
2016
+ * Read the raw touched-paths JSON array off disk. Caller's responsibility to
2017
+ * hold the per-session lock first — this has no locking of its own.
2018
+ *
2019
+ * Absent and unreadable are different answers, and callers MUST branch on
2020
+ * the difference: a genuinely absent (or genuinely empty) file returns `[]`
2021
+ * — safe to treat as "nothing accumulated". A file that exists but fails to
2022
+ * read or parse returns `null` — NOT the same as empty. A caller that
2023
+ * conflates the two (codex FIX 1) and then does a set-difference clear on
2024
+ * `null`-as-`[]` will compute "nothing left" and delete the file outright,
2025
+ * silently losing every pending path to a transient I/O or parse error.
2026
+ *
2027
+ * @returns {string[]|null} the array, or `null` on a read/parse failure
2028
+ */
2029
+ function readTouchedPathsFile(path) {
2030
+ if (!existsSync(path)) return [];
2031
+ try {
2032
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
2033
+ return Array.isArray(parsed) ? parsed.filter((p) => typeof p === 'string' && p) : null;
2034
+ } catch {
2035
+ return null; // corrupt/unreadable — NOT the same as empty; see above
2036
+ }
2037
+ }
2038
+
2039
+ /**
2040
+ * Accumulate vault-relative touched paths for `sessionId`. Best-effort,
2041
+ * dedup-on-insert, JSON array (not delimiter-joined — survives non-ASCII and
2042
+ * any byte a filename can legally hold). No-op without a session_id: never
2043
+ * accumulate into a shared bucket.
2044
+ *
2045
+ * Read-merge-write is guarded by the per-session file lock (the SAME lock
2046
+ * `drainTouchedPaths` takes), so a PostToolUse hook accumulating concurrently
2047
+ * with the Stop-chain drain can never lose a path to either a lost update
2048
+ * (two writers merging from the same stale read) or a drain racing between
2049
+ * this function's read and its write.
2050
+ *
2051
+ * @param {string} hypoDir
2052
+ * @param {string|null|undefined} sessionId
2053
+ * @param {string|string[]} relPaths one or more vault-relative paths
2054
+ */
2055
+ export function recordTouchedPaths(hypoDir, sessionId, relPaths) {
2056
+ if (!sessionId) return;
2057
+ const incoming = (Array.isArray(relPaths) ? relPaths : [relPaths]).filter(
2058
+ (p) => typeof p === 'string' && p.length > 0,
2059
+ );
2060
+ if (incoming.length === 0) return;
2061
+ const path = touchedPathsPath(hypoDir, sessionId);
2062
+ try {
2063
+ withFileLock(path, () => {
2064
+ const current = readTouchedPathsFile(path);
2065
+ // A corrupt/unreadable file (current === null) is recovered from here,
2066
+ // not preserved: an accumulate is additive by nature (there is nothing
2067
+ // salvageable to merge with), so starting fresh from `incoming` is the
2068
+ // correct best-effort behavior — unlike clearTouchedPaths, where the
2069
+ // same `null` MUST NOT be treated as empty (see readTouchedPathsFile).
2070
+ const merged = new Set(current === null ? [] : current);
2071
+ for (const p of incoming) merged.add(p);
2072
+ atomicWriteShared(path, JSON.stringify([...merged]));
2073
+ });
2074
+ } catch {
2075
+ // best-effort: a hook must never fail a tool call over a cache write
2076
+ // (includes a lock-timeout — a dropped accumulation here is the same
2077
+ // fail-safe shape as every other best-effort cache write in this file).
2078
+ }
2079
+ }
2080
+
1563
2081
  /**
1564
- * Stage + commit every non-.hypoignore change in the wiki. Does NOT pull/push —
1565
- * remote sync stays in the auto-commit Stop hook (commit is local + cheap; sync is
2082
+ * Read and clear a session's accumulated touched paths in one step — "drain",
2083
+ * not "read", because the caller is expected to consume the WHOLE set
2084
+ * unconditionally. Kept for callers that genuinely want that (e.g. a
2085
+ * probe/inspection path); the Stop-chain auto-commit does NOT use this —
2086
+ * see commitTouchedPaths below, which holds ONE lock across a peek, the
2087
+ * commit itself, and a clear scoped to exactly what committed, so neither a
2088
+ * commit failure nor a same-path race loses anything.
2089
+ *
2090
+ * Guarded by the SAME per-session file lock every touched-paths mutation
2091
+ * takes: the read-then-remove here is mutually exclusive with a concurrent
2092
+ * accumulate or commitTouchedPaths call.
2093
+ *
2094
+ * A read/parse failure is NOT treated as an empty set to be cleared: like
2095
+ * clearTouchedPaths and commitTouchedPaths, a corrupt/unreadable file
2096
+ * (readTouchedPathsFile returns `null`) is left on disk untouched — never
2097
+ * deleted — so a transient I/O or parse error can't erase a set that a human
2098
+ * or a later pass could still recover. Drain returns `[]` in that case
2099
+ * (nothing safely consumable), but does not remove the file.
2100
+ *
2101
+ * @param {string} hypoDir
2102
+ * @param {string|null|undefined} sessionId
2103
+ * @returns {string[]} vault-relative paths, deduped; [] when absent, corrupt, or no session_id
2104
+ */
2105
+ export function drainTouchedPaths(hypoDir, sessionId) {
2106
+ if (!sessionId) return [];
2107
+ const path = touchedPathsPath(hypoDir, sessionId);
2108
+ try {
2109
+ return withFileLock(path, () => {
2110
+ const result = readTouchedPathsFile(path);
2111
+ if (result === null) return []; // corrupt/unreadable: leave the file for inspection, never delete
2112
+ try {
2113
+ rmSync(path, { force: true });
2114
+ } catch {
2115
+ // best-effort
2116
+ }
2117
+ return result;
2118
+ });
2119
+ } catch {
2120
+ // lock-timeout (or an unexpected lock error): fail closed to "nothing
2121
+ // drained" rather than risk reading concurrently with a writer. The set
2122
+ // stays on disk untouched, so it is still there for the next drain.
2123
+ return [];
2124
+ }
2125
+ }
2126
+
2127
+ /**
2128
+ * Read a session's accumulated touched paths WITHOUT clearing them. Kept as
2129
+ * a standalone probe for callers that just want to inspect the set; the
2130
+ * Stop-chain auto-commit does NOT call this on its own — see
2131
+ * commitTouchedPaths, which performs an equivalent internal read but holds
2132
+ * the lock through the commit and clear that follow it too.
2133
+ *
2134
+ * @param {string} hypoDir
2135
+ * @param {string|null|undefined} sessionId
2136
+ * @returns {string[]} vault-relative paths, deduped; [] when absent, corrupt,
2137
+ * no session_id, or a lock-timeout (fails closed to "nothing to commit" —
2138
+ * the set stays on disk, untouched, for the next Stop)
2139
+ */
2140
+ export function peekTouchedPaths(hypoDir, sessionId) {
2141
+ if (!sessionId) return [];
2142
+ const path = touchedPathsPath(hypoDir, sessionId);
2143
+ try {
2144
+ return withFileLock(path, () => {
2145
+ const result = readTouchedPathsFile(path);
2146
+ return result === null ? [] : result;
2147
+ });
2148
+ } catch {
2149
+ return [];
2150
+ }
2151
+ }
2152
+
2153
+ /**
2154
+ * Remove exactly `paths` from a session's touched-paths set — a set
2155
+ * difference, not a clear, and NOT a drain: any path a concurrent
2156
+ * PostToolUse (or Stop-chain generator) accumulated before this call is read
2157
+ * fresh under the SAME lock and therefore survives, because it was never in
2158
+ * `paths` to begin with.
2159
+ *
2160
+ * Called only after commitWikiChanges has ACTUALLY committed `paths` (or
2161
+ * confirmed there was nothing to commit) — never on a commit failure.
2162
+ *
2163
+ * Two failure modes this function must not turn into data loss (codex FIX 1
2164
+ * + FIX 2 review):
2165
+ *
2166
+ * - A read/parse failure on the touched-paths file (readTouchedPathsFile
2167
+ * returns `null`, NOT `[]`) must NOT be treated as "nothing left" — that
2168
+ * would make the set difference below compute an empty remainder and
2169
+ * DELETE the file outright on a transient I/O or parse error, losing
2170
+ * every pending path. On `null`, this function does nothing at all:
2171
+ * no write, no delete, the file is left exactly as it was.
2172
+ * - If this clear itself fails (lock-timeout, I/O) after a successful
2173
+ * read, the already-committed paths simply stay in the file: the next
2174
+ * Stop re-peeks them and re-runs commitWikiChanges, which is a clean
2175
+ * no-op (INTERSECT against a tree with no more changes at those paths
2176
+ * yields an empty scoped set). Over-retention is safe by construction —
2177
+ * it can never lose a path, only a commit failure (handled by leaving
2178
+ * the file alone entirely, see commitTouchedPaths) can.
2179
+ *
2180
+ * Standalone use of peekTouchedPaths + clearTouchedPaths as two SEPARATE
2181
+ * lock acquisitions still carries the same-path race codex FIX 2 describes
2182
+ * (a write between the two calls is indistinguishable from the one already
2183
+ * peeked, since the set only tracks path presence, not a generation/version
2184
+ * per path) — that is exactly why the Stop hook uses commitTouchedPaths
2185
+ * instead, which holds ONE lock across the whole peek→commit→clear window
2186
+ * so no write can land inside it at all.
2187
+ *
2188
+ * @param {string} hypoDir
2189
+ * @param {string|null|undefined} sessionId
2190
+ * @param {string[]} paths the exact paths that were just committed
2191
+ */
2192
+ export function clearTouchedPaths(hypoDir, sessionId, paths) {
2193
+ if (!sessionId) return;
2194
+ const toRemove = new Set((Array.isArray(paths) ? paths : []).filter(Boolean));
2195
+ if (toRemove.size === 0) return;
2196
+ const path = touchedPathsPath(hypoDir, sessionId);
2197
+ try {
2198
+ withFileLock(path, () => {
2199
+ const current = readTouchedPathsFile(path);
2200
+ if (current === null) return; // FIX 1: never delete/write on a read failure
2201
+ const remaining = current.filter((p) => !toRemove.has(p));
2202
+ if (remaining.length === 0) {
2203
+ try {
2204
+ rmSync(path, { force: true });
2205
+ } catch {
2206
+ // best-effort
2207
+ }
2208
+ } else {
2209
+ atomicWriteShared(path, JSON.stringify(remaining));
2210
+ }
2211
+ });
2212
+ } catch {
2213
+ // lock-timeout or unexpected error: leave the file as-is. Safe per the
2214
+ // over-retention argument above — the committed paths simply linger
2215
+ // until a later clear (or drain) removes them, at worst causing a
2216
+ // future no-op re-commit attempt, never a lost path.
2217
+ }
2218
+ }
2219
+
2220
+ /**
2221
+ * Peek a session's touched paths, run `commitFn(paths)` (expected to be
2222
+ * `commitWikiChanges` or an equivalent), and — only when it reports
2223
+ * `committed: true` — clear `paths` from the touched-paths set, ALL under
2224
+ * ONE hold of the per-session file lock (codex FIX 2). This is what the
2225
+ * Stop-chain auto-commit uses instead of calling peekTouchedPaths,
2226
+ * commitFn, and clearTouchedPaths as three separate steps.
2227
+ *
2228
+ * Holding one lock across peek → commit → clear (rather than acquiring and
2229
+ * releasing it three times, with the commit itself unlocked in between)
2230
+ * closes a same-path race: without it, a `recordTouchedPaths` call for a
2231
+ * path already in the just-peeked set could land in the window between the
2232
+ * commit and the clear. Since the touched-paths set only tracks path
2233
+ * PRESENCE (no per-path version/generation), that accumulate call is
2234
+ * indistinguishable from the one already peeked — the clear would remove it
2235
+ * anyway, silently orphaning a real edit that was never actually committed
2236
+ * (it landed on disk after `git commit` already ran, but the touched-paths
2237
+ * record of it just got wiped). With one continuous lock hold, that
2238
+ * accumulate call either fully precedes the peek (so it's included in THIS
2239
+ * commit, since commitWikiChanges reads live git status, not a cached
2240
+ * snapshot) or fully follows the clear (so it's untouched, waiting for the
2241
+ * next Stop) — there is no window where it can land in between.
2242
+ *
2243
+ * Lock order stays vault → per-session everywhere in this codebase (the
2244
+ * Stop hook takes the vault lock before calling this; accumulation only
2245
+ * ever takes the per-session lock, never the vault lock), so holding the
2246
+ * per-session lock for the whole commit here introduces no new ordering and
2247
+ * no deadlock risk.
2248
+ *
2249
+ * FIX 1 (read/parse failure) applies here too: a corrupt/unreadable
2250
+ * touched-paths file is never treated as empty. `commitFn` still runs (with
2251
+ * an empty scope — a safe no-op through commitWikiChanges), but nothing is
2252
+ * ever written to the corrupt file; it is left exactly as it was for a
2253
+ * human or a future recovery pass to look at.
2254
+ *
2255
+ * @param {string} hypoDir
2256
+ * @param {string|null|undefined} sessionId
2257
+ * @param {(paths: string[]) => {committed: boolean, [k: string]: unknown}} commitFn
2258
+ * @returns {{committed: boolean, [k: string]: unknown}} whatever `commitFn` returned,
2259
+ * or `{committed: false, reason: 'touched-paths-lock-timeout'}` if the lock
2260
+ * itself could not be acquired (commitFn never ran; the file is untouched)
2261
+ */
2262
+ export function commitTouchedPaths(hypoDir, sessionId, commitFn) {
2263
+ if (!sessionId) return commitFn([]);
2264
+ const path = touchedPathsPath(hypoDir, sessionId);
2265
+ try {
2266
+ return withFileLock(path, () => {
2267
+ const current = readTouchedPathsFile(path);
2268
+ if (current === null) {
2269
+ // FIX 1: a read/parse failure is not "empty" — commit nothing this
2270
+ // round (a safe no-op scope) and leave the corrupt file untouched,
2271
+ // rather than let a downstream clear compute "nothing left" and
2272
+ // delete it.
2273
+ return commitFn([]);
2274
+ }
2275
+ const result = commitFn(current);
2276
+ if (result && result.committed && current.length > 0) {
2277
+ // Still under the SAME lock acquired above: no recordTouchedPaths
2278
+ // call for this session can have landed since `current` was read
2279
+ // (it takes this exact lock too), so the set on disk right now is
2280
+ // EXACTLY `current` — clearing it needs no re-read or set
2281
+ // difference, just remove what we already know is the whole thing.
2282
+ try {
2283
+ rmSync(path, { force: true });
2284
+ } catch {
2285
+ // best-effort: the committed paths just linger on disk; the next
2286
+ // Stop re-peeks them and re-runs commitFn, a clean no-op.
2287
+ }
2288
+ }
2289
+ return result;
2290
+ });
2291
+ } catch {
2292
+ // Lock-timeout (or an unexpected lock error): never entered the
2293
+ // critical section, so commitFn never ran and nothing was peeked or
2294
+ // cleared. The touched-paths file is untouched on disk, and the next
2295
+ // Stop retries this session's commit from the same scope.
2296
+ return { committed: false, reason: 'touched-paths-lock-timeout' };
2297
+ }
2298
+ }
2299
+
2300
+ /**
2301
+ * The lock target both commit loci (hypo-auto-commit.mjs Stop hook,
2302
+ * crystallize.mjs --apply-session-close) hold while staging+committing (and,
2303
+ * for the Stop hook, syncing) the vault, so two concurrent sessions on a
2304
+ * shared vault never interleave `git add`/`git commit`/`git pull`/`git push`.
2305
+ * A stable, non-content path — withFileLock only ever touches its `.lock`
2306
+ * sibling, this file itself is never created.
2307
+ */
2308
+ export function vaultCommitLockTarget(hypoDir) {
2309
+ return join(hypoDir, '.cache', 'vault-commit');
2310
+ }
2311
+
2312
+ /** `projects/<slug>/...` → `<slug>`; anything else → its first path segment. */
2313
+ function projectOfPath(relPath) {
2314
+ const parts = relPath.split('/');
2315
+ if (parts[0] === 'projects' && parts.length > 1 && parts[1]) return parts[1];
2316
+ return parts[0] || relPath;
2317
+ }
2318
+
2319
+ /**
2320
+ * Stage + commit ONLY the caller-supplied `paths`, intersected with what is
2321
+ * actually changed on disk right now. Does NOT pull/push; remote
2322
+ * sync stays in the auto-commit Stop hook (commit is local + cheap; sync is
1566
2323
  * network + soft-fail). Shared by hypo-auto-commit.mjs and crystallize.mjs's
1567
2324
  * --apply-session-close path so the .hypoignore staging filter cannot diverge
1568
2325
  * between the two commit loci.
1569
2326
  *
1570
- * "Nothing to commit" (clean tree, or only .hypoignore'd changes) is SUCCESS, not
1571
- * failure — the caller's tree is already in the committed state it wanted.
2327
+ * The caller supplies the scope; this function never re-derives it from the
2328
+ * whole tree. `paths` absent/empty is a clean no-op (`scoped: 0`), not an
2329
+ * error and not a whole-tree fallback — this is how a caller with nothing to
2330
+ * contribute (e.g. no session_id, so nothing was accumulated) skips cleanly.
2331
+ *
2332
+ * The authoritative scope is INTERSECT(paths, currently-changed): a stale
2333
+ * entry (already committed elsewhere, or never actually changed) is dropped
2334
+ * silently rather than erroring. `.hypoignore` filtering, the staged
2335
+ * re-derivation, the commit-message count, and the final commit all use this
2336
+ * SAME scoped set — no step here may widen back to whole-tree, or another
2337
+ * session's dirty/staged files could slip back in through any one of them.
2338
+ *
2339
+ * "Nothing to commit" (empty scope, or only .hypoignore'd changes) is
2340
+ * SUCCESS, not failure — the caller's tree is already in the state it wanted.
1572
2341
  *
1573
2342
  * @param {string} hypoDir
1574
- * @returns {{committed: boolean, reason?: string}} committed:true when a commit was
1575
- * created OR nothing needed committing; committed:false (with reason) on a real
1576
- * failure: not a git repo, or git status/add/commit erroring.
2343
+ * @param {string[]} [paths] vault-relative paths this caller wrote/owns this close
2344
+ * @returns {{committed: boolean, scoped?: number, reason?: string}} committed:true
2345
+ * when a commit was created OR nothing needed committing (scoped:0 in the
2346
+ * latter case); committed:false (with reason) on a real failure: not a git
2347
+ * repo, or git status/add/commit erroring.
1577
2348
  */
1578
- export function commitWikiChanges(hypoDir) {
2349
+ export function commitWikiChanges(hypoDir, paths) {
1579
2350
  const git = (...args) =>
1580
2351
  spawnSync('git', ['-C', hypoDir, ...args], { encoding: 'utf-8', timeout: 30000 });
1581
2352
  if (git('rev-parse', '--is-inside-work-tree').status !== 0)
1582
2353
  return { committed: false, reason: `not a git repository: ${hypoDir}` };
1583
- // `-z`: NUL-separated records with verbatim paths — no surrounding quotes and
1584
- // no octal escaping, so non-ASCII paths (Korean page names are normal input
1585
- // here) survive intact. Without it, `core.quotepath=true` (the default) yields
1586
- // `"pages/\355\225\234\352\270\200.md"` and the old quote-strip parser fed that
1587
- // literal, non-existent path to `git add` — failing the whole commit.
2354
+
2355
+ const supplied = new Set(
2356
+ (Array.isArray(paths) ? paths : []).filter((p) => typeof p === 'string' && p.length > 0),
2357
+ );
2358
+ if (supplied.size === 0) return { committed: true, scoped: 0 };
2359
+
1588
2360
  // `-z`: NUL-separated records with verbatim paths — no surrounding quotes and
1589
2361
  // no octal escaping, so non-ASCII paths (Korean page names are normal input
1590
2362
  // here) survive intact. Without it, `core.quotepath=true` (the default) yields
@@ -1596,41 +2368,85 @@ export function commitWikiChanges(hypoDir) {
1596
2368
  // `.hypoignore` is the project privacy boundary. `git add -A` ignores it, so
1597
2369
  // enumerate changed paths, drop ignored ones, then stage explicitly.
1598
2370
  const ignorePatterns = loadHypoIgnore(hypoDir);
1599
- const paths = [];
2371
+ const scoped = []; // pathspec for `git add -A` — worktree/index paths only
2372
+ const commitScope = []; // pathspec for the final diff/commit --only (superset)
1600
2373
  const records = (porcelain.stdout || '').split('\0');
1601
2374
  for (let i = 0; i < records.length; i++) {
1602
2375
  const rec = records[i];
1603
2376
  if (!rec) continue;
1604
2377
  const xy = rec.slice(0, 2);
1605
2378
  const file = rec.slice(3); // `XY <path>`; the destination path for a rename/copy
2379
+ const isRename = xy[0] === 'R' || xy[1] === 'R';
1606
2380
  // A rename OR copy emits two records (`to\0from`); consume the trailing
1607
2381
  // `from`. Copy `C` records only appear under `status.renames=copies`, but
1608
2382
  // when they do, missing this skip feeds the `from` path to `git add` as a
1609
2383
  // bogus pathspec — the exact auto-commit failure this parser fixes.
1610
- if (xy[0] === 'R' || xy[1] === 'R' || xy[0] === 'C' || xy[1] === 'C') i++;
2384
+ let fromFile = null;
2385
+ if (isRename || xy[0] === 'C' || xy[1] === 'C') {
2386
+ i++;
2387
+ fromFile = records[i] || null;
2388
+ }
1611
2389
  if (!file) continue;
2390
+ if (!supplied.has(file)) continue; // out of this caller's scope
1612
2391
  if (ignorePatterns.length > 0 && isIgnored(join(hypoDir, file), hypoDir, ignorePatterns))
1613
2392
  continue;
1614
- paths.push(file);
2393
+ scoped.push(file);
2394
+ commitScope.push(file);
2395
+ // A rename's `from` path is the SAME change as its destination — without
2396
+ // it, `git commit --only` on the destination alone commits the addition
2397
+ // but leaves the source's deletion staged as residue (a git --only
2398
+ // quirk, verified). It is NOT added to `git add -A` (the deletion is
2399
+ // already staged by the rename itself, and its worktree entry is gone —
2400
+ // `git add -A -- <a gone-and-already-staged path>` errors "did not match
2401
+ // any files"), only to the commit's pathspec. A copy's `from` is
2402
+ // independently-owned, still-existing content, so it is NOT auto-pulled
2403
+ // in at all: the caller must name it explicitly if it wants it in scope.
2404
+ if (isRename && fromFile) commitScope.push(fromFile);
1615
2405
  }
1616
- if (paths.length > 0) {
1617
- const add = git('add', '--', ...paths);
2406
+ if (scoped.length === 0 && commitScope.length === 0) return { committed: true, scoped: 0 };
2407
+
2408
+ if (scoped.length > 0) {
2409
+ const add = git('add', '-A', '--', ...scoped);
1618
2410
  if (add.status !== 0)
1619
2411
  return {
1620
2412
  committed: false,
1621
2413
  reason: `git add failed: ${(add.stderr || '').trim() || 'unknown'}`,
1622
2414
  };
1623
2415
  }
1624
- const staged = git('diff', '--cached', '--name-only').stdout?.trim() || '';
1625
- if (!staged) return { committed: true }; // nothing to commit = success (idempotent)
2416
+
2417
+ // Re-derive from what actually landed in the index, bounded by the SAME
2418
+ // pathspec (commitScope, the rename-aware superset of `scoped`) — this step
2419
+ // must not widen back to whole-tree either, or another session's already-
2420
+ // staged file would slip into the commit here.
2421
+ const staged = git('diff', '--cached', '--name-only', '-z', '--', ...commitScope);
2422
+ const stagedFiles = (staged.stdout || '').split('\0').filter(Boolean);
2423
+ if (stagedFiles.length === 0) return { committed: true, scoped: 0 };
2424
+
2425
+ const projects = new Set(stagedFiles.map(projectOfPath));
1626
2426
  const today = new Date().toISOString().slice(0, 10);
1627
- const commit = git('commit', '-m', `auto: ${today} wiki update`);
2427
+ const msg = `auto: ${today} wiki update (${stagedFiles.length} paths across ${projects.size} projects)`;
2428
+
2429
+ // `git commit --only -- <paths>` (first use of --only in this repo): commits
2430
+ // ONLY the staged changes under this pathspec, ignoring anything else
2431
+ // staged in the index — e.g. another session's own staged-but-uncommitted
2432
+ // work sharing this working tree. A bare `git commit -m` would sweep in
2433
+ // every staged path, defeating the whole point of the scoped set above.
2434
+ //
2435
+ // Pathspec is `commitScope`, NOT `stagedFiles`: `git diff --name-only`
2436
+ // collapses a rename to its destination alone (rename detection folds the
2437
+ // pair into one line), so re-deriving the commit's own pathspec from that
2438
+ // output would silently drop the `from` path again and reproduce the
2439
+ // exact `--only`-leaves-the-deletion-staged residue this function's rename
2440
+ // handling exists to avoid (verified). `stagedFiles` still governs the
2441
+ // empty-scope check and the N/M count above — both correct as "how many
2442
+ // logical changes", where a rename is rightly one.
2443
+ const commit = git('commit', '--only', '-m', msg, '--', ...commitScope);
1628
2444
  if (commit.status !== 0)
1629
2445
  return {
1630
2446
  committed: false,
1631
2447
  reason: `git commit failed: ${(commit.stderr || '').trim() || 'unknown'}`,
1632
2448
  };
1633
- return { committed: true };
2449
+ return { committed: true, scoped: stagedFiles.length };
1634
2450
  }
1635
2451
 
1636
2452
  /**
@@ -1661,6 +2477,134 @@ export function clearSyncState(hypoDir) {
1661
2477
  }
1662
2478
  }
1663
2479
 
2480
+ // ── sync-last-success ────────────────────────────────────────
2481
+ // `.cache/sync-last-success.json` is a single JSON object, PER-OPERATION:
2482
+ // { "pull": {"timestamp": "<ISO>", "host": "<os.hostname()>"},
2483
+ // "push": {"timestamp": "<ISO>", "host": "<...>"} }
2484
+ // Either key may be absent (pull-only or push-only history). Deliberately
2485
+ // separate from sync-state.json: that file is failure-only and gets wiped
2486
+ // wholesale on recovery (clearSyncState), so a success record living there
2487
+ // would be erased by the very thing it is meant to survive. syncRemote()
2488
+ // records here on a successful pull/push; session-start's independent
2489
+ // `git pull --ff-only` records a pull here too, so doctor never reports
2490
+ // "never synced" right after a healthy startup pull. doctor reads it via
2491
+ // readSyncLastSuccess; schema + parsing live here only.
2492
+ //
2493
+ // Scope: `.cache/` is gitignored (templates/gitignore), same as
2494
+ // sync-state.json — this file never syncs across machines, so there is no
2495
+ // cross-machine merge to protect. The lock below only has to cover the
2496
+ // same-machine case: two concurrent processes on one machine (a pull-writer
2497
+ // and a push-writer, or two overlapping sessions). `host` is kept per record
2498
+ // purely for provenance (which machine last recorded the op), not because a
2499
+ // remote write could ever land here.
2500
+
2501
+ /** @returns {string} path to the sync-last-success JSON file for a wiki root. */
2502
+ function syncLastSuccessPath(hypoDir) {
2503
+ return join(hypoDir, '.cache', 'sync-last-success.json');
2504
+ }
2505
+
2506
+ /**
2507
+ * A valid last-success record: `{timestamp: string, host: string}`. Anything
2508
+ * else (wrong type, missing field, non-object) is malformed.
2509
+ * @param {unknown} v
2510
+ * @returns {boolean}
2511
+ */
2512
+ function isValidSyncSuccessRecord(v) {
2513
+ return (
2514
+ v !== null &&
2515
+ typeof v === 'object' &&
2516
+ !Array.isArray(v) &&
2517
+ typeof v.timestamp === 'string' &&
2518
+ v.timestamp.trim().length > 0 &&
2519
+ typeof v.host === 'string' &&
2520
+ v.host.trim().length > 0
2521
+ );
2522
+ }
2523
+
2524
+ /**
2525
+ * Read last-success records. A missing file means "never synced" (not an
2526
+ * error) — the caller distinguishes that from a parse failure via
2527
+ * `parseError`. A present `pull`/`push` field that does not match the
2528
+ * `{timestamp, host}` shape (including an empty/whitespace-only timestamp or
2529
+ * host — a technically-typed but content-free record) is dropped from `data`
2530
+ * (never surfaced as if it were a real record) AND flags `parseError: true`,
2531
+ * so the caller warns ("cannot parse ... inspect manually") instead of
2532
+ * silently rendering `undefined` or an empty value — same corrupt-file
2533
+ * handling as sync-state.json. An unrecognized top-level key (anything other
2534
+ * than `pull`/`push`) likewise flags the whole file as corrupt: this schema
2535
+ * has exactly two legal keys, so a third one is evidence of a hand-edit or a
2536
+ * future/foreign writer, not a shape this reader should quietly tolerate.
2537
+ *
2538
+ * @param {string} hypoDir
2539
+ * @returns {{data: {pull?: {timestamp: string, host: string}, push?: {timestamp: string, host: string}}, parseError: boolean}}
2540
+ */
2541
+ export function readSyncLastSuccess(hypoDir) {
2542
+ const path = syncLastSuccessPath(hypoDir);
2543
+ if (!existsSync(path)) return { data: {}, parseError: false };
2544
+ try {
2545
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
2546
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
2547
+ return { data: {}, parseError: true };
2548
+ let malformed = Object.keys(parsed).some((k) => k !== 'pull' && k !== 'push');
2549
+ const data = {};
2550
+ for (const op of ['pull', 'push']) {
2551
+ if (parsed[op] === undefined) continue;
2552
+ if (isValidSyncSuccessRecord(parsed[op])) data[op] = parsed[op];
2553
+ else malformed = true; // drop the bad field; flag the file as corrupt
2554
+ }
2555
+ return { data, parseError: malformed };
2556
+ } catch {
2557
+ return { data: {}, parseError: true };
2558
+ }
2559
+ }
2560
+
2561
+ /**
2562
+ * Record a successful pull or push. Concurrency-safe on the same machine:
2563
+ * takes the vault file lock on the target path, re-reads the CURRENT file
2564
+ * under the lock, updates only the given op's field (the other op's existing
2565
+ * value survives — a same-machine concurrent pull-writer and push-writer must
2566
+ * not erase each other), then commits via temp-write + rename so a crash or a
2567
+ * concurrent read never sees a half-written file. `.cache/` is gitignored, so
2568
+ * this file never syncs across machines — there is no cross-machine case to
2569
+ * protect here. A pre-existing but unparseable file, or a sibling field that
2570
+ * does not match `{timestamp, host}` (including an empty/whitespace-only
2571
+ * value) or that carries an unrecognized key, is dropped rather than carried
2572
+ * forward (never preserve garbage into a freshly-written record) — the same
2573
+ * `isValidSyncSuccessRecord` predicate readSyncLastSuccess uses.
2574
+ *
2575
+ * Lock acquisition is best-effort — a timeout (or any other failure) is
2576
+ * swallowed, same as appendSyncFailure, since a failed success-log must never
2577
+ * break the caller (Stop hook / SessionStart).
2578
+ *
2579
+ * @param {string} hypoDir
2580
+ * @param {'pull'|'push'} op
2581
+ */
2582
+ export function recordSyncSuccess(hypoDir, op) {
2583
+ try {
2584
+ const path = syncLastSuccessPath(hypoDir);
2585
+ withFileLock(path, () => {
2586
+ let current = {};
2587
+ try {
2588
+ if (existsSync(path)) {
2589
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
2590
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
2591
+ for (const k of ['pull', 'push']) {
2592
+ if (isValidSyncSuccessRecord(parsed[k])) current[k] = parsed[k];
2593
+ }
2594
+ }
2595
+ }
2596
+ } catch {
2597
+ // corrupt existing file: overwrite with a fresh object rather than
2598
+ // carry the corruption forward.
2599
+ }
2600
+ current[op] = { timestamp: new Date().toISOString(), host: hostname() };
2601
+ atomicWriteShared(path, JSON.stringify(current, null, 2) + '\n');
2602
+ });
2603
+ } catch {
2604
+ // best-effort: lock timeout or write failure must never break the caller
2605
+ }
2606
+ }
2607
+
1664
2608
  // ── auto-project suggestion ────────────────────────────────────────
1665
2609
  // `.cache/project-suggestions.json` is a single JSON object:
1666
2610
  // { "skips": [{cwd, declined_at, reason}], "cooldowns": {"<cwd>": "<iso>"} }
@@ -1960,11 +2904,11 @@ export function clearClearMarker(hypoDir) {
1960
2904
  // Writer authority lives in crystallize, NOT this hook: the hook only checks
1961
2905
  // presence. See amendment 2026-05-19 Q2 for the split rationale.
1962
2906
 
1963
- const SESSION_CLOSED_MARKER_STALE_MS = 7 * 24 * 60 * 60 * 1000;
2907
+ export const SESSION_CLOSED_MARKER_STALE_MS = 7 * 24 * 60 * 60 * 1000;
1964
2908
 
1965
2909
  /** Sanitize session_id for filesystem use — Claude session_ids are UUIDs but
1966
2910
  * defend against accidental path traversal regardless. */
1967
- function sanitizeSessionId(sessionId) {
2911
+ export function sanitizeSessionId(sessionId) {
1968
2912
  return String(sessionId)
1969
2913
  .replace(/[^A-Za-z0-9._-]/g, '_')
1970
2914
  .slice(0, 128);
@@ -3120,6 +4064,114 @@ export function isClosePattern(text) {
3120
4064
  return [...krPatterns, ...enPatterns].some((re) => re.test(text));
3121
4065
  }
3122
4066
 
4067
+ // ── close ARTIFACTS, not the marker (issue: close gate lives on one writer) ──
4068
+ //
4069
+ // hasUserCloseSignal/isClosePattern answer "did the user ask to close" — the
4070
+ // input side of the gate. This answers a different question: "does this file
4071
+ // or commit message already READ as closed to a human", independent of
4072
+ // whether any marker writer ever ran. The 2026-07-28 incident produced a
4073
+ // closing session-state.md heading, a rewritten hot.md, and a close-worded
4074
+ // commit WITHOUT writing a session-closed marker at all — the hard gate on
4075
+ // the marker writer never fired because the model never called it. Closing
4076
+ // is a set of user-visible artifacts, not one internal file.
4077
+ //
4078
+ // Narrowed scope — this is a PARTIAL defense, not the completed artifact-set
4079
+ // gate: hot.md's REPLACEMENT is a diff against the prior version, which a
4080
+ // pure function taking only current content cannot see. This only catches a
4081
+ // hot.md that carries close vocabulary in its own bold heading — a hot.md
4082
+ // rewritten with a closing narrative that happens not to use 마감/종료
4083
+ // literally (as the incident's own hot.md rewrite did) will NOT trip this
4084
+ // signal. That is a real, known false-negative, not a corner this slice
4085
+ // closes: catching it needs a diff-aware check (comparing against the prior
4086
+ // committed hot.md, or a PreToolUse guard that sees the edit as it happens),
4087
+ // which is future work, not something reusing isClosePattern's heuristics
4088
+ // would fix either. The session-state heading and commit-message signals
4089
+ // still catch the one incident on record, so today's gap is documented, not
4090
+ // silent — but it is a gap, not a boundary this slice was designed to hold.
4091
+ //
4092
+ // A close word used as a NOUN-MODIFIER is not an announcement — "마감
4093
+ // 조건을/여부/로직/절차/정책" all describe something ABOUT closing, not a close
4094
+ // that happened. Enumerating the modifiers (blacklist, round 1) and then the
4095
+ // verb suffixes that ARE an announcement (whitelist, round 2) both kept
4096
+ // finding new words each review round — neither converges, because both are
4097
+ // open lexical classes. The convergent rule is a WORD-BOUNDARY, not a word
4098
+ // list: Korean verb conjugation attaches directly with no space (마감했다,
4099
+ // 마감되었습니다, 마감했습니다, 마감됨 — see the corpus in
4100
+ // tests/close-signals.test.mjs), while a noun-modifier is a SEPARATE word
4101
+ // after a space (마감 조건, 마감 정책, 종료 여부, 종료 절차). So: a close word
4102
+ // followed immediately (no space) by more Hangul is a conjugation and
4103
+ // announces a close; a close word followed by whitespace THEN Hangul is a
4104
+ // modifier and does not. `CLOSE_WORD_TAIL` consumes the (possibly empty)
4105
+ // directly-attached conjugation run, then requires the close word to be
4106
+ // effectively the LAST content in its heading: only a parenthetical, ":" +
4107
+ // trailing narrative, terminal punctuation, or the bold-heading's end may
4108
+ // follow — a bare space-separated Hangul word after it fails to match any of
4109
+ // those and rejects. Known accepted limit: a same-word-no-space compound like
4110
+ // "마감일" (deadline-date, a noun) would match — over the FN/FP asymmetry this
4111
+ // check is built on (a missed real close is the exact failure mode it exists
4112
+ // to catch; a stray warn is mild noise), that's the accepted direction.
4113
+ const CLOSE_WORD_TAIL = '[가-힣]*(?:\\s*:[^*\\n]*|(?:\\([^)]*\\))?[.,]?\\s*)';
4114
+ const SESSION_STATE_CLOSE_HEADING = new RegExp(
4115
+ `\\*\\*(\\d{4}-\\d{2}-\\d{2})[^*\\n]*?마감${CLOSE_WORD_TAIL}\\*\\*`,
4116
+ );
4117
+ const HOT_CLOSE_NARRATIVE = new RegExp(
4118
+ `\\*\\*(\\d{4}-\\d{2}-\\d{2})[^*\\n]*?(?:마감|세션\\s*종료)${CLOSE_WORD_TAIL}\\*\\*`,
4119
+ );
4120
+ // EN: requires the CLOSE's object to actually be "session" ("close the
4121
+ // session" / "close the Nth session" — an ORDINAL or digit-ordinal, the only
4122
+ // forms a real close commit uses), not any noun ("close the database
4123
+ // session", "close the browser session" are technical commits, not a
4124
+ // session-close). KR: same word-boundary rule as the heading patterns above,
4125
+ // applied as a lookahead only (a commit subject isn't bold-wrapped, so there
4126
+ // is no terminal structure to consume into) — reject only when a bare SPACE
4127
+ // separates the close word from a following Hangul word; a directly-attached
4128
+ // conjugation (세션을 종료했다) still matches. "을/를" is the object particle
4129
+ // Korean puts between "세션" and its verb.
4130
+ const ORDINAL =
4131
+ '(?:\\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|' +
4132
+ 'eleventh|twelfth|thirteenth|fourteenth|fifteenth|sixteenth|seventeenth|eighteenth|nineteenth|twentieth)';
4133
+ const CLOSE_COMMIT_MESSAGE = new RegExp(
4134
+ `\\b(?:session:\\s*)?close(?:s|d)?\\s+(?:the|this)\\s+(?:${ORDINAL}\\s+)?session\\b|` +
4135
+ `세션(?:을|를)?\\s*(?:마무리|마감|종료)(?!\\s+[가-힣])`,
4136
+ 'i',
4137
+ );
4138
+
4139
+ /**
4140
+ * Pure predicate: is this file content, or this commit message, a
4141
+ * session-close ARTIFACT (something a human would read as "this session was
4142
+ * closed")? Never reads the filesystem — callers own IO. `path`'s basename
4143
+ * selects which pattern applies (`session-state.md` vs `hot.md`); pass
4144
+ * `commitMessage` instead for a git log entry.
4145
+ *
4146
+ * Consumed today by doctor's post-hoc check: an artifact with no matching
4147
+ * session-closed marker for its date is a signature of a hand-made close
4148
+ * that never went through the gate. Meant to also back a future PreToolUse
4149
+ * guard on the same definition, so the two defenses can't drift apart on
4150
+ * what "close" means.
4151
+ *
4152
+ * @param {{path?: string|null, content?: string|null, commitMessage?: string|null}} input
4153
+ * @returns {{matched: boolean, kind: string|null, date: string|null}} `date`
4154
+ * is the YYYY-MM-DD captured from the artifact's own heading, or null for a
4155
+ * commit-message match (the caller already has the commit's date).
4156
+ */
4157
+ export function detectSessionCloseArtifact({ path = null, content = null, commitMessage = null } = {}) {
4158
+ if (typeof commitMessage === 'string' && CLOSE_COMMIT_MESSAGE.test(commitMessage)) {
4159
+ return { matched: true, kind: 'commit-message', date: null };
4160
+ }
4161
+ if (typeof path === 'string' && typeof content === 'string') {
4162
+ const base = path.split(/[\\/]/).pop();
4163
+ if (base === 'session-state.md') {
4164
+ const m = SESSION_STATE_CLOSE_HEADING.exec(content);
4165
+ if (m) return { matched: true, kind: 'session-state-heading', date: m[1] };
4166
+ }
4167
+ if (base === 'hot.md') {
4168
+ const m = HOT_CLOSE_NARRATIVE.exec(content);
4169
+ if (m) return { matched: true, kind: 'hot-narrative', date: m[1] };
4170
+ }
4171
+ }
4172
+ return { matched: false, kind: null, date: null };
4173
+ }
4174
+
3123
4175
  /**
3124
4176
  * Resolve a session's transcript path from its (globally-unique) session id by
3125
4177
  * globbing every Claude project dir: ~/.claude/projects/<slug>/<id>.jsonl.
@@ -3181,6 +4233,9 @@ export function resolveTranscriptBySessionId(
3181
4233
  * • INVALIDATE a fresh user intent that expires the lease: any other genuine
3182
4234
  * user text, `/clear`, `popAll`, a non-close queued_command, a
3183
4235
  * non-close AskUserQuestion selection.
4236
+ * • NEUTRAL additionally: a typed `apply-proposals <nonce>` whose nonce this
4237
+ * transcript shows `proposal challenge` minting (see "the approval
4238
+ * line" below).
3184
4239
  * • NEUTRAL everything the model can produce or the harness injects: system/
3185
4240
  * sdk replay, isMeta bodies, sidechain, interruptedMessageId
3186
4241
  * companions, assistant, tool_result, task-notification.
@@ -3193,9 +4248,45 @@ export function resolveTranscriptBySessionId(
3193
4248
  * known limit (no leaf pointer exists to resolve it — see the branch note on the
3194
4249
  * function), mitigated by the lease.
3195
4250
  *
4251
+ * THE APPROVAL LINE IS NOT A CHANGE OF MIND. The lease exists to catch a user who
4252
+ * changed their mind, and it also caught the user for doing what the close
4253
+ * procedure told them to do. `proposal challenge` instructs the user to type
4254
+ * `apply-proposals <nonce>`, which can never be a close phrase, so typing it
4255
+ * expired the close grant given a turn earlier (measured 2026-08-06: the close
4256
+ * needed three approval round trips because of it). Two gates read one transcript
4257
+ * under two rules, and passing one broke the other.
4258
+ *
4259
+ * So one carve-out: a user message that IS the approval line, for a nonce this
4260
+ * transcript shows being minted, is NEUTRAL. It never grants; a lease that was not
4261
+ * already live stays dead. The mint has to be correlated, not merely present:
4262
+ * `collectMinted` reads only a tool_result correlated to a Bash tool_use, and only
4263
+ * when the surrounding challenge framing is there too, so a hex the model typed in
4264
+ * its own prose (or any other tool's output) is not a mint. Order is part of it:
4265
+ * the set fills as the walk goes, so a message can never mint the nonce it spends.
4266
+ * An unminted hex is ordinary text and still expires the lease.
4267
+ *
4268
+ * What this does NOT cover: an AskUserQuestion answer during the close procedure
4269
+ * (the skill's Step 1a reflections) still expires the lease. A carve-out was
4270
+ * written for it and withdrawn, because "the answer does not read as a retraction"
4271
+ * is fail-open on an open class of phrasings, and this repo routes an unknown value
4272
+ * to the cautious branch. Recognizing a close-procedure answer POSITIVELY needs a
4273
+ * marker on the question, and the model authors the question. The round trip stays.
4274
+ *
3196
4275
  * Threat model: an honest-but-drifting model that does not forge the
3197
4276
  * transcript. This is a safety interlock, not an authorization boundary — a model
3198
- * that forges records is out of scope and documented so.
4277
+ * that forges records is out of scope and documented so. The carve-out does not
4278
+ * move that boundary: it only PRESERVES a grant the user already gave, so the model
4279
+ * still cannot manufacture one. The residual it does carry: a model that runs an
4280
+ * arbitrary Bash command can print the challenge framing itself and plant a mint.
4281
+ * That buys it nothing on its own, because the user still has to send the approval
4282
+ * line, and the result is neutrality rather than a grant.
4283
+ *
4284
+ * A command invocation is NOT a channel here. `/hypo:crystallize` typed by the user
4285
+ * was accepted as a grant for one review round and removed: the harness records a
4286
+ * model-issued Skill call as the same non-meta `<command-name>` user record
4287
+ * (verified against Claude Code 2.1.243's `processPromptSlashCommand`), so the
4288
+ * model could have closed the session by calling its own skill. The premise that a
4289
+ * command tag proves a human typed it is false.
3199
4290
  *
3200
4291
  * Fail-closed: any read/parse error, or an unresolvable branch, → false.
3201
4292
  */
@@ -3292,9 +4383,42 @@ export function hasUserCloseSignal(transcriptPath) {
3292
4383
  // staleness limit, mitigated by the lease: any later live user intent, on any
3293
4384
  // branch, still expires it.
3294
4385
  const askIds = new Set();
4386
+ // Bash tool_use ids, so a mint can be tied to a command that actually ran rather
4387
+ // than to any string in the file. Filled in the same content scan as askIds.
4388
+ const bashIds = new Set();
3295
4389
  let granted = false;
4390
+ // The nonces this transcript shows `proposal challenge` minting. Producer, not
4391
+ // just presence: the hex has to arrive in a NON-error tool_result of a Bash
4392
+ // tool_use, wrapped in the challenge's own framing. Model prose carrying a
4393
+ // plausible hex, an isMeta/system body, and any other tool's output all fail
4394
+ // that, which matters because a mint neutralizes the user's next message. The
4395
+ // set fills as the walk goes, so a message cannot mint the nonce it spends.
4396
+ const mintedNonces = new Set();
4397
+ const challengeMint = new RegExp(
4398
+ `must type this line in the conversation:\\s*${APPROVAL_PHRASE} ([a-f0-9]{32,})\\s*Then run: hypomnema proposal resolve`,
4399
+ 'g',
4400
+ );
4401
+ const approvalLine = new RegExp(`^${APPROVAL_PHRASE}\\s+([a-f0-9]{32,})$`);
4402
+ const collectMinted = (o) => {
4403
+ const c = (o.message ?? o).content;
4404
+ if (!Array.isArray(c)) return;
4405
+ for (const b of c) {
4406
+ if (!b || typeof b !== 'object') continue;
4407
+ if (b.type !== 'tool_result' || !b.tool_use_id || !bashIds.has(b.tool_use_id)) continue;
4408
+ if (b.is_error === true) continue;
4409
+ const text = typeof b.content === 'string' ? b.content : JSON.stringify(b.content);
4410
+ if (typeof text !== 'string' || !text.includes(APPROVAL_PHRASE)) continue;
4411
+ for (const m of text.matchAll(challengeMint)) mintedNonces.add(m[1]);
4412
+ }
4413
+ };
3296
4414
 
3297
4415
  for (const o of recs) {
4416
+ // Genuine user text of this record, or null when the record is on a channel
4417
+ // the model can reach. Computed once here: the mint scan below is the exact
4418
+ // complement of it (mint from everything that is NOT the user's own text).
4419
+ const userText = eventUserText(o);
4420
+ if (userText == null) collectMinted(o);
4421
+
3298
4422
  // Queue operations. The queue carries no correlation key (measured), so the
3299
4423
  // ENQUEUE content is the decision — not a later contentless dequeue, which
3300
4424
  // would need pairing we cannot do. Reading the enqueue also keeps the live
@@ -3344,25 +4468,29 @@ export function hasUserCloseSignal(transcriptPath) {
3344
4468
  }
3345
4469
 
3346
4470
  // Record AskUserQuestion tool_use ids (assistant record, always precedes its
3347
- // answer in line order).
4471
+ // answer in line order). Bash ids ride along in the same scan, for the mint
4472
+ // correlation above.
3348
4473
  const content = (o.message ?? o).content;
3349
4474
  if (Array.isArray(content)) {
3350
4475
  for (const b of content) {
3351
- if (
3352
- b &&
3353
- typeof b === 'object' &&
3354
- b.type === 'tool_use' &&
3355
- b.name === 'AskUserQuestion' &&
3356
- b.id
3357
- )
3358
- askIds.add(b.id);
4476
+ if (!b || typeof b !== 'object' || b.type !== 'tool_use' || !b.id) continue;
4477
+ if (b.name === 'AskUserQuestion') askIds.add(b.id);
4478
+ else if (b.name === 'Bash') bashIds.add(b.id);
3359
4479
  }
3360
4480
  }
3361
4481
 
3362
- // Genuine user text → grant on a close phrase, invalidate on anything else.
3363
- const text = eventUserText(o);
3364
- if (text != null && text !== '') {
3365
- granted = isClosePattern(text);
4482
+ // Genuine user text → grant on a close phrase, invalidate on anything else,
4483
+ // minus the one carve-out for what the product itself asked the user to send.
4484
+ if (userText != null && userText !== '') {
4485
+ const spend = approvalLine.exec(userText.trim());
4486
+ if (spend && mintedNonces.has(spend[1])) {
4487
+ // The approval line `proposal challenge` tells the user to type, bound to a
4488
+ // nonce this transcript minted. Neutral, never a grant: an untouched
4489
+ // `granted` that was false stays false. An unminted hex is ordinary text and
4490
+ // falls through to the invalidating branch below.
4491
+ continue;
4492
+ }
4493
+ granted = isClosePattern(userText);
3366
4494
  continue;
3367
4495
  }
3368
4496