@catheadowl/md-tools 0.0.0-stage → 0.2.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +94 -2
  3. package/cli/config.mjs +86 -0
  4. package/cli/doc-link.mjs +145 -0
  5. package/cli/kernel.mjs +86 -0
  6. package/cli/normalize.mjs +91 -0
  7. package/cli/rename.mjs +390 -0
  8. package/conformance/cases.json +55 -0
  9. package/lib/gate-check.d.ts +87 -0
  10. package/lib/gate-check.js +233 -0
  11. package/lib/index.d.ts +8 -0
  12. package/lib/index.js +8 -0
  13. package/lib/links/anchors.d.ts +43 -0
  14. package/lib/links/anchors.js +93 -0
  15. package/lib/links/cli.d.ts +33 -0
  16. package/lib/links/cli.js +86 -0
  17. package/lib/links/git.d.ts +156 -0
  18. package/lib/links/git.js +329 -0
  19. package/lib/links/index.d.ts +33 -0
  20. package/lib/links/index.js +25 -0
  21. package/lib/links/markdown.d.ts +127 -0
  22. package/lib/links/markdown.js +253 -0
  23. package/lib/links/normalize.d.ts +40 -0
  24. package/lib/links/normalize.js +102 -0
  25. package/lib/links/rebase.d.ts +24 -0
  26. package/lib/links/rebase.js +44 -0
  27. package/lib/links/rename.d.ts +257 -0
  28. package/lib/links/rename.js +864 -0
  29. package/lib/links/resolve.d.ts +145 -0
  30. package/lib/links/resolve.js +297 -0
  31. package/lib/links/scheme.d.ts +115 -0
  32. package/lib/links/scheme.js +209 -0
  33. package/lib/links/textual.d.ts +26 -0
  34. package/lib/links/textual.js +144 -0
  35. package/lib/measure/count.d.ts +47 -0
  36. package/lib/measure/count.js +91 -0
  37. package/lib/measure/document.d.ts +105 -0
  38. package/lib/measure/document.js +173 -0
  39. package/lib/measure/index.d.ts +22 -0
  40. package/lib/measure/index.js +18 -0
  41. package/lib/measure/sections.d.ts +38 -0
  42. package/lib/measure/sections.js +37 -0
  43. package/lib/measure/structure.d.ts +53 -0
  44. package/lib/measure/structure.js +186 -0
  45. package/package.json +82 -4
  46. package/skills/md-tools/SKILL.md +42 -0
  47. package/skills/md-tools/references/freeze.md +17 -0
  48. package/skills/md-tools/references/payload.md +28 -0
