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.
@@ -13,17 +13,24 @@
13
13
  */
14
14
 
15
15
  import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
16
- import { join, relative, extname } from 'path';
16
+ import { join, relative, extname, dirname } from 'path';
17
17
  import { homedir } from 'os';
18
18
  import { spawnSync } from 'child_process';
19
19
  import { fileURLToPath } from 'url';
20
20
  import { resolveHypoRoot, expandHome } from './lib/hypo-root.mjs';
21
21
  import { loadHypoIgnore, isScanIgnored } from './lib/hypo-ignore.mjs';
22
+ import { readRenameMarker, renameMarkerPath, RENAME_MARKER_REL } from './lib/rename-marker.mjs';
23
+ import { resolveGitHooksDir } from './lib/git-hooks-dir.mjs';
22
24
  import { parseFrontmatter } from './lib/frontmatter.mjs';
23
25
  import {
24
26
  readSyncState,
27
+ readSyncLastSuccess,
28
+ classifySyncOp,
25
29
  projectSuggestionsPath,
26
30
  collectProjectWorkingDirs,
31
+ detectSessionCloseArtifact,
32
+ localAndUtcDates,
33
+ SESSION_CLOSED_MARKER_STALE_MS,
27
34
  } from '../hooks/hypo-shared.mjs';
28
35
  import { listProposals } from '../hooks/proposal-store.mjs';
