@catheadowl/md-tools 0.0.0-stage → 0.1.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.
@@ -0,0 +1,864 @@
1
+ /**
2
+ * Rename transaction kernel: rebaseHref (a document-relative
3
+ * href from a source file to an absolute target) plus planRename/applyRenamePlan
4
+ * (plan-then-apply, "工作树绝不半改"). Pure lib — no ctx, node:test-able.
5
+ *
6
+ * L1 explicit rename: the caller passes an authoritative oldPath → newPath.
7
+ * L2/L3/L4 (git rename detection / content similarity / agent fallback) are
8
+ * gate-side (路 B) and out of scope here.
9
+ *
10
+ * A pending move's source must carry tracked content: `git mv` stages the
11
+ * move, and a source with nothing tracked at/under it — a never-added file,
12
+ * or the reversed post-hoc pair (old = the untracked file standing on disk,
13
+ * new = the vanished tracked path) — refuses whole at plan time with a code
14
+ * the remedy exits key on. A `git mv` failure at apply time (the world
15
+ * changed between plan and apply) surfaces as `RenameApplyError`: code, git's
16
+ * own message, and the pairs that already moved — never raw spawn text.
17
+ *
18
+ * Post-hoc repair: when the move ALREADY happened and git can witness it —
19
+ * oldPath missing with newPath present (staged `R old→new`, a `D old` whose
20
+ * shifted new-side counterpart exists on disk, or old recorded in the HEAD
21
+ * tree when the worktree shows nothing — the window closes once the move is
22
+ * committed), or a self-nesting pair (newPath inside oldPath,
23
+ * the dir→dir/sub sink-down) whose old path survives on disk only as the
24
+ * moved subtree's ancestor — the same (old, new) pair plans a link-only
25
+ * repair: no `git mv`, in-links resolved lexically (existence-free, never
26
+ * silently dropped), out-links read at the new position and resolved against
27
+ * the old baseline, scoped to the git-witnessed moved files only (an
28
+ * unrelated neighbor under newPath is not part of the move). Without evidence
29
+ * the plan refuses whole — no guessing, no restore. The self-nesting geometry
30
+ * guard (`new path is inside the old path`) stands exactly where no repair is
31
+ * possible: the pending move, where the physical danger is real.
32
+ *
33
+ * Opt-in asserted repair (`replay: true`): the caller holds out-of-band proof
34
+ * (e.g. a rename record from history) and asserts the pair completed — the
35
+ * assertion replaces the git witness entirely, which is the same authority the
36
+ * pending mode grants every caller pair. The moved set is the declared pair's
37
+ * projection (everything Markdown under the new path mapped back), so an
38
+ * unproven neighbor under newPath joins the move BY DECLARATION — the
39
+ * git-witnessed scoping above is a default-window guarantee the caller
40
+ * explicitly takes over here.
41
+ *
42
+ * Informational history evidence: the no-evidence refusal and the plain
43
+ * old-path-missing refusal each spend one `git log` at refusal time and
44
+ * attach the findings to the conflict (`historyEvidence` — records verbatim,
45
+ * ambiguity included; the probe-shape manifest is
46
+ * `RENAME_HISTORY_EVIDENCE_SHAPES`). Information face, not verdict face: the
47
+ * refusals stand unchanged, and success paths never pay the probe.
48
+ *
49
+ * The data plane reuses the mdast seams (extractReferences / resolveReference /
50
+ * rebaseDestination): a reference is located byte-exactly and its destination
51
+ * substring replaced, preserving the fragment/query suffix and every other byte.
52
+ * When the authored label is the destination written out — the path, its last
53
+ * segment, with or without `.md` — the label is recomputed the same way: a
54
+ * mirror is re-derived, never guessed (`relabelFor`), and any other label is
55
+ * author prose and stays byte-untouched.
56
+ *
57
+ * Multi-pair planning (`planSink`): sinking a directory's
58
+ * contents one level down is planned as one joint transaction over every child
59
+ * pair — links between moved siblings keep their relative geometry because
60
+ * every href is computed against the FINAL positions in a single pass, which
61
+ * sequential per-pair planning cannot offer (each intermediate plan would see
62
+ * a half-moved tree). A plain rename is the one-pair case of the same core.
63
+ *
64
+ * Opt-in textual rebase (`textual: true`): non-link
65
+ * renderings of the moved path — tree-diagram lines, code spans, heading path
66
+ * strings — join the same plan through the textual seam (`textual.ts`). Default
67
+ * off: old paths in historical records are true statements; rewriting them is
68
+ * falsification unless declared. Frozen linkage mirrors the link half: a frozen
69
+ * source's would-be textual rewrites become reported skips.
70
+ */
71
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
72
+ import { basename, dirname, relative, resolve } from 'node:path';
73
+ import { GitMoveError, gitGrep, gitLogLastTouched, gitLogRenameRecords, gitMove, gitStatusPorcelain, gitTopLevel, gitTrackedUnder, gitTreeHas } from './git.js';
74
+ import { splitMarkdownUrlTarget } from './markdown.js';
75
+ import { scanTextualOccurrences } from './textual.js';
76
+ import { extractReferences, pathInside, posixRelative, resolveReference, resolveReferenceLexically, } from './resolve.js';
77
+ /** Characters that cannot appear in a bare document-relative markdown target. */
78
+ const BARE_DESTINATION_UNSAFE = /[\s()<>]/;
79
+ /**
80
+ * Stable machine identifiers for every whole-plan refusal this kernel can
81
+ * emit. Contract identifiers, additive-only: a code is never renamed, never
82
+ * reused for a different meaning, and never derived from wording. Consumers
83
+ * that branch on the conflict kind (remedy attachment, description
84
+ * enumeration, output routing) must branch on the code, never on the reason
85
+ * text.
86
+ */
87
+ export const RENAME_CONFLICT_CODES = [
88
+ 'repo-root',
89
+ 'outside-repo',
90
+ 'old-path-missing',
91
+ 'old-path-untracked',
92
+ 'new-path-exists',
93
+ 'self-nesting',
94
+ 'no-rename-evidence',
95
+ 'sink-source-not-directory',
96
+ 'sink-no-children',
97
+ ];
98
+ /**
99
+ * Surface-neutral wording for each conflict code — the single source of the
100
+ * `reason` string every refusal carries. Model-facing projections may quote
101
+ * these verbatim; they must not re-derive competing wording for the same
102
+ * fact. Consumers keying a map over the codes stay complete by construction:
103
+ * a new code with no table entry fails to compile.
104
+ */
105
+ export const RENAME_CONFLICT_MESSAGES = {
106
+ 'repo-root': 'cannot rename the repository root',
107
+ 'outside-repo': 'rename outside the repository',
108
+ 'old-path-missing': 'old path does not exist',
109
+ 'old-path-untracked': 'old path is not tracked by git',
110
+ 'new-path-exists': 'new path already exists',
111
+ 'self-nesting': 'new path is inside the old path',
112
+ 'no-rename-evidence': 'no evidence of a completed rename from the old path to the new path',
113
+ 'sink-source-not-directory': 'sink source is not an existing directory',
114
+ 'sink-no-children': 'directory has no children to sink',
115
+ };
116
+ /**
117
+ * Conflict reason when git cannot witness that the (old, new) pair already
118
+ * completed — oldPath missing without evidence, or a self-nesting pair whose
119
+ * old path still stands while what sits under new is indistinguishable from
120
+ * a copy (D1: refuse with a remedy hint, never guess or restore). The remedy
121
+ * wording belongs to the plugin output layer; this lib only emits the
122
+ * structured reason. Alias of the message-table entry for consumers already
123
+ * branching on the constant.
124
+ */
125
+ export const REASON_NO_RENAME_EVIDENCE = RENAME_CONFLICT_MESSAGES['no-rename-evidence'];
126
+ /** Document-relative href from a source file's directory to an absolute target. */
127
+ export function rebaseHref(fromFile, toAbs) {
128
+ return posixRelative(dirname(fromFile), toAbs);
129
+ }
130
+ /**
131
+ * The history-evidence probe shapes, in the order the refusal branches attach
132
+ * them — the informational payload's schema manifest (surface-neutral
133
+ * summaries; model-facing descriptions project these instead of re-deriving
134
+ * the probe conditions).
135
+ */
136
+ export const RENAME_HISTORY_EVIDENCE_SHAPES = [
137
+ { shape: 'pair-rename-records', summary: 'direct R records between the pair from git log rename detection' },
138
+ { shape: 'old-path-history', summary: 'whether the old path has any git history (never tracked = likely a typo)' },
139
+ ];
140
+ function isInside(dir, target) {
141
+ return pathInside(dir, target);
142
+ }
143
+ /** Shift one path under `old` to the corresponding path under `new`. */
144
+ function shiftPrefix(old, next, target) {
145
+ return resolve(next, relative(old, target));
146
+ }
147
+ /** Markdown files at or under `path` (recursive, pure fs — no git spawn). */
148
+ function listMarkdownUnder(path) {
149
+ const out = [];
150
+ const walk = (dir) => {
151
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
152
+ const abs = resolve(dir, entry.name);
153
+ if (entry.isDirectory())
154
+ walk(abs);
155
+ else if (entry.isFile() && abs.toLowerCase().endsWith('.md'))
156
+ out.push(abs);
157
+ }
158
+ };
159
+ if (statSync(path).isDirectory())
160
+ walk(path);
161
+ else if (path.toLowerCase().endsWith('.md'))
162
+ out.push(path);
163
+ return out;
164
+ }
165
+ /**
166
+ * Apply a set of byte edits to one source. Edits are non-overlapping (distinct
167
+ * AST nodes / textual tokens), so applying in descending start order keeps
168
+ * every remaining edit's offsets valid in the evolving buffer. Within one
169
+ * reference the label always sits strictly before the destination; textual
170
+ * tokens live in zones link syntax never occupies — the invariant is uniform.
171
+ */
172
+ function applyEdits(source, edits) {
173
+ let out = source;
174
+ for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
175
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
176
+ }
177
+ return out;
178
+ }
179
+ /** The byte edits one committed link rewrite contributes (destination splice + optional mirror-label splice). */
180
+ function rewriteEdits({ reference, newHref, newLabel }) {
181
+ const edits = [{ start: reference.start, end: reference.end, text: newHref + splitMarkdownUrlTarget(reference.url).suffix }];
182
+ if (newLabel !== undefined && reference.label !== undefined) {
183
+ edits.push({ start: reference.label.start, end: reference.label.end, text: newLabel });
184
+ }
185
+ return edits;
186
+ }
187
+ /** Characters that would break the label syntax if written inside `[...]` verbatim. */
188
+ const LABEL_UNSAFE = /[[\]\\\r\n]/;
189
+ /** `docs/guide.md` → `docs/guide`; a path without the extension is unchanged. */
190
+ function withoutMarkdownExtension(path) {
191
+ return path.toLowerCase().endsWith('.md') ? path.slice(0, -3) : path;
192
+ }
193
+ /** `docs/guide.md` → `guide.md`. */
194
+ function lastSegment(path) {
195
+ return path.slice(path.lastIndexOf('/') + 1);
196
+ }
197
+ /**
198
+ * The label renderings a rename may recompute: each writes the reference's own
199
+ * destination the way a reader addresses it. The list is closed on purpose — a
200
+ * label that is none of these is author prose, and prose is never rewritten.
201
+ * Name renderings come first: when several match, the destination was a bare
202
+ * filename in the link's own directory, and a same-directory link labels the
203
+ * FILE, not the path it happened to be reachable by (see `relabelFor`).
204
+ */
205
+ const MIRRORED_LABELS = [
206
+ lastSegment,
207
+ path => withoutMarkdownExtension(lastSegment(path)),
208
+ path => path,
209
+ withoutMarkdownExtension,
210
+ ];
211
+ /**
212
+ * The label a rewrite must carry: when `label` is one of `MIRRORED_LABELS` of
213
+ * the reference's current destination, the same rendering recomputed on the new
214
+ * destination — the mirror relation is re-derived, not guessed at.
215
+ *
216
+ * `undefined` means "leave the label alone", for three deterministic reasons:
217
+ * no rendering matched (author prose), a matched rendering of the new
218
+ * destination already equals the label (a pure move — the mirror still holds,
219
+ * so zero bytes change), or every matched rendering of the new destination is
220
+ * unrepresentable inside `[...]`.
221
+ *
222
+ * Several renderings can match only where the authored destination was a bare
223
+ * filename (identity and last segment then read the same); the earliest entry
224
+ * wins, so the label keeps the author's own shape — `[a](a.md)` follows the
225
+ * target's new NAME with no extension, `[a.md](a.md)` with one, and neither
226
+ * turns into a path.
227
+ * @param label - the authored label text (brackets excluded).
228
+ * @param oldPath - the reference's current destination path (suffix stripped).
229
+ * @param newPath - the rebased destination path.
230
+ */
231
+ export function relabelFor(label, oldPath, newPath) {
232
+ let chosen;
233
+ let mirrorsNewDestination = false;
234
+ for (const render of MIRRORED_LABELS) {
235
+ if (render(oldPath) !== label)
236
+ continue;
237
+ const next = render(newPath);
238
+ if (LABEL_UNSAFE.test(next))
239
+ continue;
240
+ if (next === label)
241
+ mirrorsNewDestination = true;
242
+ else
243
+ chosen ??= next;
244
+ }
245
+ return mirrorsNewDestination ? undefined : chosen;
246
+ }
247
+ /**
248
+ * Every whole-plan refusal, built from the code so `reason` can never drift
249
+ * from the message table. All rename refusals are plan-level (line 0, no
250
+ * single reference to point at).
251
+ */
252
+ function conflict(file, code, historyEvidence) {
253
+ return historyEvidence === undefined
254
+ ? { file, line: 0, url: '', code, reason: RENAME_CONFLICT_MESSAGES[code] }
255
+ : { file, line: 0, url: '', code, reason: RENAME_CONFLICT_MESSAGES[code], historyEvidence };
256
+ }
257
+ function skip(file, ref, reason) {
258
+ return { file, line: ref.line, url: ref.url, reason };
259
+ }
260
+ /**
261
+ * Shared tail of every rewrite site (all four passes): verify the rebased
262
+ * destination is representable, attach the mirrored label when the authored one
263
+ * renders the destination, then record the rewrite. One helper so the label
264
+ * rule can never drift between passes.
265
+ */
266
+ function recordRewrite(file, ref, newHref, rewrites, skips) {
267
+ if (BARE_DESTINATION_UNSAFE.test(newHref)) {
268
+ skips.push(skip(file, ref, `rebased href ${JSON.stringify(newHref)} is not representable as a bare markdown target`));
269
+ return;
270
+ }
271
+ const label = ref.label;
272
+ const newLabel = label === undefined ? undefined : relabelFor(label.text, splitMarkdownUrlTarget(ref.url).path, newHref);
273
+ rewrites.push(newLabel === undefined ? { reference: ref, newHref } : { reference: ref, newHref, newLabel });
274
+ }
275
+ /** Skip reason when a rewrite was planned but its source file is frozen (read-only by policy). */
276
+ const REASON_FROZEN_SOURCE = 'source file is frozen (read-only by policy; reference left unchanged)';
277
+ /** Same contract for the opt-in textual half: the occurrence stays as authored. */
278
+ const REASON_FROZEN_TEXTUAL = 'source file is frozen (read-only by policy; textual occurrence left unchanged)';
279
+ /**
280
+ * Commit one source's planned rewrites: nothing to do when there are none; a
281
+ * frozen source converts each would-be rewrite (link or textual) into a
282
+ * reported skip; otherwise the file is written at `file` with every edit
283
+ * spliced in one pass, and each label / textual occurrence it rewrote is
284
+ * reported against `reportFile` (the pre-move path for L1 out-links, the
285
+ * post-move path elsewhere — each pass's existing reporting convention).
286
+ */
287
+ function commitRewrites(file, reportFile, source, rewrites, textuals, frozen, editsByFile, skips, relabels, textualReports) {
288
+ if (rewrites.length === 0 && textuals.length === 0)
289
+ return;
290
+ if (frozen) {
291
+ for (const { reference } of rewrites)
292
+ skips.push(skip(reportFile, reference, REASON_FROZEN_SOURCE));
293
+ for (const textual of textuals) {
294
+ skips.push({ file: reportFile, line: textual.line, url: textual.from, reason: REASON_FROZEN_TEXTUAL });
295
+ }
296
+ return;
297
+ }
298
+ const edits = [];
299
+ for (const rewrite of rewrites)
300
+ edits.push(...rewriteEdits(rewrite));
301
+ for (const textual of textuals)
302
+ edits.push({ start: textual.start, end: textual.end, text: textual.replacement });
303
+ editsByFile.set(file, applyEdits(source, edits));
304
+ for (const { reference, newLabel } of rewrites) {
305
+ if (newLabel === undefined || reference.label === undefined)
306
+ continue;
307
+ relabels.push({ file: reportFile, line: reference.line, from: reference.label.text, to: newLabel });
308
+ }
309
+ for (const textual of textuals) {
310
+ textualReports.push({ file: reportFile, line: textual.line, from: textual.from, to: textual.replacement });
311
+ }
312
+ }
313
+ /**
314
+ * The git shapes that can witness "this rename already happened" (post-hoc
315
+ * repair evidence), in the order the evidence gate checks them — the two
316
+ * worktree-tier shapes first, the HEAD-tree shape only when the worktree
317
+ * shows nothing. Surface-neutral wording: model-facing descriptions project
318
+ * these summaries instead of re-deriving the witness conditions.
319
+ */
320
+ export const POSTHOC_WITNESS_SHAPES = [
321
+ { shape: 'staged-rename-record', summary: 'a staged R record from the old path to the new path' },
322
+ { shape: 'deleted-record-with-shifted-counterpart', summary: 'a D record of the old path whose shifted counterpart exists on disk' },
323
+ { shape: 'head-tree-entry', summary: 'the old path recorded in the HEAD tree while the worktree shows nothing' },
324
+ ];
325
+ /**
326
+ * D1 evidence that "this rename already happened", plus the moved-file set it
327
+ * witnesses. Worktree tier (one `git status --porcelain -z`): staged
328
+ * `R old→new` records, or `D old` records (either column) whose shifted
329
+ * new-side counterpart exists on disk. HEAD tier (one `git cat-file -e`):
330
+ * old recorded in HEAD while the worktree shows nothing (e.g. a
331
+ * skip-worktree-hidden deletion) — run only when the worktree tier found
332
+ * nothing. A staged rename from inside old to somewhere OTHER than the
333
+ * shifted new path contradicts the requested pair and voids the evidence:
334
+ * refuse rather than rewrite towards the wrong destination.
335
+ */
336
+ function postHocEvidence(repoRoot, oldAbs, newAbs) {
337
+ const oldRel = posixRelative(repoRoot, oldAbs);
338
+ const newRel = posixRelative(repoRoot, newAbs);
339
+ /** Suffix of `p` under `oldRel` ('' for old itself), or undefined when outside. */
340
+ const underOld = (p) => p === oldRel ? '' : p.startsWith(`${oldRel}/`) ? p.slice(oldRel.length) : undefined;
341
+ const shiftedRel = (suffix) => (suffix === '' ? newRel : `${newRel}${suffix}`);
342
+ const moved = new Map();
343
+ for (const record of gitStatusPorcelain(repoRoot)) {
344
+ if (record.origPath !== undefined) {
345
+ const suffix = underOld(record.origPath);
346
+ if (suffix === undefined)
347
+ continue;
348
+ if (record.path === shiftedRel(suffix))
349
+ moved.set(record.origPath, record.path);
350
+ else
351
+ return undefined; // staged away from the requested pair — contradiction
352
+ }
353
+ if (record.xy.includes('D')) {
354
+ const suffix = underOld(record.path);
355
+ if (suffix === undefined)
356
+ continue;
357
+ if (existsSync(shiftPrefix(oldAbs, newAbs, resolve(repoRoot, record.path)))) {
358
+ moved.set(record.path, shiftedRel(suffix));
359
+ }
360
+ }
361
+ }
362
+ if (moved.size > 0)
363
+ return moved;
364
+ // HEAD tier (D1 ②): old recorded in HEAD while the worktree cannot witness
365
+ // it (e.g. a skip-worktree-hidden deletion) — reachable only when old is
366
+ // actually gone from disk. With old standing (the self-nesting sink-down
367
+ // keeps it as new's ancestor), the tier's premise is void: a HEAD-shaped
368
+ // reconstruction must not witness a repair, or a hand-copied tree would be
369
+ // mistaken for a move and live links repointed at the copy.
370
+ if (existsSync(oldAbs))
371
+ return undefined;
372
+ if (!gitTreeHas(repoRoot, 'HEAD', oldRel))
373
+ return undefined;
374
+ if (statSync(newAbs).isDirectory()) {
375
+ const fromHead = new Map();
376
+ for (const newFile of listMarkdownUnder(newAbs)) {
377
+ fromHead.set(posixRelative(repoRoot, shiftPrefix(newAbs, oldAbs, newFile)), posixRelative(repoRoot, newFile));
378
+ }
379
+ return fromHead;
380
+ }
381
+ return new Map([[oldRel, newRel]]);
382
+ }
383
+ /**
384
+ * Evidence carried by the operator's assertion (`replay: true`) instead of a
385
+ * git shape: the caller holds out-of-band proof (e.g. a rename record from
386
+ * history) and declares the pair completed, so nothing is probed. A file pair
387
+ * projects trivially; a directory pair's moved set is everything Markdown
388
+ * under the NEW path mapped back onto the old namespace (the inverse
389
+ * projection, which for a self-nesting pair strips the sunk segment). An
390
+ * unproven neighbor under newPath joins the move BY DECLARATION — the
391
+ * git-witnessed scoping of the default window is exactly the guarantee the
392
+ * caller takes over here.
393
+ */
394
+ function assertedEvidence(repoRoot, oldAbs, newAbs) {
395
+ const oldRel = posixRelative(repoRoot, oldAbs);
396
+ const newRel = posixRelative(repoRoot, newAbs);
397
+ if (!statSync(newAbs).isDirectory())
398
+ return new Map([[oldRel, newRel]]);
399
+ const asserted = new Map();
400
+ for (const newFile of listMarkdownUnder(newAbs)) {
401
+ asserted.set(posixRelative(repoRoot, shiftPrefix(newAbs, oldAbs, newFile)), posixRelative(repoRoot, newFile));
402
+ }
403
+ return asserted;
404
+ }
405
+ /** Shift `target` through the first pair whose old subtree contains it; a target no pair owns stays put. */
406
+ function shiftThroughPairs(pairs, target) {
407
+ for (const { oldPath, newPath } of pairs) {
408
+ if (pathInside(oldPath, target))
409
+ return shiftPrefix(oldPath, newPath, target);
410
+ }
411
+ return target;
412
+ }
413
+ /**
414
+ * Joint planning core over one or more (old → new) pairs. A plain rename is
415
+ * the one-pair case; `planSink` enumerates a directory's children into pairs
416
+ * and lands here with the same contract. Resolves every pair against `root`
417
+ * (session workspace), computes the full edit plan (out-link rebase +
418
+ * in-link rewrite + opt-in textual rebase + skip/conflict lists), and reports
419
+ * `certain` = conflict-free. Every href is computed against the FINAL
420
+ * positions in one pass — links between co-moved siblings keep their relative
421
+ * geometry, which sequential per-pair planning cannot offer. When the move
422
+ * already happened under git's witness (single pair only) the plan is
423
+ * link-only (post-hoc repair); on the caller's assertion (`replay`) the same
424
+ * link-only repair runs on the declared pair instead of a witnessed one.
425
+ * oldPath missing without evidence stays a hard conflict. The self-nesting
426
+ * geometry guard stands only while the move is
427
+ * pending — in repair mode the move has completed under git's witness
428
+ * (nothing will be moved), so the guard yields and the pair repairs links.
429
+ */
430
+ function planPairs(root, aggregateOld, aggregateNew, pairs, options) {
431
+ const repoRoot = gitTopLevel(root);
432
+ const isFrozen = options.isFrozen;
433
+ const textual = options.textual === true;
434
+ const conflicts = [];
435
+ const skips = [];
436
+ const relabels = [];
437
+ const textuals = [];
438
+ const shifts = pairs.map(({ oldPath, newPath }) => ({
439
+ from: posixRelative(repoRoot, oldPath),
440
+ to: posixRelative(repoRoot, newPath),
441
+ }));
442
+ const emptyPlan = () => ({
443
+ root: repoRoot,
444
+ oldPath: aggregateOld,
445
+ newPath: aggregateNew,
446
+ pairs,
447
+ editsByFile: new Map(),
448
+ skips,
449
+ relabels,
450
+ textuals,
451
+ conflicts,
452
+ linkOnly: false,
453
+ });
454
+ // Hard preconditions — reject whole, no plan. The root guard normalizes
455
+ // both sides: git reports the top level with forward slashes on Windows,
456
+ // and a strict equality against a resolved path would never fire there —
457
+ // the whole repo root would sail into planning.
458
+ for (const { oldPath, newPath } of pairs) {
459
+ if (resolve(oldPath) === resolve(repoRoot)) {
460
+ conflicts.push(conflict(posixRelative(repoRoot, oldPath), 'repo-root'));
461
+ return { certain: false, plan: emptyPlan() };
462
+ }
463
+ if (!isInside(repoRoot, oldPath) || !isInside(repoRoot, newPath)) {
464
+ conflicts.push(conflict(posixRelative(repoRoot, oldPath), 'outside-repo'));
465
+ return { certain: false, plan: emptyPlan() };
466
+ }
467
+ }
468
+ // Move-completion shapes are single-pair territory: the classic post-hoc
469
+ // (old gone, new present) and the self-nesting sink-down (old survives on
470
+ // disk, but only as new's ancestor — the moved subtree IS the requested
471
+ // move). Repairing a completed sink stays the single self-nesting pair
472
+ // (dir, dir/sub) even though sinking forward is multi-pair. Both repair
473
+ // candidates plan link-only, gated by D1 evidence; an evidence-less
474
+ // candidate is refused whole.
475
+ const single = pairs.length === 1 ? pairs[0] : undefined;
476
+ let movedFiles;
477
+ if (single !== undefined) {
478
+ const oldAbs = single.oldPath;
479
+ const newAbs = single.newPath;
480
+ const selfNesting = oldAbs !== newAbs && isInside(oldAbs, newAbs);
481
+ const oldExists = existsSync(oldAbs);
482
+ const newExists = existsSync(newAbs);
483
+ const repairCandidate = newExists && (!oldExists || selfNesting);
484
+ // Self-nesting guard: real only while the move is PENDING — the directory
485
+ // still standing at old with nothing under new yet. A completed sink-down
486
+ // cannot move-into-itself anymore, so the guard stands exactly where no
487
+ // repair is possible (old present, new absent).
488
+ if (selfNesting && !repairCandidate) {
489
+ conflicts.push(conflict(posixRelative(repoRoot, newAbs), 'self-nesting'));
490
+ return { certain: false, plan: emptyPlan() };
491
+ }
492
+ // With the operator's assertion (replay) the pair itself is the witness —
493
+ // no git shape is consulted; the moved set is the declared projection.
494
+ movedFiles = repairCandidate
495
+ ? (options.replay === true ? assertedEvidence(repoRoot, oldAbs, newAbs) : postHocEvidence(repoRoot, oldAbs, newAbs))
496
+ : undefined;
497
+ if (repairCandidate && movedFiles === undefined) {
498
+ // Informational history evidence: one `git log` (both pair sides under
499
+ // the pathspec — the only shape that surfaces R records) lists direct
500
+ // rename records verbatim. Never a verdict: the refusal stands either
501
+ // way, and the records only triage which exit applies.
502
+ conflicts.push(conflict(posixRelative(repoRoot, oldAbs), 'no-rename-evidence', {
503
+ records: gitLogRenameRecords(repoRoot, [posixRelative(repoRoot, oldAbs), posixRelative(repoRoot, newAbs)]),
504
+ }));
505
+ return { certain: false, plan: emptyPlan() };
506
+ }
507
+ if (movedFiles === undefined) {
508
+ if (!oldExists) {
509
+ // Informational history evidence: one `git log` probes whether the
510
+ // old path has any history — never tracked is the strongest typo
511
+ // signal. Single-pair refusals only: sink children enumerate from the
512
+ // disk (a missing child is a race), and per-pair probes would bill
513
+ // O(pairs) spawns on a refusal path that stays O(1) by contract.
514
+ conflicts.push(conflict(posixRelative(repoRoot, oldAbs), 'old-path-missing', {
515
+ everTracked: gitLogLastTouched(repoRoot, posixRelative(repoRoot, oldAbs)) !== undefined,
516
+ }));
517
+ return { certain: false, plan: emptyPlan() };
518
+ }
519
+ if (newExists) {
520
+ conflicts.push(conflict(posixRelative(repoRoot, newAbs), 'new-path-exists'));
521
+ return { certain: false, plan: emptyPlan() };
522
+ }
523
+ }
524
+ }
525
+ else {
526
+ // Multi-pair (sink): every pair is an ordinary pending move — old must
527
+ // stand, new must be free, no self-nesting (a fresh sub never sits inside
528
+ // a sibling, but the guard stays cheap insurance).
529
+ for (const { oldPath, newPath } of pairs) {
530
+ if (!existsSync(oldPath)) {
531
+ conflicts.push(conflict(posixRelative(repoRoot, oldPath), 'old-path-missing'));
532
+ return { certain: false, plan: emptyPlan() };
533
+ }
534
+ if (existsSync(newPath)) {
535
+ conflicts.push(conflict(posixRelative(repoRoot, newPath), 'new-path-exists'));
536
+ return { certain: false, plan: emptyPlan() };
537
+ }
538
+ if (isInside(oldPath, newPath)) {
539
+ conflicts.push(conflict(posixRelative(repoRoot, newPath), 'self-nesting'));
540
+ return { certain: false, plan: emptyPlan() };
541
+ }
542
+ }
543
+ }
544
+ // Pending moves stage through `git mv`, which refuses a source carrying
545
+ // nothing tracked at/under it — a never-added file, or the reversed post-hoc
546
+ // pair (old = the untracked file standing on disk, new = the vanished
547
+ // tracked path). That refusal is decided here, with a code the remedy exits
548
+ // key on, instead of surfacing as a raw spawn error at apply time. One
549
+ // ls-files spawn covers every pair; repair plans (link-only) never move and
550
+ // skip the probe.
551
+ if (movedFiles === undefined) {
552
+ const tracked = new Set(gitTrackedUnder(repoRoot, pairs.map(({ oldPath }) => posixRelative(repoRoot, oldPath))));
553
+ const carriesTracked = (rel) => {
554
+ for (const t of tracked) {
555
+ if (t === rel || t.startsWith(`${rel}/`))
556
+ return true;
557
+ }
558
+ return false;
559
+ };
560
+ for (const { oldPath } of pairs) {
561
+ const rel = posixRelative(repoRoot, oldPath);
562
+ if (!carriesTracked(rel)) {
563
+ conflicts.push(conflict(rel, 'old-path-untracked'));
564
+ return { certain: false, plan: emptyPlan() };
565
+ }
566
+ }
567
+ }
568
+ const editsByFile = new Map();
569
+ const textualEditsFor = (source) => (textual ? scanTextualOccurrences(source, shifts) : []);
570
+ if (movedFiles !== undefined && single !== undefined) {
571
+ const oldAbs = single.oldPath;
572
+ const newAbs = single.newPath;
573
+ // 1p. Out-link rebase over the git-witnessed moved set (D2): content is
574
+ // read at its physical NEW position but resolved against the OLD
575
+ // baseline (pre-move semantics, same as L1). A file under newPath
576
+ // that git cannot place under old is NOT part of the move — its
577
+ // out-links stay untouched.
578
+ for (const [oldRel, newRel] of movedFiles) {
579
+ const oldFile = resolve(repoRoot, oldRel); // resolution baseline (pre-move position)
580
+ const newFile = resolve(repoRoot, newRel); // physical content location
581
+ const frozen = isFrozen?.(oldFile) === true; // freeze judged at the pre-move position
582
+ const source = readFileSync(newFile, 'utf8');
583
+ const rewrites = [];
584
+ for (const ref of extractReferences(source)) {
585
+ const resolution = resolveReferenceLexically(ref, oldFile);
586
+ if (resolution.ignored)
587
+ continue; // external / / / scheme → not touched
588
+ const target = resolution.abs;
589
+ if (isInside(oldAbs, target)) {
590
+ // Moves with the subtree → href unchanged (but report a target the
591
+ // move left behind: honesty over silence).
592
+ if (!existsSync(shiftPrefix(oldAbs, newAbs, target))) {
593
+ skips.push(skip(newRel, ref, 'out-link target was not moved to the new location (rename does not repair broken links)'));
594
+ }
595
+ continue;
596
+ }
597
+ if (!existsSync(target)) {
598
+ skips.push(skip(newRel, ref, 'out-link target does not exist (rename does not touch broken links)'));
599
+ continue;
600
+ }
601
+ if (!isInside(repoRoot, target)) {
602
+ skips.push(skip(newRel, ref, 'out-link outside repository (rename does not touch it)'));
603
+ continue;
604
+ }
605
+ if (ref.start === undefined || ref.end === undefined) {
606
+ skips.push(skip(newRel, ref, 'out-link has no rebasable destination (autolink / bare URL)'));
607
+ continue;
608
+ }
609
+ const newHref = rebaseHref(newFile, target);
610
+ if (newHref === splitMarkdownUrlTarget(ref.url).path)
611
+ continue; // depth-preserving move → href unchanged
612
+ recordRewrite(newRel, ref, newHref, rewrites, skips);
613
+ }
614
+ commitRewrites(newFile, newRel, source, rewrites, textualEditsFor(source), frozen, editsByFile, skips, relabels, textuals);
615
+ }
616
+ // 2p. In-link rewrite, resolved lexically (plan-layer difference #1):
617
+ // targets under the gone old path never pass an existsSync gate, so
618
+ // every old-pointing reference is either rewritten or reported —
619
+ // never silently dropped. A moved file at its new position is the
620
+ // out-link pass's business; an unproven neighbor under newPath stays
621
+ // an ordinary in-link candidate (D2).
622
+ const movedNewAbs = new Set([...movedFiles.values()].map(rel => resolve(repoRoot, rel)));
623
+ const selfNesting = oldAbs !== newAbs && isInside(oldAbs, newAbs);
624
+ const candidates = new Set(gitGrep(repoRoot, basename(oldAbs)));
625
+ if (selfNesting) {
626
+ // Sink-down residue: old still stands on disk and whatever it still
627
+ // holds (outside new) are ordinary in-link holders now — but their
628
+ // same-directory links never mention old's name, so the needle grep
629
+ // cannot see them. Enumerate the residue explicitly to keep the
630
+ // either-rewritten-or-reported contract.
631
+ for (const residueAbs of listMarkdownUnder(oldAbs)) {
632
+ if (!isInside(newAbs, residueAbs))
633
+ candidates.add(residueAbs);
634
+ }
635
+ }
636
+ for (const candidateAbs of candidates) {
637
+ if (movedNewAbs.has(candidateAbs))
638
+ continue; // part of the move → out-link pass owns it
639
+ const source = readFileSync(candidateAbs, 'utf8');
640
+ const candidateRel = posixRelative(repoRoot, candidateAbs);
641
+ const rewrites = [];
642
+ for (const ref of extractReferences(source)) {
643
+ const resolution = resolveReferenceLexically(ref, candidateAbs);
644
+ if (resolution.ignored)
645
+ continue; // not an internal in-link to old
646
+ if (!isInside(oldAbs, resolution.abs))
647
+ continue; // points elsewhere
648
+ if (ref.start === undefined || ref.end === undefined) {
649
+ skips.push(skip(candidateRel, ref, 'in-link has no rebasable destination (autolink / bare URL)'));
650
+ continue;
651
+ }
652
+ const newTarget = shiftPrefix(oldAbs, newAbs, resolution.abs);
653
+ if (!existsSync(newTarget)) {
654
+ skips.push(skip(candidateRel, ref, `in-link target was not moved to the new location (no counterpart at ${posixRelative(repoRoot, newTarget)})`));
655
+ continue;
656
+ }
657
+ const newHref = rebaseHref(candidateAbs, newTarget);
658
+ recordRewrite(candidateRel, ref, newHref, rewrites, skips);
659
+ }
660
+ commitRewrites(candidateAbs, candidateRel, source, rewrites, textualEditsFor(source), isFrozen?.(candidateAbs) === true, editsByFile, skips, relabels, textuals);
661
+ }
662
+ return {
663
+ certain: conflicts.length === 0,
664
+ plan: { root: repoRoot, oldPath: aggregateOld, newPath: aggregateNew, pairs, editsByFile, skips, relabels, textuals, conflicts, linkOnly: true },
665
+ };
666
+ }
667
+ // 1. Out-link rebase: every moved Markdown file's outbound references,
668
+ // resolved at the OLD position, rewritten to still resolve from the NEW
669
+ // position. Targets that move together with their own pair keep their
670
+ // relative path unchanged; a target inside ANOTHER pair (sink siblings)
671
+ // moves in the same transaction, so its href is computed against the
672
+ // final positions — for a same-parent sink that is byte-identical, which
673
+ // the equality check turns into a no-op.
674
+ for (const { oldPath, newPath } of pairs) {
675
+ for (const oldFile of listMarkdownUnder(oldPath)) {
676
+ const source = readFileSync(oldFile, 'utf8');
677
+ const newFile = shiftPrefix(oldPath, newPath, oldFile);
678
+ const rewrites = [];
679
+ for (const ref of extractReferences(source)) {
680
+ const resolution = resolveReference(ref, oldFile, repoRoot);
681
+ if (resolution.ignored)
682
+ continue; // external / / / scheme → not touched
683
+ if (resolution.reason) {
684
+ skips.push(skip(posixRelative(repoRoot, oldFile), ref, `out-link ${resolution.reason} (rename does not touch broken links)`));
685
+ continue;
686
+ }
687
+ if (pathInside(oldPath, resolution.abs))
688
+ continue; // moves with its own subtree → href unchanged (geometry)
689
+ if (ref.start === undefined || ref.end === undefined) {
690
+ skips.push(skip(posixRelative(repoRoot, oldFile), ref, 'out-link has no rebasable destination (autolink / bare URL)'));
691
+ continue;
692
+ }
693
+ const newHref = rebaseHref(newFile, shiftThroughPairs(pairs, resolution.abs));
694
+ if (newHref === splitMarkdownUrlTarget(ref.url).path)
695
+ continue; // depth-preserving move → href unchanged
696
+ recordRewrite(posixRelative(repoRoot, oldFile), ref, newHref, rewrites, skips);
697
+ }
698
+ // Freeze judged at the pre-move position: a file moving INTO a frozen
699
+ // directory (the archival move) is fully rewritten — that edit is the
700
+ // policy-authorized last one.
701
+ commitRewrites(newFile, posixRelative(repoRoot, oldFile), source, rewrites, textualEditsFor(source), isFrozen?.(oldFile) === true, editsByFile, skips, relabels, textuals);
702
+ }
703
+ }
704
+ // 2. In-link rewrite: references elsewhere that resolve INTO any moved
705
+ // subtree, rewritten to the shifted target. Candidates come from one
706
+ // `git grep -l` per distinct old basename; resolution filters to the
707
+ // real moved subtrees.
708
+ const needles = [...new Set(pairs.map(({ oldPath }) => basename(oldPath)))];
709
+ const candidates = new Set();
710
+ for (const needle of needles) {
711
+ for (const candidateAbs of gitGrep(repoRoot, needle))
712
+ candidates.add(candidateAbs);
713
+ }
714
+ for (const candidateAbs of candidates) {
715
+ if (pairs.some(({ oldPath }) => pathInside(oldPath, candidateAbs)))
716
+ continue; // moves with the plan → pass 1 owns it
717
+ const source = readFileSync(candidateAbs, 'utf8');
718
+ const candidateRel = posixRelative(repoRoot, candidateAbs);
719
+ const rewrites = [];
720
+ for (const ref of extractReferences(source)) {
721
+ const resolution = resolveReference(ref, candidateAbs, repoRoot);
722
+ if (resolution.ignored)
723
+ continue; // not an internal in-link to a moved subtree
724
+ if (resolution.abs === undefined) {
725
+ // Pre-broken/unresolvable in-link: report it only when it points
726
+ // lexically INTO a moved subtree's old namespace (same honesty
727
+ // rule as the post-hoc pass: every old-pointing reference is
728
+ // either rewritten or reported, never
729
+ // silently dropped). Breakage elsewhere is the doc-link gate's
730
+ // territory, not this move's.
731
+ const lexical = resolveReferenceLexically(ref, candidateAbs);
732
+ const lexicalAbs = lexical.abs;
733
+ if (lexicalAbs !== undefined && pairs.some(({ oldPath }) => pathInside(oldPath, lexicalAbs))) {
734
+ skips.push(skip(candidateRel, ref, 'in-link target did not exist before the move (rename does not repair broken links)'));
735
+ }
736
+ continue;
737
+ }
738
+ const owner = pairs.find(({ oldPath }) => pathInside(oldPath, resolution.abs));
739
+ if (owner === undefined)
740
+ continue; // points elsewhere
741
+ if (ref.start === undefined || ref.end === undefined) {
742
+ skips.push(skip(candidateRel, ref, 'in-link has no rebasable destination (autolink / bare URL)'));
743
+ continue;
744
+ }
745
+ const newTarget = shiftPrefix(owner.oldPath, owner.newPath, resolution.abs);
746
+ const newHref = rebaseHref(candidateAbs, newTarget);
747
+ recordRewrite(candidateRel, ref, newHref, rewrites, skips);
748
+ }
749
+ commitRewrites(candidateAbs, candidateRel, source, rewrites, textualEditsFor(source), isFrozen?.(candidateAbs) === true, editsByFile, skips, relabels, textuals);
750
+ }
751
+ return {
752
+ certain: conflicts.length === 0,
753
+ plan: { root: repoRoot, oldPath: aggregateOld, newPath: aggregateNew, pairs, editsByFile, skips, relabels, textuals, conflicts, linkOnly: false },
754
+ };
755
+ }
756
+ /**
757
+ * Plan an explicit rename without writing anything — the one-pair case of the
758
+ * joint planning core. See `planPairs` for the contract.
759
+ */
760
+ export function planRename(root, oldPath, newPath, options = {}) {
761
+ const oldAbs = resolve(root, oldPath);
762
+ const newAbs = resolve(root, newPath);
763
+ return planPairs(root, oldAbs, newAbs, [{ oldPath: oldAbs, newPath: newAbs }], options);
764
+ }
765
+ /**
766
+ * Plan a one-level sink: `<dir>/*` moves to
767
+ * `<dir>/<sub>/*` as ONE transaction — internally every child becomes a pair
768
+ * and `planPairs` computes every href against the final positions (links
769
+ * between co-moved siblings keep their relative geometry). The aggregate
770
+ * old/new on the plan is (dir, dir/sub) for reporting; repair of an already
771
+ * completed sink stays the single self-nesting pair — planRename(dir, dir/sub)
772
+ * — because git witnessed the completed geometry, not the per-child staging.
773
+ */
774
+ export function planSink(root, dir, sub, options = {}) {
775
+ const repoRoot = gitTopLevel(root);
776
+ const dirAbs = resolve(root, dir);
777
+ const subAbs = resolve(dirAbs, sub);
778
+ const conflicts = [];
779
+ const shell = () => ({
780
+ certain: false,
781
+ plan: { root: repoRoot, oldPath: dirAbs, newPath: subAbs, pairs: [], editsByFile: new Map(), skips: [], relabels: [], textuals: [], conflicts, linkOnly: false },
782
+ });
783
+ if (!isInside(repoRoot, dirAbs) || !isInside(repoRoot, subAbs)) {
784
+ conflicts.push(conflict(posixRelative(repoRoot, dirAbs), 'outside-repo'));
785
+ return shell();
786
+ }
787
+ if (!existsSync(dirAbs) || !statSync(dirAbs).isDirectory()) {
788
+ conflicts.push(conflict(posixRelative(repoRoot, dirAbs), 'sink-source-not-directory'));
789
+ return shell();
790
+ }
791
+ if (existsSync(subAbs)) {
792
+ conflicts.push(conflict(posixRelative(repoRoot, subAbs), 'new-path-exists'));
793
+ return shell();
794
+ }
795
+ const children = readdirSync(dirAbs, { withFileTypes: true }).filter(entry => entry.isDirectory() || entry.isFile());
796
+ if (children.length === 0) {
797
+ conflicts.push(conflict(posixRelative(repoRoot, dirAbs), 'sink-no-children'));
798
+ return shell();
799
+ }
800
+ const pairs = children.map(child => ({ oldPath: resolve(dirAbs, child.name), newPath: resolve(subAbs, child.name) }));
801
+ return planPairs(root, dirAbs, subAbs, pairs, options);
802
+ }
803
+ /**
804
+ * The physical move failed at apply time — the typed, catchable contract for
805
+ * every `git mv` failure. Plan-time refusals are conflicts (nothing written);
806
+ * this is the apply tier: the plan was certain, the world changed underneath
807
+ * it (a source untracked between plan and apply, a permission, an exotic index
808
+ * state). `movedPairs` reports exactly which pairs did move before the failure
809
+ * — non-empty means the worktree IS half-changed, and honesty demands saying
810
+ * which half moved. Consumers branch on `code`, relay `gitMessage`, and never
811
+ * surface the raw spawn text.
812
+ */
813
+ export class RenameApplyError extends Error {
814
+ code = 'git-move-failed';
815
+ /** The pair whose move failed. */
816
+ pair;
817
+ /** git's own message (captured stderr, e.g. `fatal: not under version control, source=…`). */
818
+ gitMessage;
819
+ /** Pairs already moved before the failure, in move order. */
820
+ movedPairs;
821
+ constructor(pair, gitMessage, movedPairs) {
822
+ super(`git mv failed for ${pair.oldPath} -> ${pair.newPath}: ${gitMessage}`
823
+ + (movedPairs.length > 0 ? ` (already moved: ${movedPairs.map(p => `${p.oldPath} -> ${p.newPath}`).join(', ')})` : ''));
824
+ this.name = 'RenameApplyError';
825
+ this.pair = pair;
826
+ this.gitMessage = gitMessage;
827
+ this.movedPairs = movedPairs;
828
+ }
829
+ }
830
+ /**
831
+ * Apply a certain plan: `git mv` every pair (staging the moves), then write
832
+ * every edit to its post-move path. A link-only (post-hoc) plan skips the
833
+ * moves — the files are already in place — and reports `moved: false`.
834
+ * Refuses to run while conflicts remain — the caller must only call this when
835
+ * `certain` is true ("工作树绝不半改"). A `git mv` failure throws
836
+ * `RenameApplyError` (see the class for the apply-tier contract).
837
+ */
838
+ export function applyRenamePlan(plan) {
839
+ if (plan.conflicts.length > 0) {
840
+ throw new Error(`applyRenamePlan refuses to run with unresolved conflicts: ${plan.conflicts.map(c => c.reason).join('; ')}`);
841
+ }
842
+ const repoRoot = plan.root;
843
+ if (!plan.linkOnly) {
844
+ const movedPairs = [];
845
+ for (const pair of plan.pairs) {
846
+ mkdirSync(dirname(pair.newPath), { recursive: true });
847
+ try {
848
+ gitMove(repoRoot, posixRelative(repoRoot, pair.oldPath), posixRelative(repoRoot, pair.newPath));
849
+ }
850
+ catch (error) {
851
+ const gitMessage = error instanceof GitMoveError ? error.stderr : String(error?.message ?? error);
852
+ throw new RenameApplyError(pair, gitMessage, movedPairs);
853
+ }
854
+ movedPairs.push(pair);
855
+ }
856
+ }
857
+ for (const [file, content] of plan.editsByFile) {
858
+ writeFileSync(file, content);
859
+ }
860
+ return {
861
+ moved: !plan.linkOnly,
862
+ edited: [...plan.editsByFile.keys()].map(file => posixRelative(repoRoot, file)),
863
+ };
864
+ }