package/cli/rename.mjs ADDED
@@ -0,0 +1,390 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * doc-rename — move a file/directory and rebase every in-repo Markdown
4
+ * reference with it (plan-then-apply, all-or-nothing — the worktree is never
5
+ * half-changed). CLI face of the rename kernel shipped in this package (lib/)
6
+ * — import, not a copy; semantics and their full test face live in the
7
+ * kernel. The kernel import is guarded by ./kernel.mjs: a missing or stale
8
+ * kernel build exits 1 with a reinstall remedy instead of a raw, misleading
9
+ * ESM error.
10
+ *
11
+ * Post-hoc repair: when the move already happened and git can witness it,
12
+ * the same (old, new) pair repairs links only — no second move. Witnessed
13
+ * shapes: the classic (oldPath gone, newPath present — staged `R old→new`,
14
+ * `D old` with the shifted counterpart on disk, or old recorded in the HEAD
15
+ * tree while the worktree shows nothing — a window spanning the staged state
16
+ * and the HEAD tree, closing once the rename is committed) and the
17
+ * self-nesting sink-down (newPath inside
18
+ * oldPath; old survives on disk only as the moved subtree's ancestor). The
19
+ * self-nesting geometry guard stands exactly where no repair is possible —
20
+ * the pending move: this tool never moves a directory into itself, so sink
21
+ * with --sink (below) or a two-step git mv, then repair with the same pair.
22
+ * Past the window — the rename already committed — re-running with --replay
23
+ * (below) repairs on the caller's asserted pair instead.
24
+ *
25
+ * Untracked sources: a pending move's source must carry tracked content —
26
+ * git mv stages the move, and a source with nothing tracked at/under it (a
27
+ * never-added file, or a reversed post-hoc pair) refuses whole with a remedy
28
+ * pointing each intent at its own path.
29
+ *
30
+ * Informational history evidence: the no-evidence and plain missing-old
31
+ * refusals attach one git log probe's findings to the conflict
32
+ * (historyEvidence — direct R records between the pair, or whether the old
33
+ * path was ever tracked). Information face only: refusal verdicts, the
34
+ * default window, and every success path are unchanged.
35
+ *
36
+ * Freeze policy, default base layer: folder-manifest `archived: true`
37
+ * declarations (manifest.yml on the frozen tree itself) — declared trees'
38
+ * files are read-only holders, discovered automatically. Narrow pinned read
39
+ * (schema 1, boolean archived, everything else ignored); a manifest.yml that
40
+ * is unparseable or shaped wrong exits 1 with a one-line diagnosis.
41
+ * --frozen flags replace the whole policy for one run (not a union);
42
+ * --no-manifest-freeze skips manifest reading entirely.
43
+ *
44
+ * Usage (paths resolve against the current directory; run inside a git repo):
45
+ * doc-rename <oldPath> <newPath> [--dry-run] [--json] [--replay] [--frozen <dirName>...] [--no-manifest-freeze] [--textual]
46
+ * doc-rename --sink <dir> <sub> [--dry-run] [--json] [--frozen <dirName>...] [--no-manifest-freeze] [--textual]
47
+ *
48
+ * --dry-run plan only — print what would change, write nothing
49
+ * --json machine-readable output (shape mirrors the md_rename tool JSON)
50
+ * --frozen <name> directory name whose content is read-only by policy; repeatable.
51
+ * Mirrors the extras `doc-link` gate's `frozen-dirs` option semantics:
52
+ * frozen sources move with the plan but their bytes never change —
53
+ * would-be rewrites become reported skips. Replaces the manifest
54
+ * freeze policy for this run.
55
+ * --no-manifest-freeze
56
+ * skip folder-manifest archived declarations entirely —
57
+ * neither read nor trusted for this run.
58
+ * --sink <dir> <sub> one planned transaction sinking a directory's contents one level
59
+ * down (dir/* → dir/sub/*): every child becomes a pair inside one
60
+ * plan, so links between co-moved siblings keep their geometry and
61
+ * the worktree never shows a half-sunk state. Repairing an already
62
+ * completed sink stays the plain pair form: doc-rename <dir> <dir>/<sub>.
63
+ * --textual opt-in: non-link renderings of the moved path — tree-diagram lines
64
+ * in code blocks, code spans, heading path strings — join the same
65
+ * plan (each occurrence listed line by line; --frozen still wins).
66
+ * Default off: old paths in historical records are true statements;
67
+ * rewriting them is falsification unless declared.
68
+ * --replay opt-in: repair an already-completed pair on the caller's assertion —
69
+ * out-of-band proof (e.g. a rename record from git history) replaces
70
+ * the git witness and the same (old, new) pair repairs links only.
71
+ * The moved set is the declared pair's projection: everything under
72
+ * newPath maps back onto oldPath, so an unproven neighbor joins the
73
+ * move BY DECLARATION. An assertion contradicting the disk still
74
+ * refuses (the old/new geometry checks stand).
75
+ * Agent skill: the shipped skill payload lives at `skills/md-tools/`
76
+ * (package root; the whole subtree is the install unit) — the agent installs.
77
+ * Exit codes: 0 moved/repaired (or dry-run certain), 1 conflict (nothing
78
+ * written), apply failure (git's message plus the pairs already moved,
79
+ * reported exactly), or failed kernel-freshness startup guard, 2 usage
80
+ * error. Skips are honest reports, never failures.
81
+ */
82
+ import { realpathSync } from 'node:fs'
83
+ import { resolve } from 'node:path'
84
+ import { pathToFileURL } from 'node:url'
85
+
86
+ import { loadKernel } from './kernel.mjs'
87
+ import { loadFreezePolicy } from './config.mjs'
88
+
89
+ // Dynamic by necessity: a static kernel import would link before any code
90
+ // runs, so the freshness guard in kernel.mjs could never fire first.
91
+ const {
92
+ applyRenamePlan,
93
+ discoverRepositoryRoot,
94
+ frozenSourcePredicate,
95
+ frozenTreePredicate,
96
+ pathInside,
97
+ planRename,
98
+ planSink,
99
+ posixRelative,
100
+ RenameApplyError,
101
+ } = await loadKernel('doc-rename')
102
+
103
+ /**
104
+ * D1 remedy exits when git cannot witness the completed rename — CLI wording
105
+ * of the evidence-refusal exits (the lib emits the structured reason; each
106
+ * output layer words its own remedy). Three mirror the plugin face's exits;
107
+ * the committed-rename exit is this face's own: past the staged-or-HEAD-tree
108
+ * window, --replay repairs on the caller's asserted pair, and the pre-move
109
+ * resurrection is the manual fallback. The
110
+ * self-nesting shape (new inside old, old still standing) gets its own list:
111
+ * the classic exit 2 ("restore old, remove new, re-run") lands in the pending
112
+ * geometry refusal there — this tool never performs a move into itself, so
113
+ * restoring a pending self-nesting move is a dead end.
114
+ */
115
+ const NO_EVIDENCE_REMEDY = [
116
+ 'Confirm the real old path: the history records attached to this conflict and git log --follow -- <newPath> show where the file actually came from.',
117
+ 'If old exists in HEAD and new was not edited since the move: verify the new content matches HEAD (git cat-file -p HEAD:<oldPath>), git checkout HEAD -- <oldPath>, remove newPath, then re-run this command with the same pair.',
118
+ 'If the rename was already committed (old gone from HEAD too, worktree clean): this tool witnesses only the staged state and the HEAD tree. Verify the move on your side (the attached history records are exactly that evidence), then re-run this command with the same pair and --replay — the asserted pair repairs links only. The manual alternative: git checkout <moveCommit>^ -- <oldPath>, remove newPath, then re-run with the same pair.',
119
+ 'If old was never tracked: references to it were already broken before the move — that is a link-integrity check surface, not this tool.',
120
+ ]
121
+
122
+ const SELF_NESTING_REMEDY = [
123
+ 'If the tree under the new path is a copy rather than the moved original, remove it — the evidence gate refuses unproven copies because this tool would repoint live links at the copy.',
124
+ 'This tool never moves a directory into itself. To sink one level (dir -> dir/sub): use this tool\'s --sink <dir> <sub> (one planned transaction), or two-step git mv via a temp name (git mv <dir> <tmp>; mkdir <dir>; git mv <tmp> <dir>/<sub>) — then re-run this command with the same pair: git will witness the completed move and repair links only.',
125
+ 'If the sink already physically happened but git cannot witness it (nothing under the old path was ever tracked), git has nothing to prove the move with — repair the links manually.',
126
+ ]
127
+
128
+ /**
129
+ * Remedy exits when a pending move's source carries nothing tracked by git.
130
+ * Two intents share the refusal: the reversed post-hoc pair (old = the
131
+ * untracked file standing on disk, new = the vanished tracked path) and the
132
+ * never-added file — the exits point each intent back at its own path.
133
+ */
134
+ const UNTRACKED_SOURCE_REMEDY = [
135
+ 'If the move already happened and you meant to repair it, the pair is reversed: pass the vanished tracked path as oldPath (git status lists its deletion) and the file\'s current location as newPath — git will witness the completed move and this tool repairs links only.',
136
+ 'If the file was simply never committed: stage it first (git add <oldPath>), then re-run this command with the same pair.',
137
+ ]
138
+
139
+ /**
140
+ * Remedy exits for the plain missing-old refusal — both of the pair's sides
141
+ * are absent from the disk, so the intent splits by the attached evidence:
142
+ * a typo against a tree that never knew the path (everTracked false), or a
143
+ * repair aimed at a path that was deleted or moved (everTracked true).
144
+ */
145
+ const OLD_PATH_MISSING_REMEDY = [
146
+ 'Both paths are absent from the disk. If the old path is a typo (attached history says it was never tracked — git history never knew it), correct the spelling against the tree and re-run.',
147
+ 'If the old path did exist (attached history says it has git history), it was deleted or moved: git log --oneline -- <oldPath> shows when. To repair a completed move, pass the REAL old path — and add --replay when that move is already committed.',
148
+ ]
149
+
150
+ /** Remedy exits worded for the pair's geometry shape (wording only; the gate itself lives in the lib). */
151
+ function noEvidenceRemedy(root, oldPath, newPath) {
152
+ return pathInside(resolve(root, oldPath), resolve(root, newPath)) ? SELF_NESTING_REMEDY : NO_EVIDENCE_REMEDY
153
+ }
154
+
155
+ const conflictView = (c) => ({ code: c.code, file: c.file, line: c.line, url: c.url, reason: c.reason, ...(c.historyEvidence !== undefined ? { historyEvidence: c.historyEvidence } : {}) })
156
+ const skipView = (s) => ({ file: s.file, line: s.line, url: s.url, reason: s.reason })
157
+ const relabelView = (r) => ({ file: r.file, line: r.line, from: r.from, to: r.to })
158
+ const textualView = (t) => ({ file: t.file, line: t.line, from: t.from, to: t.to })
159
+
160
+ function renderConflict(conflicts, skips, remedy) {
161
+ const lines = ['conflict: refuse whole — nothing was written']
162
+ for (const c of conflicts) {
163
+ lines.push(` ${c.file} ${c.reason}`)
164
+ const evidence = c.historyEvidence
165
+ if (evidence === undefined) continue
166
+ for (const r of evidence.records ?? []) lines.push(` history ${r.commit} ${r.oldPath} -> ${r.newPath}`)
167
+ if (evidence.everTracked !== undefined) {
168
+ lines.push(` history old path ${evidence.everTracked ? 'has git history (it existed — deleted or moved)' : 'was never tracked (likely a typo)'}`)
169
+ }
170
+ }
171
+ for (const s of skips) lines.push(` [skip] ${s.file}:${s.line} ${s.url} (${s.reason})`)
172
+ if (remedy) {
173
+ lines.push('remedy:')
174
+ for (const [i, r] of remedy.entries()) lines.push(` ${i + 1}. ${r}`)
175
+ }
176
+ return lines.join('\n')
177
+ }
178
+
179
+ function renderApplied(result, plan, oldPath, newPath, asserted = false) {
180
+ const lines = [`${result.moved ? 'moved' : `repaired (link-only${asserted ? ', asserted' : ''})`} ${oldPath} -> ${newPath}`]
181
+ lines.push(`${result.edited.length} file(s) edited:`)
182
+ for (const f of result.edited) lines.push(` ${f}`)
183
+ for (const r of plan.relabels) lines.push(` relabel ${r.file}:${r.line} [${r.from}] -> [${r.to}]`)
184
+ for (const t of plan.textuals) lines.push(` textual ${t.file}:${t.line} ${t.from} -> ${t.to}`)
185
+ for (const s of plan.skips) lines.push(` [skip] ${s.file}:${s.line} ${s.url} (${s.reason})`)
186
+ return lines.join('\n')
187
+ }
188
+
189
+ function renderDryRun(plan, oldPath, newPath, asserted = false) {
190
+ const wouldEdit = [...plan.editsByFile.keys()].map((f) => posixRelative(plan.root, f))
191
+ const lines = [`plan (dry-run) ${oldPath} -> ${newPath}${plan.linkOnly ? ` [link-only repair${asserted ? ', asserted' : ''}]` : ''}`]
192
+ lines.push(`${wouldEdit.length} file(s) would be edited:`)
193
+ for (const f of wouldEdit) lines.push(` ${f}`)
194
+ for (const r of plan.relabels) lines.push(` relabel ${r.file}:${r.line} [${r.from}] -> [${r.to}]`)
195
+ for (const t of plan.textuals) lines.push(` textual ${t.file}:${t.line} ${t.from} -> ${t.to}`)
196
+ for (const s of plan.skips) lines.push(` [skip] ${s.file}:${s.line} ${s.url} (${s.reason})`)
197
+ lines.push('certain — re-run without --dry-run to apply')
198
+ return lines.join('\n')
199
+ }
200
+
201
+ // The bin face runs through the global link's junction/symlink: argv[1] names
202
+ // the link path while import.meta.url carries the real path — accept either.
203
+ const isMain = process.argv[1] && (import.meta.url === pathToFileURL(process.argv[1]).href
204
+ || import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href)
205
+ if (isMain) {
206
+ const usage = () => console.error(
207
+ 'usage: doc-rename <oldPath> <newPath> [--dry-run] [--json] [--replay] [--frozen <dirName>...] [--no-manifest-freeze] [--textual]\n' +
208
+ ' doc-rename --sink <dir> <sub> [--dry-run] [--json] [--frozen <dirName>...] [--no-manifest-freeze] [--textual]')
209
+ const argv = process.argv.slice(2)
210
+ const paths = []
211
+ const frozenNames = new Set()
212
+ let dryRun = false
213
+ let json = false
214
+ let textual = false
215
+ let replay = false
216
+ let noManifestFreeze = false
217
+ let sink = null
218
+ for (let i = 0; i < argv.length; i++) {
219
+ const a = argv[i]
220
+ if (a === '--dry-run') dryRun = true
221
+ else if (a === '--json') json = true
222
+ else if (a === '--textual') textual = true
223
+ else if (a === '--replay') replay = true
224
+ else if (a === '--no-manifest-freeze') noManifestFreeze = true
225
+ else if (a === '--sink') {
226
+ const dir = argv[++i]
227
+ const sub = argv[++i]
228
+ if (!dir || !sub || dir.startsWith('--') || sub.startsWith('--')) {
229
+ console.error('--sink needs <dir> <sub>')
230
+ process.exit(2)
231
+ }
232
+ if (/[/\\]/.test(sub) || sub === '.' || sub === '..') {
233
+ console.error('--sink sub must be a single directory name (dir/* -> dir/<sub>/*)')
234
+ process.exit(2)
235
+ }
236
+ sink = [dir, sub]
237
+ } else if (a === '--frozen') {
238
+ const v = argv[++i]
239
+ if (!v) {
240
+ console.error('--frozen needs a directory name')
241
+ process.exit(2)
242
+ }
243
+ frozenNames.add(v)
244
+ } else if (a === '-h' || a === '--help') {
245
+ console.log(
246
+ 'usage: doc-rename <oldPath> <newPath> [--dry-run] [--json] [--replay] [--frozen <dirName>...] [--no-manifest-freeze] [--textual]\n' +
247
+ ' doc-rename --sink <dir> <sub> [--dry-run] [--json] [--frozen <dirName>...] [--no-manifest-freeze] [--textual]\n' +
248
+ ' freeze policy: folder-manifest archived: true declarations, discovered automatically;\n' +
249
+ ' --frozen replaces the whole policy for this run, --no-manifest-freeze skips manifest reading')
250
+ process.exit(0)
251
+ } else if (a.startsWith('--')) {
252
+ console.error(`unknown option: ${a}`)
253
+ process.exit(2)
254
+ } else paths.push(a)
255
+ }
256
+ // --replay asserts a COMPLETED pair (link-only repair); --sink plans NEW
257
+ // moves — the two contradict each other, so the combination is a usage
258
+ // error rather than a silently inert flag.
259
+ if (sink !== null && replay) {
260
+ console.error('--replay repairs an already-completed pair; --sink plans new moves — they cannot combine')
261
+ process.exit(2)
262
+ }
263
+ let oldPath, newPath
264
+ if (sink !== null) {
265
+ if (paths.length !== 0) {
266
+ usage()
267
+ process.exit(2)
268
+ }
269
+ ;[oldPath, newPath] = [sink[0], `${sink[0].replace(/[/\\]+$/, '')}/${sink[1]}`]
270
+ } else if (paths.length === 2) {
271
+ ;[oldPath, newPath] = paths
272
+ } else {
273
+ usage()
274
+ process.exit(2)
275
+ }
276
+
277
+ // Pre-flight repo discovery: the kernel classifies "no git on PATH" vs
278
+ // "outside a repository" (the same discovery the kernel's report face
279
+ // degrades on) — refuse cleanly as a usage error either way.
280
+ const discovery = discoverRepositoryRoot(process.cwd())
281
+ if (!discovery.discovered) {
282
+ console.error(discovery.code === 'git-unavailable'
283
+ ? 'git not found on PATH — this tool needs git.'
284
+ : 'cwd is not inside a git repository — the repo is discovered from cwd; cd into one and re-run.')
285
+ process.exit(2)
286
+ }
287
+ const repoRoot = discovery.topLevel
288
+
289
+ // Freeze policy: --frozen names replace the manifest declarations for this
290
+ // run; --no-manifest-freeze skips manifest reading; neither means declared
291
+ // trees apply, no declarations means nothing is frozen. Predicates come
292
+ // from the kernel — the product face carries no predicate copies.
293
+ let isFrozen
294
+ if (frozenNames.size > 0) {
295
+ isFrozen = frozenSourcePredicate(repoRoot, [...frozenNames])
296
+ } else if (!noManifestFreeze) {
297
+ const policy = await loadFreezePolicy('doc-rename', repoRoot)
298
+ if (policy.frozenTrees !== undefined) isFrozen = frozenTreePredicate(repoRoot, policy.frozenTrees)
299
+ }
300
+
301
+ const root = process.cwd()
302
+ const planOptions = {}
303
+ if (isFrozen !== undefined) planOptions.isFrozen = isFrozen
304
+ if (textual) planOptions.textual = true
305
+ if (replay) planOptions.replay = true
306
+ const { certain, plan } = sink !== null
307
+ ? planSink(root, sink[0], sink[1], planOptions)
308
+ : planRename(root, oldPath, newPath, planOptions)
309
+
310
+ if (!certain) {
311
+ const conflicts = plan.conflicts.map(conflictView)
312
+ const remedy = conflicts.some((c) => c.code === 'no-rename-evidence')
313
+ ? noEvidenceRemedy(root, oldPath, newPath)
314
+ : conflicts.some((c) => c.code === 'old-path-untracked')
315
+ ? UNTRACKED_SOURCE_REMEDY
316
+ : conflicts.some((c) => c.code === 'old-path-missing')
317
+ ? OLD_PATH_MISSING_REMEDY
318
+ : undefined
319
+ if (json) {
320
+ console.log(JSON.stringify({ status: 'conflict', conflicts, skips: plan.skips.map(skipView), ...(remedy ? { remedy } : {}) }, null, 2))
321
+ } else {
322
+ console.log(renderConflict(conflicts, plan.skips, remedy))
323
+ }
324
+ process.exit(1)
325
+ }
326
+
327
+ if (dryRun) {
328
+ if (json) {
329
+ console.log(JSON.stringify({
330
+ status: 'dry-run',
331
+ linkOnly: plan.linkOnly,
332
+ ...(replay ? { asserted: true } : {}),
333
+ oldPath,
334
+ newPath,
335
+ wouldEdit: [...plan.editsByFile.keys()].map((f) => posixRelative(plan.root, f)),
336
+ relabels: plan.relabels.map(relabelView),
337
+ textuals: plan.textuals.map(textualView),
338
+ skips: plan.skips.map(skipView),
339
+ }, null, 2))
340
+ } else {
341
+ console.log(renderDryRun(plan, oldPath, newPath, replay))
342
+ }
343
+ process.exit(0)
344
+ }
345
+
346
+ const result = (() => {
347
+ try {
348
+ return applyRenamePlan(plan)
349
+ } catch (error) {
350
+ if (!(error instanceof RenameApplyError)) throw error
351
+ const rel = (abs) => posixRelative(plan.root, abs)
352
+ const movedPairs = error.movedPairs.map((p) => `${rel(p.oldPath)} -> ${rel(p.newPath)}`)
353
+ if (json) {
354
+ console.log(JSON.stringify({
355
+ status: 'apply-failed',
356
+ code: error.code,
357
+ oldPath: rel(error.pair.oldPath),
358
+ newPath: rel(error.pair.newPath),
359
+ gitMessage: error.gitMessage,
360
+ movedPairs,
361
+ }, null, 2))
362
+ } else {
363
+ const lines = [`apply failed ${rel(error.pair.oldPath)} -> ${rel(error.pair.newPath)} (${error.gitMessage})`]
364
+ if (movedPairs.length > 0) {
365
+ lines.push('pairs already moved before the failure (the worktree is half-changed):')
366
+ for (const m of movedPairs) lines.push(` ${m}`)
367
+ } else {
368
+ lines.push('nothing was moved; no content edits were written')
369
+ }
370
+ console.log(lines.join('\n'))
371
+ }
372
+ process.exit(1)
373
+ }
374
+ })()
375
+ if (json) {
376
+ console.log(JSON.stringify({
377
+ status: result.moved ? 'moved' : 'repaired',
378
+ ...(replay ? { asserted: true } : {}),
379
+ oldPath,
380
+ newPath,
381
+ edited: result.edited,
382
+ relabels: plan.relabels.map(relabelView),
383
+ textuals: plan.textuals.map(textualView),
384
+ skips: plan.skips.map(skipView),
385
+ }, null, 2))
386
+ } else {
387
+ console.log(renderApplied(result, plan, oldPath, newPath, replay))
388
+ }
389
+ process.exit(0)
390
+ }
@@ -0,0 +1,55 @@
1
+ {
2
+ "meta": {
3
+ "description": "L0 semantic-canon conformance corpus — language-neutral pure data. Capabilities: the classification caliber every implementation must agree on, wiki-link extraction (targets with fragment/alias split, code-region exclusion), and registered-scheme recognition (ukp the first resident; unregistered scheme shapes are not references). Each consumer repo carries this file as a verbatim copy with a mechanical sync lock and runs its own thin runner over the capabilities it implements.",
4
+ "taxonomy": {
5
+ "local": "resolves against the document tree: document-relative paths and Windows drive-letter absolute paths (single letter + ':' + '/' or '\\')",
6
+ "scheme": "a real URI — scheme of two letters or more (http, mailto, doi, obsidian, file:///D:/...)",
7
+ "protocol-relative": "starts with '//'",
8
+ "root-absolute": "starts with a single '/'",
9
+ "in-page": "starts with '#', or is the empty destination (mdast url '' from `[x]()` — href \"\" renders as the current page; ruled 2026-10-14 when the declared divergence closed)"
10
+ },
11
+ "knownScopeLines": [
12
+ "anchors and percent-decoding — resolution capability, out of the classification set"
13
+ ]
14
+ },
15
+ "cases": [
16
+ { "capability": "classification", "id": "relative-plain", "url": "guide.md", "expect": "local" },
17
+ { "capability": "classification", "id": "relative-fragment", "url": "docs/a.md#Start", "expect": "local" },
18
+ { "capability": "classification", "id": "relative-traversal", "url": "../x.md", "expect": "local" },
19
+ { "capability": "classification", "id": "relative-percent-encoded", "url": "my%20doc.md", "expect": "local" },
20
+ { "capability": "classification", "id": "relative-dot-slash", "url": "./x.md", "expect": "local" },
21
+ { "capability": "classification", "id": "drive-forward", "url": "D:/x.md", "expect": "local", "drive": true },
22
+ { "capability": "classification", "id": "drive-backslash", "url": "E:\\y.md", "expect": "local", "drive": true },
23
+ { "capability": "classification", "id": "drive-lowercase", "url": "d:/x.md", "expect": "local", "drive": true },
24
+ { "capability": "classification", "id": "drive-nested-backslash", "url": "D:\\x\\y.md", "expect": "local", "drive": true },
25
+ { "capability": "classification", "id": "drive-with-fragment", "url": "D:/x.md#Section", "expect": "local", "drive": true },
26
+ { "capability": "classification", "id": "scheme-https", "url": "https://example.com/x.md", "expect": "scheme" },
27
+ { "capability": "classification", "id": "scheme-http-local-port", "url": "http://127.0.0.1:3080", "expect": "scheme" },
28
+ { "capability": "classification", "id": "scheme-mailto", "url": "mailto:a@b.c", "expect": "scheme" },
29
+ { "capability": "classification", "id": "scheme-doi", "url": "doi:10.1000/182", "expect": "scheme" },
30
+ { "capability": "classification", "id": "scheme-obsidian", "url": "obsidian://open?v=x", "expect": "scheme" },
31
+ { "capability": "classification", "id": "scheme-file-uri-drive", "url": "file:///D:/x.md", "expect": "scheme" },
32
+ { "capability": "classification", "id": "bare-drive-no-separator", "url": "D:", "expect": "scheme" },
33
+ { "capability": "classification", "id": "protocol-relative", "url": "//cdn.example/y", "expect": "protocol-relative" },
34
+ { "capability": "classification", "id": "root-absolute", "url": "/site/x.md", "expect": "root-absolute" },
35
+ { "capability": "classification", "id": "in-page-fragment", "url": "#anchor", "expect": "in-page" },
36
+ { "capability": "classification", "id": "in-page-empty-destination", "url": "", "expect": "in-page" },
37
+ { "capability": "wiki-extraction", "id": "wiki-plain", "source": "see [[note]] here", "expect": [ { "target": "note" } ] },
38
+ { "capability": "wiki-extraction", "id": "wiki-fragment", "source": "[[note#Heading]]", "expect": [ { "target": "note", "fragment": "Heading" } ] },
39
+ { "capability": "wiki-extraction", "id": "wiki-alias", "source": "[[note|shown]]", "expect": [ { "target": "note", "alias": "shown" } ] },
40
+ { "capability": "wiki-extraction", "id": "wiki-full-form", "source": "[[dir/note#Head|alias text]]", "expect": [ { "target": "dir/note", "fragment": "Head", "alias": "alias text" } ] },
41
+ { "capability": "wiki-extraction", "id": "wiki-embed-prefix", "source": "![[note]]", "expect": [ { "target": "note" } ] },
42
+ { "capability": "wiki-extraction", "id": "wiki-inline-code-excluded", "source": "a `[[note]]` mention", "expect": [] },
43
+ { "capability": "wiki-extraction", "id": "wiki-fenced-code-excluded", "source": "```\n[[note]]\n```", "expect": [] },
44
+ { "capability": "wiki-extraction", "id": "wiki-whitespace-target-excluded", "source": "[[ ]]", "expect": [] },
45
+ { "capability": "wiki-extraction", "id": "wiki-md-link-coexists", "source": "[[note]] and [md](a.md)", "expect": [ { "target": "note" } ] },
46
+ { "capability": "scheme-recognition", "id": "ukp-registered", "url": "ukp://name/path", "expect": { "scheme": "ukp", "address": "name/path" } },
47
+ { "capability": "scheme-recognition", "id": "ukp-uppercase-scheme", "url": "UKP://name", "expect": { "scheme": "ukp", "address": "name" } },
48
+ { "capability": "scheme-recognition", "id": "ukp-fragment-stripped", "url": "ukp://name/p#frag", "expect": { "scheme": "ukp", "address": "name/p" } },
49
+ { "capability": "scheme-recognition", "id": "ukp-percent-decoded", "url": "ukp://name/my%20doc", "expect": { "scheme": "ukp", "address": "name/my doc" } },
50
+ { "capability": "scheme-recognition", "id": "ukp-malformed-escape-kept", "url": "ukp://name/my%zzdoc", "expect": { "scheme": "ukp", "address": "name/my%zzdoc" } },
51
+ { "capability": "scheme-recognition", "id": "ukp-query-preserved", "url": "ukp://name/p?q=1", "expect": { "scheme": "ukp", "address": "name/p?q=1" } },
52
+ { "capability": "scheme-recognition", "id": "scheme-unregistered-not-a-reference", "url": "https://example.com/x", "expect": null },
53
+ { "capability": "scheme-recognition", "id": "drive-shape-not-a-scheme", "url": "D://x", "expect": null }
54
+ ]
55
+ }
@@ -0,0 +1,87 @@
1
+ import type { RepositoryUnavailableCode } from './links/index.js';
2
+ /**
3
+ * Report-face parameter and output types — plain structural shapes
4
+ * (`ChangeSet` / `ReportViolation`) so host gate adapters assign them
5
+ * without mapping. The kernel owns no gate
6
+ * vocabulary; policy reaches it only through these shapes.
7
+ */
8
+ export interface ChangeSet {
9
+ /** Session-written paths; the resolution base is the `root` passed to `check`. Readonly — the kernel never mutates the change set. */
10
+ paths?: readonly string[];
11
+ /** True when the change set cannot be enumerated — every violation is attributable. */
12
+ opaque?: boolean;
13
+ }
14
+ export interface ReportViolation {
15
+ /** Stable report category; additive to the existing report shape. */
16
+ class: ReportViolationClass;
17
+ file: string;
18
+ line: number;
19
+ reason: string;
20
+ remedy: {
21
+ kind: 'manual';
22
+ guidance: string;
23
+ };
24
+ }
25
+ /** Stable categories exposed by the doc-link report face. */
26
+ export type ReportViolationClass = 'target-missing' | 'anchor-missing' | 'outside-repository';
27
+ /**
28
+ * Structured "this check does not apply here" outcome: the workspace sits
29
+ * outside any git repository (or git itself is unavailable), so there is no
30
+ * git-discovered file set to scan and no violation can exist. Returning this
31
+ * instead of throwing keeps an infrastructure non-fact from being wrapped by
32
+ * gate hosts into a content-violation-shaped block that no content edit could
33
+ * ever fix. `code` is the stable branching key; `message` is face-neutral
34
+ * wording each delivery face may reword (never parse).
35
+ */
36
+ export interface ReportNotApplicable {
37
+ /** Always `false` — the discriminator for consumers holding a `CheckOutcome`. */
38
+ applicable: false;
39
+ /** Which precondition failed: `not-a-git-repository` / `git-unavailable`. */
40
+ code: RepositoryUnavailableCode;
41
+ /** Face-neutral one-liner; consumers surface or reword it, never parse it. */
42
+ message: string;
43
+ }
44
+ /** `check` result: the findings array, or — where the scan cannot apply — the structured not-applicable outcome. */
45
+ export type CheckOutcome = ReportViolation[] | ReportNotApplicable;
46
+ /**
47
+ * Report face: full scan, then filter to session-attributable violations (the
48
+ * stop-tier consumer semantics). A workspace whose root cannot be discovered
49
+ * through git degrades first: the structured not-applicable outcome returns
50
+ * before any option is parsed or any file is read, so attribution and freeze
51
+ * overlays never run on ground the scan cannot apply to.
52
+ */
53
+ export declare function check(root: string, changes?: ChangeSet, options?: Record<string, unknown>): CheckOutcome;
54
+ /**
55
+ * The `frozen-dirs` gate option: directory names whose content is frozen
56
+ * (read-only by repo policy, e.g. DOC-style `archived/` trees). Must be a
57
+ * list of strings when present; anything else fails loud (a typo'd policy
58
+ * must not silently widen or narrow the check). Shared with the `md_rename`
59
+ * tool face so a bad shape fails on BOTH faces, never just one.
60
+ */
61
+ export declare function parseFrozenDirs(value: unknown): string[] | undefined;
62
+ /**
63
+ * Frozen-source predicate for a `frozen-dirs` name set: a file is frozen when
64
+ * any ancestor directory name (repo-root-relative, any depth) hits the
65
+ * declared set — the `{subtree}/archived/{original path}` shape. Shared by
66
+ * the gate (source exemption) and the `md_rename` tool (read-only holders),
67
+ * so both faces keep one freeze semantics.
68
+ */
69
+ export declare function frozenSourcePredicate(repoRoot: string, frozenDirs: readonly string[]): (absSource: string) => boolean;
70
+ /**
71
+ * The `frozen-trees` gate option: repository-root-relative directory paths
72
+ * (forward slashes) whose content is frozen by a declaration living on the
73
+ * tree itself (the folder-manifest `archived: true` gesture). Must be a list
74
+ * of strings when present; anything else fails loud, exactly like
75
+ * `parseFrozenDirs` — a typo'd policy must not silently widen or narrow the
76
+ * check. The path twin of the name-list gesture: the caller (product face or
77
+ * gate adapter) reads the declarations and passes the tree list; this module
78
+ * never reads manifests.
79
+ */
80
+ export declare function parseFrozenTrees(value: unknown): string[] | undefined;
81
+ /**
82
+ * Frozen-source predicate for a `frozen-trees` path set: a file is frozen
83
+ * when it sits inside any declared tree (the tree's own root included). Unlike
84
+ * the name-list gesture this freezes exactly the declared trees — a
85
+ * same-named directory elsewhere stays in scope.
86
+ */
87
+ export declare function frozenTreePredicate(repoRoot: string, trees: readonly string[]): (absSource: string) => boolean;