@staix/vault-mem 0.5.1 → 0.6.0

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +138 -23
  3. package/package.json +5 -4
  4. package/src/amem/seam.ts +15 -6
  5. package/src/analysis-commands.ts +1 -1
  6. package/src/analysis-input.ts +24 -3
  7. package/src/analysis-reports.ts +1 -1
  8. package/src/analysis-types.ts +13 -1
  9. package/src/canon-tables.ts +190 -0
  10. package/src/cli-output.ts +15 -1
  11. package/src/cli.ts +1 -1
  12. package/src/commands-table.ts +6 -2
  13. package/src/config.ts +31 -3
  14. package/src/frontmatter.ts +10 -3
  15. package/src/links.ts +13 -1
  16. package/src/mcp-spec.ts +19 -11
  17. package/src/mcp-vault.ts +14 -9
  18. package/src/mcp.ts +4 -2
  19. package/src/org-promote.ts +29 -12
  20. package/src/promote.ts +24 -12
  21. package/src/read-commands.ts +1 -2
  22. package/src/read-output.ts +7 -5
  23. package/src/registry.ts +1 -0
  24. package/src/skills-mine.ts +5 -4
  25. package/src/spec-command-table.ts +10 -1
  26. package/src/spec-commands.ts +7 -3
  27. package/src/spec-gitlinks.ts +106 -0
  28. package/src/spec-output.ts +30 -0
  29. package/src/spec-source.ts +9 -3
  30. package/src/spec-validate.ts +6 -3
  31. package/src/spec-write.ts +469 -0
  32. package/src/ui/inbox.ts +28 -10
  33. package/src/ui/panel.js +26 -5
  34. package/src/ui/plugin.ts +38 -12
  35. package/src/ui/snapshot-cache.ts +123 -0
  36. package/src/vault-index.ts +109 -19
  37. package/src/vault-lint.ts +53 -5
  38. package/src/vault-log.ts +3 -2
  39. package/src/vault-stats.ts +110 -5
  40. package/src/write-commands.ts +4 -3
  41. package/src/write-files.ts +63 -0
  42. package/src/write-operations.ts +175 -25
  43. package/src/write-output.ts +20 -9
  44. package/src/write-types.ts +8 -1
  45. package/src/write-validation.ts +46 -17
  46. package/src/writer.ts +137 -41
  47. package/src/yaml-quoted.ts +12 -2
@@ -1,28 +1,129 @@
1
+ import { resolve } from "node:path";
2
+ import { MAX_AUX_BYTES, analysisReadWithSize } from "./analysis-input.ts";
1
3
  import { localDate } from "./local-date.ts";
2
4
  import { LOG_TYPES } from "./log-format.ts";
5
+ import { canonicalPath, isDenied } from "./platform.ts";
3
6
  import { loadRegistry } from "./registry.ts";
4
- import { VaultIndex } from "./vault-index.ts";
7
+ import { sourceReferences, sourceWorkspaceRoot, type SourceReference } from "./source.ts";
8
+ import { VaultIndex, type NoteSize, type SourcedNote } from "./vault-index.ts";
5
9
  import { readLog } from "./vault-log.ts";
6
10
  import type { WriteIssue } from "./write-types.ts";
7
11
  import type { VaultSpec } from "./config.ts";
8
12
 
9
13
  export const STATS_DEFAULT_DAYS = 30;
10
14
  export const STATS_MAX_DAYS = 3650;
15
+ /** Source files the ratio pass reads per call, and how many source bytes it counts in total. */
16
+ export const MAX_RATIO_SOURCES = 10000;
17
+ export const MAX_RATIO_SOURCE_BYTES = 64 * 1024 * 1024;
18
+ /** The caps one ratio call works within; the defaults are the two bounds above, and a test lowers them. */
19
+ export interface RatioLimits { sources: number; bytes: number }
20
+ export const RATIO_LIMITS: RatioLimits = { sources: MAX_RATIO_SOURCES, bytes: MAX_RATIO_SOURCE_BYTES };
21
+ /** One bounded source read; `noteSourceRatio` takes one so a test can count the reads a pass really makes. */
22
+ export type SourceFileRead = (file: string, maximum: number) => { bytes: number } | null;
23
+ /** Notes listed as the largest, and the ratio above which a note is larger than the sources it cites. */
24
+ export const RATIO_LARGEST_SHOWN = 5;
25
+ export const RATIO_OVER_ONE = 1;
26
+ export interface VaultRatio {
27
+ /** Notes whose sources could be read and total more than zero bytes. */
28
+ notes: number;
29
+ /** Source files read within the per-call bounds; a zero-byte file is read and counted but leaves its note out of the ratio. */
30
+ sources: number;
31
+ /** Source references left out of the ratio; `skippedNonFile` of them are not workspace files at all. */
32
+ skipped: number;
33
+ skippedNonFile: number;
34
+ /**
35
+ * Notes left out because their readable sources total zero bytes. Such a note has no ratio, and counting it here
36
+ * keeps `skipped` a count of source references: its sources were read and are already in `sources`.
37
+ */
38
+ emptySourceNotes: number;
39
+ /**
40
+ * Sourced notes the index kept out of the pass (`MAX_RATIO_NOTES`), counted rather than dropped silently. The
41
+ * index stops collecting at the cap, so the median, p90 and the rest describe the notes it returned, not all of them.
42
+ */
43
+ truncatedNotes: number;
44
+ /** Median and nearest-rank p90 of the per-note ratio: note bytes over the bytes of its readable sources. */
45
+ median: number | null;
46
+ p90: number | null;
47
+ /** Notes whose ratio is above `RATIO_OVER_ONE`, so the note is larger than its sources. */
48
+ overOne: number;
49
+ largest: { path: string; ratio: number }[];
50
+ }
11
51
  export interface VaultStats {
12
52
  vault: string;
13
53
  /** Local calendar date the windows end on (today included). */
14
54
  asOf: string;
55
+ /** Note text size in bytes and words, by type and domain; "(none)" groups an empty type or domain. */
56
+ size: { total: NoteSize; byType: Record<string, NoteSize>; byDomain: Record<string, NoteSize> };
57
+ /** How large the notes are next to the workspace files they cite. */
58
+ ratio: VaultRatio;
15
59
  notes: { total: number; byType: Record<string, number>; byDomain: Record<string, number>; byStatus: Record<string, number> };
16
60
  /** Notes whose indexed mtime falls within the last 7 and 30 local calendar days, today included. */
17
61
  modified: { last7Days: number; last30Days: number };
18
62
  /** Log events dated on or after `since` (local date), by type; types outside the known set count as "(other)". */
19
63
  log: { days: number; since: string; total: number | null; byType: Record<string, number> | null; warnings: string[]; issues: WriteIssue[] };
20
64
  }