29
36
  import {
@@ -450,20 +457,168 @@ function checkGit(hypoDir) {
450
457
  warn('Git remote origin', 'No remote configured — wiki will not sync/backup automatically');
451
458
  }
452
459
 
453
- const preCommitPath = join(hypoDir, '.git', 'hooks', 'pre-commit');
460
+ // Ask git for the ACTIVE hooks dir rather than assuming <repo>/.git/hooks —
461
+ // that guess is wrong in a linked worktree (`.git` is a file) and whenever
462
+ // core.hooksPath is set, and reporting "not installed" for either would be a
463
+ // false negative. Read-side policy differs from the installer's: doctor
464
+ // reports a hooks dir it would refuse to WRITE into, so the user can see it.
465
+ const resolved = resolveGitHooksDir(hypoDir);
466
+ if (!resolved.ok) {
467
+ const detail =
468
+ resolved.reason === 'hooks-disabled'
469
+ ? `Hooks path is not a directory (${resolved.path}) — git runs no hooks, so the .hypoignore guard cannot run`
470
+ : `Could not resolve the git hooks directory (${resolved.detail || resolved.reason})`;
471
+ warn('git hooks/pre-commit', detail);
472
+ return;
473
+ }
474
+
475
+ const preCommitPath = join(resolved.path, 'pre-commit');
476
+ const label = resolved.owned ? 'git hooks/pre-commit' : `pre-commit (${resolved.path})`;
477
+ let content = null;
478
+ let unreadable = null;
454
479
  if (existsSync(preCommitPath)) {
455
- const content = readFileSync(preCommitPath, 'utf-8');
456
- if (content.includes('# hypo-managed:pre-commit:start')) {
457
- pass('.git/hooks/pre-commit', 'Hypomnema .hypoignore guard installed');
458
- } else {
459
- warn(
460
- '.git/hooks/pre-commit',
461
- 'Exists but not managed by Hypomnema — manual git add can bypass .hypoignore',
462
- );
480
+ try {
481
+ content = readFileSync(preCommitPath, 'utf-8');
482
+ } catch (e) {
483
+ unreadable = e.code || e.message;
463
484
  }
485
+ }
486
+
487
+ if (unreadable) {
488
+ warn(label, `Exists but could not be read (${unreadable})`);
489
+ } else if (content === null) {
490
+ // Telling the user to run /hypo:init here would contradict the ownership
491
+ // warning below, which says it will refuse this very path.
492
+ warn(
493
+ label,
494
+ resolved.owned
495
+ ? 'Not installed — run /hypo:init to install .hypoignore guard'
496
+ : 'Not installed, and /hypo:init will not install into this path — point core.hooksPath back inside the repository, or install the guard yourself',
497
+ );
498
+ } else if (content.includes('# hypo-managed:pre-commit:start')) {
499
+ pass(label, 'Hypomnema .hypoignore guard installed');
464
500
  } else {
465
- warn('.git/hooks/pre-commit', 'Not installed — run /hypo:init to install .hypoignore guard');
501
+ warn(label, 'Exists but not managed by Hypomnema — manual git add can bypass .hypoignore');
502
+ }
503
+
504
+ // Reported even when the hook above was unreadable — an unreadable hook is
505
+ // exactly when knowing WHERE git looks matters most.
506
+ if (!resolved.owned) {
507
+ warn(
508
+ 'core.hooksPath',
509
+ `Points outside this repository (${resolved.path}) — /hypo:init will not install there`,
510
+ );
511
+ }
512
+ }
513
+
514
+ // rename.mjs --apply writes .cache/rename-in-progress.json before its first
515
+ // inbound-link rewrite and removes it only after the terminal move lands (see
516
+ // rename.mjs's writeRenameMarker/clearRenameMarker). A marker still present
517
+ // means the process died mid-run: some inbound wikilinks may already point at
518
+ // `to` while the page/directory itself still sits at `from`. checkBrokenLinks
519
+ // below would just report those as generic broken links (W4's doctor
520
+ // counterpart) with no clue why — this names the cause and the exact fix.
521
+ // Re-running the SAME command converges on its own (the module docstring's
522
+ // move-last invariant): nothing to merge or roll back by hand.
523
+ // Best-effort: does this vault's git repo leave `markerPath` un-ignored (either
524
+ // already tracked, or plain untracked-and-stageable)? `git check-ignore` answers
525
+ // both at once — a tracked file is also reported "not ignored" by it, since
526
+ // .gitignore rules don't retroactively apply to tracked paths. Fails CLOSED to
527
+ // "don't know, say nothing": no `.git`, no git on PATH, or any non-0/1 exit
528
+ // (128 = not a repo / path outside it / other error) all return false, because
529
+ // this is advisory-only and a wrong guess is worse than silence (codex CONCERN 3
530
+ // — never turn an inconclusive git query into an error of its own).
531
+ function markerNotGitIgnored(hypoDir, markerPath) {
532
+ if (!existsSync(join(hypoDir, '.git'))) return false;
533
+ const rel = relative(hypoDir, markerPath);
534
+ const r = spawnSync('git', ['-C', hypoDir, 'check-ignore', '-q', rel], { encoding: 'utf-8' });
535
+ if (r.error || r.status === null) return false;
536
+ if (r.status !== 0 && r.status !== 1) return false; // 128 etc — inconclusive
537
+ return r.status === 1; // check-ignore's "not ignored" exit code
538
+ }
539
+
540
+ function checkIncompleteRename(hypoDir) {
541
+ // "no marker" and "a marker we cannot read" are different answers and must not
542
+ // collapse. readRenameMarker returns null for both, so ask the filesystem
543
+ // which one it is: a present-but-unreadable marker still means a rename did
544
+ // not finish, and reporting that as a pass would make the detector fail open
545
+ // on exactly the case it exists for.
546
+ const markerPath = renameMarkerPath(hypoDir);
547
+ const present = existsSync(markerPath);
548
+ if (!present) {
549
+ pass('Incomplete rename', 'No rename-in-progress marker found');
550
+ return;
551
+ }
552
+
553
+ // codex CONCERN 3: a legacy/custom vault whose .gitignore predates
554
+ // templates/gitignore's `.cache/` entry (init never edits an existing
555
+ // .gitignore) can let `git add -A` commit this marker, producing a ghost
556
+ // warning on another machine that never ran a rename at all. Advisory only —
557
+ // never turns the rename itself into an error — appended to every branch
558
+ // below that reports on a present marker.
559
+ const gitAdvisory = markerNotGitIgnored(hypoDir, markerPath)
560
+ ? ` This vault's git repo does not ignore ${dirname(RENAME_MARKER_REL)}/ — \`git add -A\` could commit this marker and produce a ghost warning on another machine. Add \`.cache/\` to .gitignore.`
561
+ : '';
562
+
563
+ const marker = readRenameMarker(hypoDir);
564
+ if (!marker || !marker.from || !marker.to) {
565
+ warn(
566
+ 'Incomplete rename',
567
+ `${markerPath} exists but is unreadable or missing its from/to fields, so a rename did not finish and this cannot say which one. Inspect the file, re-run that rename to converge, then delete the marker.${gitAdvisory}`,
568
+ );
569
+ return;
466
570
  }
571
+
572
+ // codex BLOCKER 2: the marker alone cannot distinguish a genuinely stuck
573
+ // rename from one that finished right before the process died — rename.mjs's
574
+ // move (renameSync) is the terminal step, and the marker is only cleared
575
+ // AFTER it. Cross-check `from`/`to` (vault-root-relative) against the
576
+ // filesystem to tell the three reachable states apart.
577
+ const { mode, from, to, started_at } = marker;
578
+ const label = mode === 'directory' ? 'directory' : 'page';
579
+ const fromExists = existsSync(join(hypoDir, from));
580
+ const toExists = existsSync(join(hypoDir, to));
581
+ const cmd = `node ${join(PKG_ROOT, 'scripts', 'rename.mjs')} --hypo-dir=${hypoDir} --from=${from} --to=${to} --apply`;
582
+
583
+ if (fromExists && !toExists) {
584
+ // The real in-progress case: --from still resolves, so re-running the
585
+ // IDENTICAL command converges on its own (rename.mjs's move-last invariant).
586
+ warn(
587
+ 'Incomplete rename',
588
+ `a ${label} rename from '${from}' to '${to}' did not finish` +
589
+ (started_at ? ` (started ${started_at})` : '') +
590
+ ` — some inbound links may already point at the new name while the ${label} itself has not moved. Re-run the identical rename to converge: ${cmd}${gitAdvisory}`,
591
+ );
592
+ return;
593
+ }
594
+
595
+ if (!fromExists && toExists) {
596
+ // The move already landed — renameSync is one syscall, so this can only mean
597
+ // the process died AFTER it and BEFORE clearRenameMarker ran. Re-running the
598
+ // same command here would just fail (`--from` no longer resolves — see
599
+ // rename.mjs's own "did not resolve to a unique existing page" refusal), so
600
+ // suggesting a re-run (the prior behavior) handed the user a command that
601
+ // errors. Nothing to converge: the marker is pure leftover.
602
+ warn(
603
+ 'Incomplete rename',
604
+ `a ${label} rename from '${from}' to '${to}' already finished (the ${label} moved) but its ` +
605
+ `in-progress marker was never cleared — the process likely died right after the move landed. ` +
606
+ `Nothing left to redo; just delete the stale marker: rm ${markerPath}${gitAdvisory}`,
607
+ );
608
+ return;
609
+ }
610
+
611
+ // Both paths exist, or neither does — the marker's from/to no longer map onto
612
+ // a determinable state (e.g. something else since recreated one of the two
613
+ // paths). Refuse to guess in either direction; a human needs to look.
614
+ warn(
615
+ 'Incomplete rename',
616
+ `${markerPath} names a ${label} rename from '${from}' to '${to}', but ${
617
+ fromExists && toExists
618
+ ? 'BOTH the from and to paths currently exist'
619
+ : 'NEITHER the from nor the to path currently exists'
620
+ } — cannot tell whether the rename finished. Inspect both paths by hand, then either re-run the rename or delete the marker: ${markerPath}${gitAdvisory}`,
621
+ );
467
622
  }
468
623
 
469
624
  function checkBrokenLinks(hypoDir, ignorePatterns = []) {
@@ -644,6 +799,239 @@ function checkProjectIndexAnchors(hypoDir) {
644
799
  }
645
800
  }
646
801
 
802
+ // The project(s) a commit touched, by which projects/<slug>/ paths it
803
+ // changed — a SET, because a merge or a multi-project commit can touch more
804
+ // than one, and `close the session` in that commit's message must then be
805
+ // verified against ALL of them, not silently attributed to just one.
806
+ // Empty when the commit touches no project path, or `git show` itself fails
807
+ // (a corrupt or unreachable object) — both are "can't determine scope", which
808
+ // this returns as *no scope at all*, not "any scope"; see markerCoversArtifact
809
+ // for why that direction matters.
810
+ function deriveCommitProjects(hypoDir, hash) {
811
+ // --name-status -M (not --name-only): a rename prints ONLY the destination
812
+ // path under --name-only ("R100 old\tnew" collapses to just "new"), so a
813
+ // projects/a/hot.md → projects/b/hot.md rename would silently drop project
814
+ // a from scope — a marker naming only "b" would then wrongly cover the
815
+ // whole commit. -M's tab-separated `status\told\tnew` line carries both.
816
+ const show = spawnSync(
817
+ 'git',
818
+ ['-C', hypoDir, 'show', '--name-status', '-M', '--format=', hash],
819
+ { encoding: 'utf-8' },
820
+ );
821
+ if (show.status !== 0 || !show.stdout) return [];
822
+ const projects = new Set();
823
+ for (const line of show.stdout.split('\n')) {
824
+ if (!line.trim()) continue;
825
+ // status\tpath (add/modify/delete) or status\told\tnew (rename/copy) —
826
+ // every field after the status column is a path this commit touched.
827
+ const [, ...paths] = line.split('\t');
828
+ for (const path of paths) {
829
+ const m = /^projects\/([^/]+)\//.exec(path.trim());
830
+ // _template is the scaffold, never a real project — same exclusion the
831
+ // file-scan loop above applies, so a commit that happens to touch it
832
+ // (e.g. an init/upgrade run) doesn't manufacture a phantom project a
833
+ // marker can never cover.
834
+ if (m && m[1] !== '_template') projects.add(m[1]);
835
+ }
836
+ }
837
+ return [...projects];
838
+ }
839
+
840
+ // A marker only vouches for the project(s) it names, PLUS its own calendar
841
+ // day. Two ways that can go wrong if handled loosely, both fixed here:
842
+ //
843
+ // 1. Scope creep: a same-day close in a DIFFERENT project must not silence
844
+ // this one (the marker was introduced for per-session precision
845
+ // specifically to prevent one close from vouching for another —
846
+ // hooks/hypo-shared.mjs SESSION_CLOSED_MARKER_STALE_MS comment).
847
+ // 2. Timezone artifact: closed_at is UTC; a file-content artifact's date is
848
+ // local (hooks/hypo-shared.mjs localAndUtcDates() accepts both for
849
+ // exactly this reason).
850
+ //
851
+ // `artifact.scope.kind` is a closed set, not a free-form nullable project —
852
+ // an UNKNOWN scope must never default to "any marker on that date covers
853
+ // it": this is a warning-only, best-effort check, so the cost of a false
854
+ // PASS (the exact failure mode it exists to catch) outweighs the cost of a
855
+ // false WARN (mild noise). Concretely:
856
+ // • 'root-universal' — root hot.md. The real close procedure updates it on
857
+ // EVERY close regardless of project (closeFileTargets in
858
+ // hooks/hypo-shared.mjs), so date-only correlation is legitimate here,
859
+ // not a gap.
860
+ // • 'unscoped' — root session-state.md (NOT part of the real close file
861
+ // set — the same closeFileTargets list proves it), or a commit whose
862
+ // touched-project set came back empty/ambiguous. No marker can vouch for
863
+ // an artifact with no verifiable scope, so this never matches, ever.
864
+ // • 'projects' — a project file, or a commit that touched one or more
865
+ // identifiable projects/<slug>/ paths. EVERY named project must appear
866
+ // in the marker's own `projects` list.
867
+ function markerCoversArtifact(marker, artifact) {
868
+ if (!marker.dates.includes(artifact.date)) return false;
869
+ switch (artifact.scope.kind) {
870
+ case 'root-universal':
871
+ return true;
872
+ case 'projects':
873
+ return artifact.scope.projects.every((p) => marker.projects.includes(p));
874
+ default:
875
+ return false; // 'unscoped'
876
+ }
877
+ }
878
+
879
+ // Post-hoc surface for a session closed BY HAND, without the session-closed
880
+ // marker hard gate ever firing (the gate lives on the marker writer, and a
881
+ // close done by editing files directly never calls it). Warning-only: this
882
+ // cannot tell an actually-approved-but-ungated close from an over-close, it
883
+ // can only say the two signals disagree, so it never blocks.
884
+ //
885
+ // Window: 7 days for the git-log scan, matching SESSION_CLOSED_MARKER_STALE_MS
886
+ // in hooks/hypo-shared.mjs — a marker older than that is already treated as
887
+ // expired everywhere else (enforced below too, when reading the raw marker
888
+ // files), so correlating against a longer window would compare a close
889
+ // artifact against a marker doctor itself considers stale.
890
+ function checkSessionCloseArtifacts(hypoDir) {
891
+ const artifacts = [];
892
+
893
+ const scanFile = (path, scope) => {
894
+ if (!existsSync(path)) return;
895
+ let content;
896
+ try {
897
+ content = readFileSync(path, 'utf-8');
898
+ } catch {
899
+ return;
900
+ }
901
+ const result = detectSessionCloseArtifact({ path, content });
902
+ if (result.matched) {
903
+ artifacts.push({ date: result.date, scope, where: relative(hypoDir, path) });
904
+ }
905
+ };
906
+
907
+ // Root hot.md is a real close artifact of every close, project or not — see
908
+ // markerCoversArtifact's 'root-universal' case. Root session-state.md is
909
+ // NOT: the real close procedure never touches it (closeFileTargets in
910
+ // hooks/hypo-shared.mjs lists hot.md/log.md + the ACTIVE project's files
911
+ // only), so a 마감 heading appearing there has no legitimate close to
912
+ // attribute it to — 'unscoped' means no marker, however fresh, ever covers it.
913
+ scanFile(join(hypoDir, 'hot.md'), { kind: 'root-universal' });
914
+ scanFile(join(hypoDir, 'session-state.md'), { kind: 'unscoped' });
915
+ const projectsDir = join(hypoDir, 'projects');
916
+ if (existsSync(projectsDir)) {
917
+ for (const slug of readdirSync(projectsDir)) {
918
+ if (slug === '_template') continue;
919
+ const dir = join(projectsDir, slug);
920
+ try {
921
+ if (!statSync(dir).isDirectory()) continue;
922
+ } catch {
923
+ continue;
924
+ }
925
+ scanFile(join(dir, 'session-state.md'), { kind: 'projects', projects: [slug] });
926
+ scanFile(join(dir, 'hot.md'), { kind: 'projects', projects: [slug] });
927
+ }
928
+ }
929
+
930
+ if (existsSync(join(hypoDir, '.git'))) {
931
+ const log = spawnSync(
932
+ 'git',
933
+ ['-C', hypoDir, 'log', '--since=7.days.ago', '--format=%H%x1f%ad%x1f%s', '--date=short'],
934
+ { encoding: 'utf-8' },
935
+ );
936
+ if (log.status === 0 && log.stdout) {
937
+ for (const line of log.stdout.split('\n')) {
938
+ if (!line.trim()) continue;
939
+ const [hash, date, subject] = line.split('\x1f');
940
+ if (detectSessionCloseArtifact({ commitMessage: subject }).matched) {
941
+ const projects = deriveCommitProjects(hypoDir, hash);
942
+ artifacts.push({
943
+ date,
944
+ scope: projects.length > 0 ? { kind: 'projects', projects } : { kind: 'unscoped' },
945
+ where: `commit "${subject}"`,
946
+ });
947
+ }
948
+ }
949
+ }
950
+ }
951
+
952
+ if (artifacts.length === 0) {
953
+ pass('Session-close artifacts', 'No close artifacts found');
954
+ return;
955
+ }
956
+
957
+ // Read the raw marker files directly rather than readSessionClosedMarker,
958
+ // which also DELETES an expired one as a side effect; a health check
959
+ // should not mutate state to produce a diagnosis. Staleness is still
960
+ // enforced here (same SESSION_CLOSED_MARKER_STALE_MS window) so an
961
+ // already-expired marker can't vouch for anything.
962
+ const cacheDir = join(hypoDir, '.cache');
963
+ const markers = [];
964
+ let cacheEntries = [];
965
+ if (existsSync(cacheDir)) {
966
+ try {
967
+ cacheEntries = readdirSync(cacheDir);
968
+ } catch {
969
+ // unreadable .cache/ — not this check's job to diagnose that
970
+ }
971
+ }
972
+ for (const file of cacheEntries) {
973
+ if (!file.startsWith('session-closed-') || !file.endsWith('.marker')) continue;
974
+ try {
975
+ const data = JSON.parse(readFileSync(join(cacheDir, file), 'utf-8'));
976
+ const ts = Date.parse(data?.closed_at || '');
977
+ if (!Number.isFinite(ts) || Date.now() - ts > SESSION_CLOSED_MARKER_STALE_MS) continue;
978
+ // ONLY the v4 `projects` array counts as project-scope evidence. A
979
+ // legacy flat `project` field can be a recency-derived misattribution
980
+ // (the P1 bug resolveCloseScope's own doc comment describes) — the
981
+ // runtime scope resolver already refuses to trust it uncorroborated,
982
+ // and doctor has no corroborating signal of its own to add, so it
983
+ // must refuse it too rather than re-opening the same hole standalone.
984
+ const projects = Array.isArray(data?.projects) ? data.projects.filter(Boolean) : [];
985
+ markers.push({ projects: [...new Set(projects)], dates: localAndUtcDates(new Date(ts)) });
986
+ } catch {
987
+ // corrupt marker — not this check's job to clean up
988
+ }
989
+ }
990
+
991
+ const unmatched = artifacts.filter(
992
+ (a) => !a.date || !markers.some((m) => markerCoversArtifact(m, a)),
993
+ );
994
+ if (unmatched.length === 0) {
995
+ pass(
996
+ 'Session-close artifacts',
997
+ `${artifacts.length} close artifact(s), all covered by a session-closed marker`,
998
+ );
999
+ return;
1000
+ }
1001
+
1002
+ const sample = unmatched
1003
+ .slice(0, 5)
1004
+ .map((a) => `${a.where}${a.date ? ` (${a.date})` : ''}`)
1005
+ .join(', ');
1006
+ const extra = unmatched.length > 5 ? ` (+${unmatched.length - 5} more)` : '';
1007
+ // Not necessarily UNAPPROVED — an approved log-only marker (deliberately
1008
+ // empty `projects`) or one scoped to a different project would ALSO land
1009
+ // here, since neither covers a specific project's artifact. Both readings
1010
+ // are worth a human look, so the wording covers both instead of asserting
1011
+ // the stronger, sometimes-wrong one.
1012
+ warn(
1013
+ 'Session-close artifacts',
1014
+ `${unmatched.length} close artifact(s) with no session-closed marker covering their ` +
1015
+ `date and project scope — may be an unapproved hand-made close, or an approved close ` +
1016
+ `whose marker doesn't attribute this project: ${sample}${extra}`,
1017
+ );
1018
+ }
1019
+
1020
+ /**
1021
+ * Render a `.cache/sync-last-success.json` record as an absolute-time note.
1022
+ * Deliberately no "recent"/staleness verdict — the failure-state check above
1023
+ * already carries the health signal; this only says what and when.
1024
+ */
1025
+ function formatLastSuccess(lastSuccess) {
1026
+ const pull = lastSuccess.pull
1027
+ ? `pull ${lastSuccess.pull.timestamp} (${lastSuccess.pull.host})`
1028
+ : 'pull: none recorded';
1029
+ const push = lastSuccess.push
1030
+ ? `push ${lastSuccess.push.timestamp} (${lastSuccess.push.host})`
1031
+ : 'push: none recorded';
1032
+ return `${pull}; ${push}`;
1033
+ }
1034
+
647
1035
  function checkSyncState(hypoDir) {
648
1036
  // "open" = file exists with ≥1 entries; session-start clears once
649
1037
  // sync is healthy again. Schema + parsing live in hooks/hypo-shared.mjs.
@@ -655,20 +1043,96 @@ function checkSyncState(hypoDir) {
655
1043
  }
656
1044
 
657
1045
  if (entries.length === 0) {
658
- pass('Sync state', 'No unresolved sync failures');
1046
+ // No unresolved failure — but that alone does not mean sync ever ran.
1047
+ // Read the separate, additive last-success record to tell "never synced"
1048
+ // apart from "healthy" and, when present, from a pull-only/push-only
1049
+ // history. A corrupt success file warns rather than crashing, same as the
1050
+ // sync-state parse-error handling above.
1051
+ const { data: lastSuccess, parseError: successParseError } = readSyncLastSuccess(hypoDir);
1052
+ if (successParseError) {
1053
+ warn('Sync state', 'Cannot parse .cache/sync-last-success.json — inspect manually');
1054
+ } else if (!lastSuccess.pull && !lastSuccess.push) {
1055
+ pass(
1056
+ 'Sync state',
1057
+ 'No unresolved sync failures — never synced (no recorded pull or push yet)',
1058
+ );
1059
+ } else {
1060
+ // Distinguishes pull-only / push-only / both, since formatLastSuccess
1061
+ // reports "none recorded" for whichever op is absent.
1062
+ pass(
1063
+ 'Sync state',
1064
+ `No unresolved sync failures. Last success — ${formatLastSuccess(lastSuccess)}`,
1065
+ );
1066
+ }
659
1067
  } else {
660
1068
  const last = entries[entries.length - 1];
661
- // A merge conflict needs a real manual merge, not a plain push/pull — give
662
- // the same explicit guidance session-start does instead of the generic hint.
663
- if (String(last.op || '').startsWith('conflict')) {
1069
+ // An unresolved failure does not mean the OTHER operation never
1070
+ // succeeded — a push failure can sit right next to a healthy pull, and
1071
+ // the last-success record above used to only wire into the healthy/
1072
+ // never-synced branch, leaving this branch silent about it. Append it
1073
+ // here too, best-effort, same as the healthy branch — a corrupt success
1074
+ // file still warns, never crashes.
1075
+ const { data: lastSuccess, parseError: successParseError } = readSyncLastSuccess(hypoDir);
1076
+ // Not "unreadable": readSyncLastSuccess also sets parseError for a file
1077
+ // that reads fine and parses as valid JSON but has the wrong shape (a
1078
+ // malformed pull/push field, or an unrecognized key) — "unreadable" would
1079
+ // misdescribe that case.
1080
+ const successSuffix = successParseError
1081
+ ? ' (.cache/sync-last-success.json is invalid or unreadable — inspect manually)'
1082
+ : lastSuccess.pull || lastSuccess.push
1083
+ ? ` Last success — ${formatLastSuccess(lastSuccess)}.`
1084
+ : '';
1085
+ // More than one open entry means the vault has been failing across
1086
+ // multiple sync attempts without clearing — name each one (op@timestamp),
1087
+ // not just the last, so the user isn't left to open sync-state.json
1088
+ // themselves to see the pattern. Capped like checkBrokenLinks/checkVerifyBy.
1089
+ const unresolvedList =
1090
+ entries.length > 1
1091
+ ? ` Unresolved: ${entries
1092
+ .slice(-5)
1093
+ .map((e) => `${e.op || '?'}@${e.timestamp || '?'}`)
1094
+ .join(', ')}${entries.length > 5 ? ` (+${entries.length - 5} more)` : ''}.`
1095
+ : '';
1096
+ // classifySyncOp (hooks/hypo-shared.mjs) is the single judgment both this
1097
+ // check and hypo-session-start.mjs's syncStateNotice branch on, so the
1098
+ // two surfaces cannot silently diverge on WHICH op gets which treatment.
1099
+ // 'conflict-unresolved' — the merge --abort itself failed — is the more
1100
+ // dangerous of the two conflict ops: the tree may still be
1101
+ // half-merged (unmerged index entries, or an in-progress MERGE_HEAD), so
1102
+ // it gets dedicated guidance rather than the plain-conflict branch below,
1103
+ // which claims "your local work is committed" (not true when the abort
1104
+ // itself failed) and advises `git pull --no-rebase` (git would simply
1105
+ // refuse that mid-merge). Wording mirrors hypo-session-start.mjs's
1106
+ // syncStateNotice so the two surfaces never contradict each other.
1107
+ const cls = classifySyncOp(last.op);
1108
+ if (cls === 'conflict-unresolved') {
1109
+ warn(
1110
+ 'Sync state',
1111
+ `${entries.length} unresolved sync issue(s) — last: remote diverged AND the automatic merge-abort failed; the working tree may still be half-merged (unmerged paths or an in-progress merge). Do NOT commit or push yet. Run \`git status\` first: if a merge is in progress, resolve the conflicts, then \`git add <resolved paths>\` and \`git commit\` (git refuses a commit while unmerged entries remain staged) — or run \`git merge --abort\` to discard it instead, before continuing.${unresolvedList}${successSuffix}`,
1112
+ );
1113
+ } else if (cls === 'conflict') {
1114
+ // A merge conflict needs a real manual merge, not a plain push/pull —
1115
+ // give the same explicit guidance session-start does instead of the
1116
+ // generic hint. This branch is unmerged-index-free by construction (the
1117
+ // abort succeeded), so "committed and safe" is an accurate claim here.
1118
+ warn(
1119
+ 'Sync state',
1120
+ `${entries.length} unresolved sync issue(s) — last: remote diverged (merge conflict). Your local work is committed; the other machine's version is on the remote. Resolve with \`git pull --no-rebase\`, fix conflicts, \`git add\` them, then commit and push.${unresolvedList}${successSuffix}`,
1121
+ );
1122
+ } else if (cls === 'unknown-conflict') {
1123
+ // An unrecognized `conflict*` op — a future syncRemote failure mode
1124
+ // this check has no dedicated branch for. Neither the 'conflict'
1125
+ // branch's "committed" claim nor the 'conflict-unresolved' branch's
1126
+ // "abort failed" claim is known to hold here, so assert neither:
1127
+ // report the state as unknown and treat it as unresolved.
664
1128
  warn(
665
1129
  'Sync state',
666
- `${entries.length} unresolved sync issue(s) — last: remote diverged (merge conflict). Your local work is committed; the other machine's version is on the remote. Resolve with \`git pull --no-rebase\`, fix conflicts, then push.`,
1130
+ `${entries.length} unresolved sync issue(s) — last: remote diverged — an unrecognized conflict-related sync failure ('${last.op}') was recorded. Its resolution state cannot be confirmed automatically — treat it as unresolved. Run \`git status\` first to check for unmerged paths or an in-progress merge before committing or pushing.${unresolvedList}${successSuffix}`,
667
1131
  );
668
1132
  } else {
669
1133
  warn(
670
1134
  'Sync state',
671
- `${entries.length} unresolved failure(s) — last: ${last.op || '?'} at ${last.timestamp || '?'}. Inspect .cache/sync-state.json or push/pull manually to clear.`,
1135
+ `${entries.length} unresolved failure(s) — last: ${last.op || '?'} at ${last.timestamp || '?'}. Inspect .cache/sync-state.json or push/pull manually to clear.${unresolvedList}${successSuffix}`,
672
1136
  );
673
1137
  }
674
1138
  }
@@ -1491,6 +1955,7 @@ if (rootOk) {
1491
1955
  checkFiles(args.hypoDir);
1492
1956
  checkScanIgnoreFile(args.hypoDir);
1493
1957
  checkBrokenLinks(args.hypoDir, ignorePatterns);
1958
+ checkIncompleteRename(args.hypoDir);
1494
1959
  checkVerifyBy(args.hypoDir, ignorePatterns);
1495
1960
  }
1496
1961
  checkHooks(coreManagedByPlugin);
@@ -1501,6 +1966,7 @@ if (args.codex) checkCodexPaths();
1501
1966
  if (rootOk) checkExtensions(args.hypoDir, args.claudeHome, 'claude');
1502
1967
  if (rootOk && args.codex) checkExtensions(args.hypoDir, args.claudeHome, 'codex');
1503
1968
  if (rootOk) checkProjectIndexAnchors(args.hypoDir);
1969
+ if (rootOk) checkSessionCloseArtifacts(args.hypoDir);
1504
1970
  if (rootOk) checkSyncState(args.hypoDir);
1505
1971
  if (rootOk) checkProjectSuggestions(args.hypoDir);
1506
1972
  if (rootOk) checkProposals(args.hypoDir);
package/scripts/graph.mjs CHANGED
@@ -91,7 +91,7 @@ function escapeDot(s) {
91
91
 
92
92
  // ── formatters ────────────────────────────────────────────────────────────────
93
93
 
94
- function formatJson(pages, graph, minEdges) {
94
+ function formatJson(pages, graph, minEdges, vaultFound) {
95
95
  const nodes = pages
96
96
  .map((p) => ({
97
97
  slug: p.slug,
@@ -107,7 +107,9 @@ function formatJson(pages, graph, minEdges) {
107
107
  return fn && tn;
108
108
  });
109
109
 
110
- return JSON.stringify({ nodes, edges }, null, 2);
110
+ // vaultFound: same reasoning as lint.mjs/stats.mjs — an empty graph from a
111
+ // vault that was never found must not read the same as a real, linkless one.
112
+ return JSON.stringify({ nodes, edges, vaultFound }, null, 2);
111
113
  }
112
114
 
113
115
  function formatMermaid(pages, graph, minEdges) {
@@ -156,7 +158,11 @@ function formatDot(pages, graph, minEdges) {
156
158
  const args = parseArgs(process.argv);
157
159
  // Only validate the auto-resolved path (env/marker/default). An explicit
158
160
  // --hypo-dir=<path> (tests, other tooling) is trusted as-is, valid or not.
159
- if (args.hypoDirSource) checkVaultOrExit(args.hypoDir, args.hypoDirSource);
161
+ // See lint.mjs's matching comment: source 'default'/stale-'marker' stays
162
+ // exit-0 (CI-safe).
163
+ const vaultMissing = args.hypoDirSource
164
+ ? checkVaultOrExit(args.hypoDir, args.hypoDirSource)
165
+ : false;
160
166
 
161
167
  const ignorePatterns = loadHypoIgnore(args.hypoDir);
162
168
  const scanDirs = ['pages', 'projects'].map((d) => join(args.hypoDir, d));
@@ -164,13 +170,22 @@ const pages = scanDirs.flatMap((d) => collectPagesGraph(d, args.hypoDir, ignoreP
164
170
  const slugIndex = buildSlugIndex(pages);
165
171
  const graph = buildGraph(pages, slugIndex);
166
172
 
167
- switch (args.format) {
168
- case 'mermaid':
169
- console.log(formatMermaid(pages, graph, args.minEdges));
170
- break;
171
- case 'dot':
172
- console.log(formatDot(pages, graph, args.minEdges));
173
- break;
174
- default:
175
- console.log(formatJson(pages, graph, args.minEdges));
173
+ if (vaultMissing && (args.format === 'mermaid' || args.format === 'dot')) {
174
+ // Same reasoning as lint.mjs/stats.mjs: mermaid/dot render straight to a
175
+ // diagram tool with no JSON envelope to carry `vaultFound`, so a valid but
176
+ // linkless diagram from a real (empty) vault and "no vault was found at
177
+ // all" would otherwise render identically. checkVaultOrExit already put the
178
+ // "No Hypomnema vault found" notice on stderr; suppress the stdout diagram
179
+ // rather than hand the renderer an empty-but-"real"-looking graph.
180
+ } else {
181
+ switch (args.format) {
182
+ case 'mermaid':
183
+ console.log(formatMermaid(pages, graph, args.minEdges));
184
+ break;
185
+ case 'dot':
186
+ console.log(formatDot(pages, graph, args.minEdges));
187
+ break;
188
+ default:
189
+ console.log(formatJson(pages, graph, args.minEdges, !vaultMissing));
190
+ }
176
191
  }