65
+ const round3 = (value: number) => Math.round(value * 1000) / 1000;
66
+ const middle = (sorted: readonly number[]) => {
67
+ const half = sorted.length >> 1;
68
+ return sorted.length % 2 ? sorted[half]! : (sorted[half - 1]! + sorted[half]!) / 2;
69
+ };
70
+ /** Nearest rank: the smallest sorted value that at least `p` percent of the values do not exceed. */
71
+ const percentile = (sorted: readonly number[], p: number) => sorted[Math.min(sorted.length, Math.max(1, Math.ceil((p / 100) * sorted.length))) - 1]!;
72
+ /**
73
+ * Note-to-source byte ratio over notes that declare a frontmatter `source`. Each entry is one note: its own byte size
74
+ * over the summed size of the sources that could be read. The reader is `analysisReadWithSize`, so every file keeps its
75
+ * bound, no link is followed, and the bytes counted are the file's own on-disk size rather than the size of its decoded
76
+ * text, which overstates a file that is not UTF-8. The caps bound the I/O, not just the counted total: a read asks only
77
+ * for the bytes the budget has left, the reader refuses a larger file from its fstat size without reading it, and once
78
+ * the budget is spent no further file is opened. Every read attempt, successful or not, counts against the file cap, so
79
+ * a run of failures or over-budget files cannot outrun it. A memory id, a URL, a denied, missing or oversized path and
80
+ * anything the caps leave out is a skipped source reference, which keeps the pass read-only and bounded; a note whose
81
+ * readable sources total zero bytes has no ratio and is counted in `emptySourceNotes` instead, so `skipped` stays a
82
+ * count of references and never repeats a file that was read. The per-note truncation count belongs to the index, so
83
+ * `vaultStats` adds it to this pass's result.
84
+ */
85
+ export function noteSourceRatio(rows: readonly SourcedNote[], root: string | undefined, denyPaths: string[], limits: RatioLimits = RATIO_LIMITS, readFile: SourceFileRead = analysisReadWithSize): Omit<VaultRatio, "truncatedNotes"> {
86
+ const ratios: { path: string; ratio: number }[] = [];
87
+ let sources = 0, skipped = 0, skippedNonFile = 0, emptySourceNotes = 0, bytesRead = 0, attempts = 0;
88
+ for (const row of rows) {
89
+ let refs: SourceReference[];
90
+ try { refs = sourceReferences(row.source); } catch { skipped++; continue; }
91
+ let size = 0, used = 0;
92
+ for (const ref of refs) {
93
+ if (ref.kind !== "path") { skipped++; skippedNonFile++; continue; }
94
+ const remaining = limits.bytes - bytesRead;
95
+ // Stop before opening anything once a cap is used up, so an exhausted call does no further I/O.
96
+ if (!root || attempts >= limits.sources || remaining <= 0) { skipped++; continue; }
97
+ // Counted before the read, so a failed or over-budget attempt cannot slip past the file cap.
98
+ attempts++;
99
+ const file = resolve(root, ref.value);
100
+ let read: { bytes: number } | null;
101
+ // Ask for no more than the budget has left: the reader refuses a larger file from its fstat size, unread.
102
+ try { read = isDenied(canonicalPath(file), denyPaths) ? null : readFile(file, Math.min(MAX_AUX_BYTES, remaining)); } catch { read = null; }
103
+ // A denied, missing or over-budget file is a skip, and one that would pass the cap is left out whole.
104
+ if (read === null || read.bytes > remaining) { skipped++; continue; }
105
+ size += read.bytes; bytesRead += read.bytes; sources++; used++;
106
+ }
107
+ // A note whose sources are all empty has no ratio: count the note, not a reference, so `skipped` stays reference-only.
108
+ if (!used) continue;
109
+ if (size === 0) { emptySourceNotes++; continue; }
110
+ ratios.push({ path: row.path, ratio: row.bytes / size });
111
+ }
112
+ const values = ratios.map(entry => entry.ratio).sort((a, b) => a - b);
113
+ const largest = [...ratios].sort((a, b) => b.ratio - a.ratio || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)).slice(0, RATIO_LARGEST_SHOWN);
114
+ return {
115
+ notes: ratios.length, sources, skipped, skippedNonFile, emptySourceNotes,
116
+ median: values.length ? round3(middle(values)) : null, p90: values.length ? round3(percentile(values, 90)) : null,
117
+ overOne: ratios.filter(entry => entry.ratio > RATIO_OVER_ONE).length,
118
+ largest: largest.map(entry => ({ path: entry.path, ratio: round3(entry.ratio) })),
119
+ };
120
+ }
21
121
  /**
22
122
  * Read-only vault statistics over the derived index (refreshed like every read tool) and the log streamed by `readLog`:
23
- * no vault file or log is written and no vault or log lock is taken.
123
+ * no vault file or log is written and no vault or log lock is taken. Note sizes come from the same index pass, and the
124
+ * ratio reads only workspace files a note cites, through `analysisReadWithSize` and its bounds.
24
125
  */
25
- export function vaultStats(home: string, id: string, options: { days?: number; now?: Date; expectedVault?: VaultSpec } = {}): VaultStats {
126
+ export function vaultStats(home: string, id: string, options: { days?: number; now?: Date; expectedVault?: VaultSpec; limits?: RatioLimits } = {}): VaultStats {
26
127
  const days = options.days ?? STATS_DEFAULT_DAYS, now = options.now ?? new Date();
27
128
  if (!Number.isInteger(days) || days < 1 || days > STATS_MAX_DAYS) throw new Error(`stats: days must be an integer 1..${STATS_MAX_DAYS}; omit it for the ${STATS_DEFAULT_DAYS}-day default`);
28
129
  const registry = loadRegistry(home), vault = registry.vaults.find(v => v.id === id);
@@ -34,6 +135,8 @@ export function vaultStats(home: string, id: string, options: { days?: number; n
34
135
  const index = new VaultIndex(home, vault, registry.vaults.map(v => v.path));
35
136
  let notes: ReturnType<VaultIndex["noteStats"]>;
36
137
  try { index.scan(); notes = index.noteStats([start(7).getTime(), start(30).getTime()]); } finally { index.close(); }
138
+ const size = notes.size, pass = noteSourceRatio(notes.sourced, sourceWorkspaceRoot(vault), registry.denyPaths ?? [], options.limits);
139
+ const ratio: VaultRatio = { ...pass, truncatedNotes: notes.truncatedSourced };
37
140
  const since = localDate(start(days)), byType: Record<string, number> = Object.fromEntries(LOG_TYPES.map(type => [type, 0]));
38
141
  let total = 0;
39
142
  const log = readLog(home, { vault: vault.id, limit: 1, visit: line => {
@@ -42,9 +145,11 @@ export function vaultStats(home: string, id: string, options: { days?: number; n
42
145
  const type = (LOG_TYPES as readonly string[]).includes(match[2]!) ? match[2]! : "(other)";
43
146
  total++; byType[type] = (byType[type] ?? 0) + 1;
44
147
  } });
45
- const { modified: [last7Days = 0, last30Days = 0], ...counts } = notes;
148
+ const { modified: [last7Days = 0, last30Days = 0] } = notes;
46
149
  return {
47
- vault: vault.id, asOf: localDate(now), notes: counts, modified: { last7Days, last30Days },
150
+ vault: vault.id, asOf: localDate(now), size, ratio,
151
+ notes: { total: notes.total, byType: notes.byType, byDomain: notes.byDomain, byStatus: notes.byStatus },
152
+ modified: { last7Days, last30Days },
48
153
  log: { days, since, total: log.ok ? total : null, byType: log.ok ? byType : null, warnings: log.warnings, issues: log.issues },
49
154
  };
50
155
  }
@@ -12,7 +12,7 @@ import { argumentError } from "./mcp.ts";
12
12
  import { parseTidyMap, tidyVault, TIDY_RULES } from "./tidy.ts";
13
13
  import { PLAIN, type TextOptions } from "./text-output.ts";
14
14
  import { renderTidy, renderWriteReceipt } from "./write-output.ts";
15
- const COMMANDS = new Set(["new", "patch", "append", "frontmatter", "link", "supersede", "move", "delete", "tidy", "report", "check"]);
15
+ const COMMANDS = new Set(["new", "patch", "append", "frontmatter", "link", "supersede", "merge", "move", "delete", "tidy", "report", "check"]);
16
16
  export function isWriteCommand(command: string): boolean { return COMMANDS.has(command); }
17
17
  function object(text: string, label: string): Record<string, unknown> {
18
18
  let value: unknown;
@@ -48,12 +48,12 @@ export function runWriteCommand(command: string, args: string[], home: string, e
48
48
  new: ["--type", "--domain", "--topics", "--description", "--title", "--source", "--confidence", "--status", "--extra", "--body"],
49
49
  patch: ["--old", "--new", "--edits", "--expected-sha"], append: ["--section", "--markdown", "--expected-sha"],
50
50
  frontmatter: ["--set", "--unset", "--expected-sha"], link: ["--relation", "--context"],
51
- move: ["--fingerprint"], delete: ["--fingerprint"], tidy: ["--fingerprint", "--map"], report: ["--body"], check: ["--path"], supersede: [],
51
+ merge: ["--fingerprint"], move: ["--fingerprint"], delete: ["--fingerprint"], tidy: ["--fingerprint", "--map"], report: ["--body"], check: ["--path"], supersede: [],
52
52
  };
53
53
  // For tidy, --log selects the log-redaction rule; tidy always writes its own LINT event. Check never appends an event.
54
54
  const values = valueOptions[command] ? [...valueOptions[command]!, ...(["tidy", "check"].includes(command) ? [] : ["--log"])] : undefined;
55
55
  if (!values) throw new Error("unknown writer command");
56
- const twoStep = ["move", "delete", "tidy"].includes(command);
56
+ const twoStep = ["merge", "move", "delete", "tidy"].includes(command);
57
57
  const booleans = ["--json", "--dry-run", ...(twoStep ? ["--confirm"] : []), ...(command === "link" ? ["--one-way"] : []), ...(command === "tidy" ? TIDY_RULES.map(rule => `--${rule}`).concat("--all") : [])];
58
58
  const flags: Record<string, string | boolean> = {}, positional: string[] = [];
59
59
  for (let i = 0; i < args.length; i++) {
@@ -108,6 +108,7 @@ export function runWriteCommand(command: string, args: string[], home: string, e
108
108
  case "frontmatter": operation = { op: "frontmatter", path: target, set: optional("--set") ? object(required("--set"), "set") : {}, unset: optional("--unset")?.split(","), expectedSha: optional("--expected-sha") }; break;
109
109
  case "link": operation = { op: "link", from: target, to: positional[2]!, relation: required("--relation") as Extract<WriteOp, { op: "link" }>["relation"], context: optional("--context"), bidirectional: !flags["--one-way"] }; break;
110
110
  case "supersede": operation = { op: "supersede", old: target, next: positional[2]! }; break;
111
+ case "merge": operation = { op: "merge", keep: target, absorb: positional[2]! }; break;
111
112
  case "move": operation = { op: "move", from: target, to: positional[2]! }; break;
112
113
  case "delete": operation = { op: "delete", path: target }; break;
113
114
  case "tidy": operation = { op: "tidy" }; break;
@@ -0,0 +1,63 @@
1
+ /** Shared path-based publication and descriptor-owned cleanup. These checks narrow races;
2
+ * Node fs cannot make identity checks and namespace mutations one atomic operation. */
3
+ import { fstatSync, linkSync, lstatSync, realpathSync, renameSync, unlinkSync } from "node:fs";
4
+ import { dirname, isAbsolute, relative, sep } from "node:path";
5
+
6
+ export class PublicationDrift extends Error {
7
+ constructor(readonly file: string, readonly published = false, readonly targetExists = false) {
8
+ super(`publication path identity or containment changed; ${published
9
+ ? "this step was published; stop concurrent writers, inspect the registered root, target and listed retained backups, restore the original plain parent directories, and recover the recorded write before another mutation"
10
+ : "this step was not published; stop concurrent writers, inspect the registered root and target, restore the original plain parent directories, and review any earlier applied changes before another mutation"}`);
11
+ }
12
+ }
13
+ export interface PublicationPath { root: string; file: string; parents: { path: string; identity: string }[] }
14
+ export type PublicationOperation = { kind: "rename" | "link"; temp: string } | { kind: "unlink" };
15
+ const identity = (s: { dev: bigint; ino: bigint }) => `${s.dev}:${s.ino}`;
16
+ const within = (root: string, file: string) => { const p = relative(root, file); return p === "" || !isAbsolute(p) && p !== ".." && !p.startsWith(`..${sep}`); };
17
+
18
+ export function capturePublicationPath(root: string, file: string): PublicationPath {
19
+ if (!within(root, file)) throw new PublicationDrift(file);
20
+ const parents: PublicationPath["parents"] = [];
21
+ for (let parent = dirname(file); ; parent = dirname(parent)) {
22
+ const stat = lstatSync(parent, { bigint: true });
23
+ if (!stat.isDirectory() || stat.isSymbolicLink() || !within(root, realpathSync(parent))) throw new PublicationDrift(file);
24
+ parents.push({ path: parent, identity: identity(stat) });
25
+ if (parent === root) break;
26
+ if (dirname(parent) === parent) throw new PublicationDrift(file);
27
+ }
28
+ return { root, file, parents };
29
+ }
30
+ function checkPublicationPath(path: PublicationPath, deleted: boolean, published = false): void {
31
+ try {
32
+ for (const parent of path.parents) {
33
+ const stat = lstatSync(parent.path, { bigint: true });
34
+ if (!stat.isDirectory() || stat.isSymbolicLink() || identity(stat) !== parent.identity || !within(path.root, realpathSync(parent.path))) throw new Error("parent drift");
35
+ }
36
+ try {
37
+ const stat = lstatSync(path.file);
38
+ if (!stat.isFile() || stat.isSymbolicLink() || !within(path.root, realpathSync(path.file))) throw new PublicationDrift(path.file, published, true);
39
+ } catch (error) { if (!deleted || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
40
+ } catch (error) {
41
+ if (error instanceof PublicationDrift) throw error;
42
+ throw new PublicationDrift(path.file, published);
43
+ }
44
+ }
45
+ export function publishFile(path: PublicationPath, operation: PublicationOperation, published: () => void): void {
46
+ // The target may be absent for create; existing-content guards remain the writer's responsibility.
47
+ checkPublicationPath(path, true);
48
+ if (operation.kind === "rename") renameSync(operation.temp, path.file);
49
+ else if (operation.kind === "link") linkSync(operation.temp, path.file);
50
+ else unlinkSync(path.file);
51
+ // Record persisted state before the post-publication guard can fail.
52
+ published();
53
+ checkPublicationPath(path, operation.kind === "unlink", true);
54
+ }
55
+
56
+ /** Caller keeps fd open throughout this call and closes it independently, including on failure. */
57
+ export function cleanupOwnedFile(file: string, fd: number): void {
58
+ const owned = fstatSync(fd, { bigint: true }), named = lstatSync(file, { bigint: true });
59
+ if (!owned.isFile() || !named.isFile() || named.isSymbolicLink() || identity(owned) !== identity(named)) {
60
+ throw new Error("owned file identity changed; replacement retained; inspect the temporary or lock path before manual recovery");
61
+ }
62
+ unlinkSync(file);
63
+ }
@@ -1,8 +1,8 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
- import { normalizeSource } from "./source.ts";
3
- import { parseFrontmatter, emitFrontmatter } from "./frontmatter.ts";
4
- import { LINK_RELATIONS, normalizeTarget, proseLines, rewriteLinkTargets, extractLinks, resolveLinks, type LinkNote } from "./links.ts";
5
- import type { PatchEdit, PlannedChange, WriteIssue, WriteOp } from "./write-types.ts";
2
+ import { normalizeSource, sourceReferences } from "./source.ts";
3
+ import { parseFrontmatter, emitFrontmatter, frontmatterReferences } from "./frontmatter.ts";
4
+ import { LINK_RELATIONS, normalizeTarget, proseLines, visibleProseLines, rewriteLinkTargets, extractLinks, resolveLinks, type LinkNote } from "./links.ts";
5
+ import { MAX_WRITE_BYTES, type MergeInboundLink, type MergePreview, type PatchEdit, type PlannedChange, type WriteIssue, type WriteOp } from "./write-types.ts";
6
6
  export class WriteRefusal extends Error {
7
7
  constructor(readonly issues: WriteIssue[]) { super(issues[0]?.message ?? "write refused"); }
8
8
  }
@@ -126,6 +126,173 @@ function mayHaveDoi(source: string): boolean {
126
126
  const header = source.slice(0, closing.exec(source)?.index ?? source.length);
127
127
  return /(?:^|[{\n,])[ \t]*(?:doi|["']doi["'])[ \t]*:|[\\!&*?]/.test(header);
128
128
  }
129
+ /** Shared date emission for validated note content, including promotion previews. */
130
+ export function stampNoteContent(source: string, today: string, create: boolean, warning?: (message: string) => void): string {
131
+ const doc = parseFrontmatter(source);
132
+ const dates = { updated: today, ...(create && !Object.hasOwn(doc.data, "created") ? { created: today } : {}) };
133
+ const references = frontmatterReferences(doc);
134
+ const skipStamp = (cause: string, nextStep?: string) => {
135
+ const repair = nextStep ?? "open this note in a text editor and rewrite the header as a block mapping with plain literal values" + (references.length ? ", replacing any aliases with their literal values and removing anchors" : "");
136
+ warning?.(`automatic dates were not set: ${cause}; ${repair}; later authored writes stamp updated automatically${create && !Object.hasOwn(doc.data, "created") ? "; set created explicitly in the repaired header if it was also skipped" : ""}`);
137
+ return source;
138
+ };
139
+ let candidate: string;
140
+ try { candidate = emitFrontmatter(doc, dates); }
141
+ catch (error) {
142
+ if (!(error instanceof Error) || error.message !== "frontmatter: editing requires a block mapping") throw error;
143
+ return skipStamp(references.length
144
+ ? "the header cannot be edited in place without rewriting comments, formatting or YAML anchor/alias relationships"
145
+ : "the header cannot be edited in place without rewriting comments or formatting");
146
+ }
147
+ if (Buffer.byteLength(candidate) > MAX_WRITE_BYTES && Buffer.byteLength(source) <= MAX_WRITE_BYTES) {
148
+ return skipStamp("adding automatic dates would exceed the 256 KiB note limit", "shorten this note to leave room below 256 KiB for automatic dates");
149
+ }
150
+ try {
151
+ const stamped = parseFrontmatter(candidate);
152
+ if (!isDeepStrictEqual(references, frontmatterReferences(stamped))) return skipStamp(references.length ? "date emission would change YAML anchor/alias relationships" : "the header could not be rewritten without changing its structure");
153
+ if (!isDeepStrictEqual(stamped.data, { ...doc.data, ...dates })) return skipStamp(references.length ? "date emission would alter metadata or YAML anchor/alias values" : "the header could not be rewritten without changing a value");
154
+ } catch { return skipStamp(references.length ? "the stamped YAML header would not parse after an anchor or alias changed" : "the stamped YAML header could not be parsed"); }
155
+ return candidate;
156
+ }
157
+ /** Date authored content only; mechanical rewrites retain their existing freshness. */
158
+ export function stampContentChanges(operation: WriteOp, changes: PlannedChange[], today: string, issues: WriteIssue[] = []): PlannedChange[] {
159
+ if (["check", "report", "move", "tidy", "sanitize"].includes(operation.op)) return changes;
160
+ return changes.map(change => {
161
+ if (change.after === null || change.after === change.before) return change;
162
+ if (operation.op === "merge" && change.path !== notePath(operation.keep) && change.path !== notePath(operation.absorb)) return change;
163
+ return { ...change, after: stampNoteContent(change.after, today, operation.op === "create", message => issues.push({ code: "V01", severity: "warning", path: change.path, message })) };
164
+ }).filter(change => change.before !== change.after);
165
+ }
166
+
167
+ /** Path-only reference identity shared by move and merge; alias-only links remain untouched. */
168
+ function referenceReplacement(notes: Map<string, string>, from: string, to: string): (target: string) => string | undefined {
169
+ const names = new Map<string, Set<string>>();
170
+ for (const [path, source] of notes) {
171
+ document(source, path);
172
+ const key = normalizeTarget(path.slice(6, -3)), values = names.get(key) ?? new Set<string>(); values.add(path); names.set(key, values);
173
+ }
174
+ return target => {
175
+ const candidates = names.get(normalizeTarget(target.replace(/^\.\//, "").replace(/^notes\//i, "").replace(/\.md$/i, "")));
176
+ return candidates?.size === 1 && candidates.has(from) ? to.slice(6, -3) : undefined;
177
+ };
178
+ }
179
+ /** Same metadata recursion and visible-body rewrite that move has always used. */
180
+ function rewriteNoteReferences(source: string, path: string, replace: (target: string) => string | undefined, inbound?: MergeInboundLink[], preserve: ReadonlySet<string> = new Set()): string {
181
+ const doc = document(source, path);
182
+ const record = (value: string, field: string, body = false) => {
183
+ if (!inbound) return;
184
+ for (const link of extractLinks(value)) {
185
+ const replacement = replace(link.target);
186
+ if (replacement !== undefined) inbound.push({ path, field, target: link.target, replacement, ...(body ? { line: link.line } : {}), ...(link.heading ? { heading: link.heading } : {}), ...(link.block ? { block: link.block } : {}) });
187
+ }
188
+ };
189
+ const rewriteValue = (value: unknown, field: string): unknown => {
190
+ if (typeof value === "string") { record(value, field); return rewriteLinkTargets(value, replace); }
191
+ if (Array.isArray(value)) return value.map((item, index) => rewriteValue(item, `${field}[${index}]`));
192
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, rewriteValue(item, `${field}.${key}`)]));
193
+ return value;
194
+ };
195
+ const changes: Record<string, unknown> = {};
196
+ for (const [key, value] of Object.entries(doc.data)) changes[key] = preserve.has(key) ? value : rewriteValue(value, key);
197
+ record(doc.body, "body", true);
198
+ const frontmatter = emitFrontmatter(doc, changes).slice(0, -doc.body.length || undefined);
199
+ return (doc.body.length ? frontmatter : emitFrontmatter(doc, changes)) + rewriteLinkTargets(doc.body, replace);
200
+ }
201
+ function supersededNote(source: string, path: string, next: string): string {
202
+ return emitFrontmatter(document(source, path), { status: "superseded", superseded_by: `[[${next.slice(6, -3)}]]` });
203
+ }
204
+ function topicKey(value: string): string { return normalizeTarget(value.slice(2, -2).trim().replace(/^\.\//, "").replace(/^notes\//i, "").replace(/\.md$/i, "")); }
205
+ function mergeTopics(value: unknown, path: string): string[] {
206
+ if (value === undefined) return [];
207
+ if (!Array.isArray(value) || value.some(topic => typeof topic !== "string" || !/^\[\[[^\]|#]+\]\]$/.test(topic))) refuse("V01", "merge topics must be a list of plain wiki targets; repair topics in this note before merging", path);
208
+ return value as string[];
209
+ }
210
+ /** Remove only a plain Topics list; unusual authored contents need an explicit repair, never silent deletion. */
211
+ function withoutMergeTopics(body: string, topics: string[], path: string): string {
212
+ const visible = mergeHeadingLines(body), raw = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
213
+ if (visible.some((line, index) => /^Topics[ \t]*$/i.test(line.trim()) && /^ {0,3}-+[ \t]*$/.test(visible[index + 1] ?? ""))) refuse("V05", "merge cannot consolidate a Setext Topics heading safely; convert it to a plain ## Topics list before merging", path);
214
+ const headings = visible.flatMap((line, index) => /^ {0,3}##[ \t]+Topics(?:[ \t]+#+)?[ \t]*$/i.test(line) ? [index] : []);
215
+ if (headings.length > 1) refuse("V05", "merge found multiple Topics sections; consolidate them into one matching topic list before merging", path);
216
+ const start = headings[0]; if (start === undefined) return body;
217
+ let end = start + 1;
218
+ while (end < raw.length && !/^ {0,3}#{1,2}(?:[ \t]+|$)/.test(visible[end] ?? "")) end++;
219
+ const found: string[] = [];
220
+ for (const line of raw.slice(start + 1, end)) {
221
+ if (!line.trim()) continue;
222
+ const wiki = /^[ \t]*(?:[-*+][ \t]+)?(\[\[[^\]|#]+\]\])[ \t]*(?:\r?\n)?$/.exec(line);
223
+ if (!wiki) refuse("V05", "merge cannot discard prose, headings or code inside Topics; move that content outside Topics and retry the merge", path);
224
+ found.push(topicKey(wiki[1]!));
225
+ }
226
+ const expected = topics.map(topicKey).sort(); found.sort();
227
+ if (found.length !== expected.length || found.some((value, index) => value !== expected[index])) refuse("V05", "merge Topics list does not match its metadata; align the body list with frontmatter topics before merging", path);
228
+ return raw.slice(0, start).join("") + raw.slice(end).join("");
229
+ }
230
+ /** Merge structural edits ignore raw HTML conservatively, through the next blank line. */
231
+ function mergeHeadingLines(body: string): string[] {
232
+ const raw = body.split(/\r?\n/); let html = false;
233
+ return visibleProseLines(body).map((line, index) => {
234
+ if (!raw[index]?.trim()) html = false;
235
+ else if (/^ {0,3}</.test(line)) html = true;
236
+ return html ? "" : line;
237
+ });
238
+ }
239
+ /** Remove only a leading title H1; demote other ATX headings and leave Setext/code/HTML untouched. */
240
+ function demoteMergeHeadings(body: string, removeLeadingTitle: boolean): string {
241
+ const visible = mergeHeadingLines(body), raw = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
242
+ const leading = raw.findIndex(line => line.trim());
243
+ return raw.map((line, index) => {
244
+ const heading = /^ {0,3}(#{1,6})(?:[ \t]+|$)/.exec(visible[index] ?? "");
245
+ if (!heading) return line;
246
+ if (removeLeadingTitle && index === leading && heading[1]!.length === 1 && /^ {0,3}#[ \t]+\S/.test(line)) return "";
247
+ return heading[1]!.length < 6 ? line.replace(/^( {0,3})(#+)/, "$1#$2") : line;
248
+ }).join("");
249
+ }
250
+ function mergeGap(body: string, newline: string): string {
251
+ if (body.endsWith("\n\n") || body.endsWith("\r\n\r\n")) return body;
252
+ return body + (body.endsWith("\n") ? newline : newline + newline);
253
+ }
254
+ /** Pure all-note merge plan, composed after rewriting existing references so its new provenance link is retained. */
255
+ export function planMerge(operation: Extract<WriteOp, { op: "merge" }>, notes: Map<string, string>): { changes: PlannedChange[]; preview: MergePreview; copiedBody: string } {
256
+ const keep = notePath(operation.keep), absorb = notePath(operation.absorb);
257
+ if (keep === absorb) refuse("V10", "merge endpoints must differ; choose separate keep and absorb notes", keep);
258
+ const kept = document(needed(notes, keep), keep), absorbed = document(needed(notes, absorb), absorb);
259
+ if (typeof kept.data.type !== "string" || !kept.data.type.trim() || kept.data.type !== absorbed.data.type || [kept.data.type, absorbed.data.type].some(type => type === "person" || type === "moc")) refuse("V01", "merge requires matching types other than person or moc; choose compatible notes", keep);
260
+ const replace = referenceReplacement(notes, absorb, keep), inboundLinks: MergeInboundLink[] = [], rewritten = new Map<string, string>();
261
+ for (const [path, source] of notes) {
262
+ try { rewritten.set(path, rewriteNoteReferences(source, path, replace, inboundLinks, path === keep ? new Set(["supersedes"]) : undefined)); }
263
+ catch (error) {
264
+ if (error instanceof WriteRefusal) throw error;
265
+ refuse("V01", "merge cannot rewrite this note's metadata losslessly; repair its YAML or convert the header to a block mapping, then request a fresh merge preview", path);
266
+ }
267
+ }
268
+ const keepDoc = document(rewritten.get(keep)!, keep), absorbDoc = document(rewritten.get(absorb)!, absorb);
269
+ const sources: string[] = [];
270
+ for (const [path, doc] of [[keep, keepDoc], [absorb, absorbDoc]] as const) if (doc.data.source !== undefined) {
271
+ let refs: string[];
272
+ try { refs = sourceReferences(doc.data.source).map(reference => reference.value); }
273
+ catch { refuse("V01", "merge source must contain at most 32 valid references; repair source entries in either note before merging", path); }
274
+ for (const value of refs) if (!sources.includes(value)) sources.push(value);
275
+ }
276
+ if (sources.length > 32) refuse("V01", "merge source union exceeds 32 entries; trim sources in either note first, then retry the merge", keep);
277
+ const keepTopics = mergeTopics(keepDoc.data.topics, keep), absorbTopics = mergeTopics(absorbDoc.data.topics, absorb), topics: string[] = [], seen = new Set<string>();
278
+ for (const topic of [...keepTopics, ...absorbTopics]) if (!seen.has(topicKey(topic))) { seen.add(topicKey(topic)); topics.push(topic); }
279
+ const newline = /\r?\n/.exec(keepDoc.body)?.[0] ?? "\n";
280
+ const originalLeadingLine = absorbed.body.split(/\r?\n/).find(line => line.trim()) ?? "";
281
+ const removeLeadingTitle = /^ {0,3}#[ \t]+\S/.test(originalLeadingLine);
282
+ const first = withoutMergeTopics(keepDoc.body, keepTopics, keep), second = demoteMergeHeadings(withoutMergeTopics(absorbDoc.body, absorbTopics, absorb), removeLeadingTitle);
283
+ const body = mergeGap(mergeGap(first, newline) + `## Merged from [[${absorb.slice(6, -3)}]]${newline}${newline}` + second, newline) + `## Topics${newline}${newline}` + topics.map(topic => `- ${topic}${newline}`).join("");
284
+ if (Buffer.byteLength(body) > MAX_WRITE_BYTES) refuse("V09", "merged body exceeds 256 KiB; shorten either note's content before retrying the merge", keep);
285
+ try {
286
+ const metadata = emitFrontmatter(keepDoc, { source: sources.length ? sources : undefined, topics });
287
+ rewritten.set(keep, (parseFrontmatter(metadata).frontmatter ?? "") + body);
288
+ rewritten.set(absorb, supersededNote(rewritten.get(absorb)!, absorb, keep));
289
+ } catch { refuse("V01", "merge metadata cannot be edited losslessly; convert endpoint headers to editable block mappings and retry the merge", keep); }
290
+ const changes = [...rewritten].filter(([path, after]) => after !== notes.get(path)).map(([path, after]) => ({ path, before: notes.get(path)!, after })).sort((a, b) => a.path.localeCompare(b.path));
291
+ const oversized = changes.find(change => Buffer.byteLength(change.after) > MAX_WRITE_BYTES);
292
+ if (oversized) refuse("V09", "merged file or inbound rewrite exceeds 256 KiB; shorten the affected note before retrying the merge", oversized.path);
293
+ return { changes, preview: { keep, absorb, body, source: sources, topics, inboundLinks }, copiedBody: second };
294
+ }
295
+
129
296
  /** Plan transformations in memory. This function never touches files. */
130
297
  export function planOperation(operation: WriteOp, notes: Map<string, string>, reportBefore?: string | null): PlannedChange[] {
131
298
  const planned = new Map<string, PlannedChange>();
@@ -226,35 +393,18 @@ export function planOperation(operation: WriteOp, notes: Map<string, string>, re
226
393
  case "supersede": {
227
394
  const old = existing(operation.old), next = existing(operation.next);
228
395
  if (old.path === next.path) refuse("V10", "supersession endpoints must differ");
229
- set(old.path, emitFrontmatter(document(old.source, old.path), { status: "superseded", superseded_by: `[[${next.path.slice(6, -3)}]]` }));
396
+ set(old.path, supersededNote(old.source, old.path, next.path));
230
397
  set(next.path, appendSection(next.source, "Relevant Notes", `- Supersedes [[${old.path.slice(6, -3)}]]`, next.path));
231
398
  break;
232
399
  }
400
+ case "merge": return planMerge(operation, notes).changes;
233
401
  case "delete": { const { path } = existing(operation.path); set(path, null); break; }
234
402
  case "move": {
235
403
  const fromPath = moveSourcePath(operation.from, notes), from = { path: fromPath, source: needed(notes, fromPath) }, to = notePath(operation.to);
236
404
  if (notes.has(to)) refuse("V08", "move destination already exists", to);
237
- const names = new Map<string, Set<string>>();
238
- for (const [path, source] of notes) {
239
- document(source, path); // Every note must still parse before a move rewrites links.
240
- // Links resolve by path only, so alias-only links are left untouched.
241
- const key = normalizeTarget(path.slice(6, -3)), values = names.get(key) ?? new Set<string>(); values.add(path); names.set(key, values);
242
- }
243
- const replace = (target: string): string | undefined => {
244
- const candidates = names.get(normalizeTarget(target.replace(/^\.\//, "").replace(/^notes\//i, "").replace(/\.md$/i, "")));
245
- return candidates?.size === 1 && candidates.has(from.path) ? to.slice(6, -3) : undefined;
246
- };
247
- const rewriteValue = (value: unknown): unknown => {
248
- if (typeof value === "string") return rewriteLinkTargets(value, replace);
249
- if (Array.isArray(value)) return value.map(rewriteValue);
250
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, rewriteValue(item)]));
251
- return value;
252
- };
405
+ const replace = referenceReplacement(notes, from.path, to);
253
406
  for (const [path, source] of notes) {
254
- const doc = document(source, path), changes: Record<string, unknown> = {};
255
- for (const [key, value] of Object.entries(doc.data)) changes[key] = rewriteValue(value);
256
- const frontmatter = emitFrontmatter(doc, changes).slice(0, -doc.body.length || undefined);
257
- const output = (doc.body.length ? frontmatter : emitFrontmatter(doc, changes)) + rewriteLinkTargets(doc.body, replace);
407
+ const output = rewriteNoteReferences(source, path, replace);
258
408
  if (path === from.path) { set(path, null); set(to, output); }
259
409
  else set(path, output);
260
410
  }
@@ -1,3 +1,4 @@
1
+ import type { CanonRowMatch } from "./canon-tables.ts";
1
2
  /**
2
3
  * Text renderers for writes, two-step previews and promotion (#114): one result line, then changes, issues, the
3
4
  * log receipt and, for a preview, the exact confirm command. Note bodies and drafts are never printed; `--json` has them.
@@ -9,7 +10,7 @@ import type { OrgPromoteResult } from "./org-promote.ts";
9
10
  import type { SyncResult } from "./sync.ts";
10
11
  import type { PromoteResult } from "./promote.ts";
11
12
  import { notePath } from "./write-operations.ts";
12
- import { blocks, clean, fields, issueTable, nextCommand, paragraph, plural, shellWord, table, type TextOptions, type Tone } from "./text-output.ts";
13
+ import { blocks, clean, fields, heading, issueTable, nextCommand, paragraph, plural, shellWord, table, type TextOptions, type Tone } from "./text-output.ts";
13
14
 
14
15
  /** The words the command was run with (`[command, ...args]`, no `--color`) and its positional arguments. */
15
16
  export interface WriteContext { argv: string[]; positional: string[] }
@@ -17,6 +18,7 @@ type Candidates = { projects: { project: string; candidates: { id: string; proje
17
18
 
18
19
  const line = (text: string, o: TextOptions, t?: Tone) => paragraph(text, o, t);
19
20
  const list = (label: string, items: readonly string[] | undefined) => items?.length ? [`${label}:`, ...items.map(item => ` - ${clean(item)}`)].join("\n") : undefined;
21
+ const canonList = (rows: readonly CanonRowMatch[] | undefined) => list("canonical rows", rows?.map(row => `${row.path}:${row.line} ${row.key}: ${row.row}`));
20
22
  const short = (sha: string | null) => sha ? sha.slice(0, 12) : "-";
21
23
  const action = (c: ChangeReceipt) => c.beforeSha === null ? "create" : c.sha256 === null ? "delete" : "update";
22
24
  const errors = (issues: readonly WriteIssue[]) => issues.filter(issue => issue.severity === "error").length;
@@ -40,7 +42,7 @@ function logLine(log: LogReceipt | undefined, o: TextOptions, label = "log"): st
40
42
 
41
43
  const VERBS: Record<string, [string, string]> = {
42
44
  new: ["create", "created"], patch: ["patch", "patched"], append: ["append to", "appended to"], frontmatter: ["update the frontmatter of", "updated the frontmatter of"],
43
- link: ["link", "linked"], supersede: ["supersede", "superseded"], move: ["move", "moved"], delete: ["delete", "deleted"], report: ["write", "wrote"],
45
+ link: ["link", "linked"], supersede: ["supersede", "superseded"], merge: ["merge", "merged"], move: ["move", "moved"], delete: ["delete", "deleted"], report: ["write", "wrote"],
44
46
  };
45
47
  function what(command: string, changes: ChangeReceipt[], targets: string[], past: boolean): string {
46
48
  const verb = VERBS[command]?.[past ? 1 : 0] ?? command;
@@ -48,13 +50,14 @@ function what(command: string, changes: ChangeReceipt[], targets: string[], past
48
50
  const deleted = changes.filter(c => action(c) === "delete").map(c => c.path), created = changes.filter(c => action(c) === "create").map(c => c.path);
49
51
  const updated = changes.filter(c => action(c) === "update").map(c => c.path);
50
52
  if (command === "move") return `${verb} ${deleted[0] ?? stem(targets[0])} to ${created[0] ?? stem(targets[1])}${others(updated, past ? "rewrote links in" : "rewrite links in")}`;
53
+ if (command === "merge") return `${verb} ${stem(targets[1])} into ${stem(targets[0])}${others(updated.filter(path => path !== stem(targets[0]) && path !== stem(targets[1])), past ? "rewrote links in" : "rewrite links in")}`;
51
54
  if (command === "delete") return `${verb} ${deleted[0] ?? stem(targets[0])}${others(updated, past ? "updated" : "update")}`;
52
55
  if (command === "link") return `${verb} ${stem(targets[0])} and ${stem(targets[1])}`;
53
56
  if (command === "supersede") return `${verb} ${stem(targets[0])} with ${stem(targets[1])}`;
54
57
  return `${verb} ${changes[0]?.path ?? (command === "report" ? targets[0] : stem(targets[0]))}`;
55
58
  }
56
59
 
57
- /** `new`, `patch`, `append`, `frontmatter`, `link`, `supersede`, `move`, `delete`, `report` and `check`. */
60
+ /** `new`, `patch`, `append`, `frontmatter`, `link`, `supersede`, `merge`, `move`, `delete`, `report` and `check`. */
58
61
  export function renderWriteReceipt(r: WriteReceipt, o: TextOptions, ctx: WriteContext): string {
59
62
  const command = ctx.argv[0]!, targets = ctx.positional.slice(1), issues = issueTable(r.issues, o);
60
63
  if (command === "check") {
@@ -62,18 +65,26 @@ export function renderWriteReceipt(r: WriteReceipt, o: TextOptions, ctx: WriteCo
62
65
  const verdict = r.ok ? `ok: ${path} passes validation${w ? ` (${plural(w, "warning")})` : ""}` : `fail: ${path} has ${plural(e, "error")}${w ? ` and ${plural(w, "warning")}` : ""}`;
63
66
  return blocks(issues, line(verdict, o, r.ok ? "ok" : "fail"));
64
67
  }
65
- const twoStep = command === "move" || command === "delete";
68
+ const twoStep = command === "merge" || command === "move" || command === "delete";
69
+ const hasState = r.changes.some(change => change.applied !== undefined);
70
+ const appliedSummary = hasState ? r.changes.filter(change => change.applied).map(change => change.path).join(", ") : what(command, r.changes, targets, true);
66
71
  let head: string, t: Tone;
67
- if (!r.ok) [head, t] = r.applied ? [`failed after writing: ${what(command, r.changes, targets, true)}; see the issues`, "fail"] : ["refused: nothing written", "fail"];
72
+ if (!r.ok) [head, t] = r.applied ? [`failed after writing: ${appliedSummary}; see the issues`, "fail"] : ["refused: nothing written", "fail"];
68
73
  else if (r.preview) [head, t] = [`dry run: would ${what(command, r.changes, targets, false)}`, "info"];
69
74
  else if (r.unchanged) [head, t] = ["unchanged: links already present", "muted"];
70
75
  else if (!r.applied) [head, t] = ["unchanged: nothing to write", "muted"];
71
76
  else [head, t] = [what(command, r.changes, targets, true), "ok"];
72
77
  const one = r.changes.length === 1 && r.ok && !r.preview && r.changes[0]!.sha256 ? fields([["sha256", r.changes[0]!.sha256]], o) : undefined;
73
- const changes = r.changes.length > 1 ? table(["PATH", "ACTION", "BYTES", "SHA"], r.changes.map(c => [c.path, action(c), c.sha256 === null ? "-" : c.bytes, short(c.sha256)]), o) : undefined;
78
+ const changes = r.changes.length > 1 || hasState ? table(["PATH", "ACTION", "BYTES", "SHA", ...(hasState ? ["STATE"] : [])], r.changes.map(c => [c.path, action(c), c.sha256 === null ? "-" : c.bytes, short(c.sha256), ...(hasState ? [c.applied ? "applied" : "not applied"] : [])]), o) : undefined;
74
79
  const log = r.log ? logLine(r.log, o) : r.ok && r.preview ? line(twoStep ? "log: written on confirm" : "log: none (dry run)", o, "muted") : undefined;
75
80
  const confirm = twoStep && r.ok && r.preview && r.fingerprint ? nextCommand("confirm", confirmCommand(ctx.argv, r.fingerprint), o) : undefined;
76
- return blocks([line(head, o, t), one].filter(Boolean).join("\n"), changes, issues, list("possible duplicates", r.possibleDuplicates), log, confirm);
81
+ const merge = r.merge && r.preview ? blocks(
82
+ fields([["keep", r.merge.keep], ["absorb", r.merge.absorb]], o),
83
+ line(`merged body: ${plural(Buffer.byteLength(r.merge.body), "byte")}; --json shows the full body`, o, "muted"),
84
+ list("merged source", r.merge.source), list("merged topics", r.merge.topics),
85
+ r.merge.inboundLinks.length ? heading("INBOUND LINKS", o) + "\n" + table(["PATH", "FIELD", "TARGET", "REPLACEMENT", "LINE"], r.merge.inboundLinks.map(link => [link.path, link.field, link.target + (link.block ? `#^${link.block}` : link.heading ? `#${link.heading}` : ""), link.replacement + (link.block ? `#^${link.block}` : link.heading ? `#${link.heading}` : ""), link.line ?? "-"]), o) : line("inbound links: none", o, "muted"),
86
+ ) : undefined;
87
+ return blocks([line(head, o, t), one].filter(Boolean).join("\n"), changes, merge, issues, list("possible duplicates", r.possibleDuplicates), list("retained backups", r.retainedBackups), log, confirm);
77
88
  }
78
89
 
79
90
  /** `tidy`: counts per rule and the notes touched, then the confirm command. */
@@ -106,7 +117,7 @@ export function renderOrgPromote(r: OrgPromoteResult, o: TextOptions, ctx: Write
106
117
  const lint = r.lint ? line(`org lint: ${r.lint.passed ? "passed" : "failed"}${r.lint.summary ? ` (${r.lint.summary})` : ""}`, o, r.lint.passed ? "ok" : "fail") : undefined;
107
118
  const logs = r.logs ? [logLine(r.logs.target ?? undefined, o, "target log"), logLine(r.logs.source ?? undefined, o, "source log")].filter(Boolean).join("\n") : undefined;
108
119
  const confirm = r.ok && r.preview && r.fingerprint ? nextCommand("confirm", confirmCommand(ctx.argv, r.fingerprint), o) : undefined;
109
- return blocks(line(head, o, t), issueTable(issues, o), list("dropped links", r.droppedLinks), lint, logs, confirm);
120
+ return blocks(line(head, o, t), issueTable(issues, o), list("dropped links", r.droppedLinks), canonList(r.canonRowMatches), list("canonical table warnings", r.canonTableWarnings), list("choices", r.choices), lint, logs, confirm);
110
121
  }
111
122
 
112
123
  /** `sync <vault>`. */
@@ -146,6 +157,6 @@ export function renderPromote(r: PromoteResult, o: TextOptions, ctx: WriteContex
146
157
  const info = fields([["linked", r.linked ?? ""]], o);
147
158
  const hint = edited && r.preview ? line("edited text is only previewed: save it and confirm with --body <file> and this fingerprint", o, "warn") : undefined;
148
159
  const command = r.ok && r.preview && !r.alreadyLinked && r.fingerprint ? confirmCommand(ctx.argv, r.fingerprint, edited ? ["--edit"] : []) : undefined;
149
- return blocks([line(head, o, t), info].filter(Boolean).join("\n"), draft, issueTable(r.issues, o), list("possible duplicates", r.possibleDuplicates), list("choices", r.choices),
160
+ return blocks([line(head, o, t), info].filter(Boolean).join("\n"), draft, issueTable(r.issues, o), list("possible duplicates", r.possibleDuplicates), canonList(r.canonRowMatches), list("canonical table warnings", r.canonTableWarnings), list("choices", r.choices),
150
161
  logLine(r.note?.log, o), hint, command && nextCommand("confirm", edited ? command.replace(/ --confirm /, " --body <file> --confirm ") : command, o));
151
162
  }
@@ -1,7 +1,10 @@
1
1
  import type { PiiSurface } from "./config.ts";
2
2
  import type { LogEvent, LogReceipt } from "./log-types.ts";
3
3
  import type { VaultSpec, VmemConfig } from "./config.ts";
4
+ export const MAX_WRITE_BYTES = 256 * 1024;
4
5
  export interface PatchEdit { oldString: string; newString: string }
6
+ export interface MergeInboundLink { path: string; field: string; target: string; replacement: string; line?: number; heading?: string; block?: string }
7
+ export interface MergePreview { keep: string; absorb: string; body: string; source: string[]; topics: string[]; inboundLinks: MergeInboundLink[] }
5
8
  export type WriteOp =
6
9
  | { op: "check"; path: string; text: string }
7
10
  | { op: "create"; path: string; frontmatter: Record<string, unknown>; body?: string }
@@ -11,6 +14,7 @@ export type WriteOp =
11
14
  | { op: "frontmatter"; path: string; set: Record<string, unknown>; unset?: string[]; expectedSha?: string }
12
15
  | { op: "link"; from: string; to: string; relation: "supports" | "contradicts" | "extends" | "applies-to" | "context-for"; context?: string; bidirectional?: boolean }
13
16
  | { op: "supersede"; old: string; next: string }
17
+ | { op: "merge"; keep: string; absorb: string }
14
18
  | { op: "move"; from: string; to: string }
15
19
  | { op: "delete"; path: string }
16
20
  | { op: "tidy" }
@@ -38,7 +42,7 @@ export interface ValidationContext {
38
42
  /** PII surface for content screening; `notes` unless an internal caller (org promotion) sets it. */
39
43
  piiSurface?: PiiSurface;
40
44
  }
41
- export interface ChangeReceipt { path: string; beforeSha: string | null; sha256: string | null; bytes: number }
45
+ export interface ChangeReceipt { applied?: boolean; path: string; beforeSha: string | null; sha256: string | null; bytes: number }
42
46
  export interface WriteReceipt {
43
47
  ok: boolean;
44
48
  applied: boolean;
@@ -49,7 +53,10 @@ export interface WriteReceipt {
49
53
  fingerprint?: string;
50
54
  preview?: boolean;
51
55
  possibleDuplicates?: string[];
56
+ merge?: MergePreview;
52
57
  indexUpdated: boolean;
58
+ /** Original relative names of backups retained for recovery after drift/failed rollback. */
59
+ retainedBackups?: string[];
53
60
  logged?: boolean;
54
61
  log?: LogReceipt;
55
62
  }