@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.
- package/LICENSE +21 -0
- package/README.md +76 -2
- package/cli/config.mjs +86 -0
- package/cli/doc-link.mjs +139 -0
- package/cli/kernel.mjs +86 -0
- package/cli/normalize.mjs +91 -0
- package/cli/rename.mjs +390 -0
- package/conformance/cases.json +55 -0
- package/lib/gate-check.d.ts +83 -0
- package/lib/gate-check.js +212 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +8 -0
- package/lib/links/anchors.d.ts +43 -0
- package/lib/links/anchors.js +93 -0
- package/lib/links/cli.d.ts +20 -0
- package/lib/links/cli.js +72 -0
- package/lib/links/git.d.ts +156 -0
- package/lib/links/git.js +329 -0
- package/lib/links/index.d.ts +33 -0
- package/lib/links/index.js +25 -0
- package/lib/links/markdown.d.ts +125 -0
- package/lib/links/markdown.js +253 -0
- package/lib/links/normalize.d.ts +40 -0
- package/lib/links/normalize.js +102 -0
- package/lib/links/rebase.d.ts +24 -0
- package/lib/links/rebase.js +44 -0
- package/lib/links/rename.d.ts +257 -0
- package/lib/links/rename.js +864 -0
- package/lib/links/resolve.d.ts +143 -0
- package/lib/links/resolve.js +295 -0
- package/lib/links/scheme.d.ts +112 -0
- package/lib/links/scheme.js +206 -0
- package/lib/links/textual.d.ts +26 -0
- package/lib/links/textual.js +144 -0
- package/package.json +75 -4
- package/skills/md-tools/SKILL.md +42 -0
- package/skills/md-tools/references/freeze.md +16 -0
- package/skills/md-tools/references/payload.md +28 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CatheadOwl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @catheadowl/md-tools
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Keep Markdown references true while a repository moves.** `doc-rename` moves files and directories and rebases every in-repo reference as one atomic plan; `doc-link` checks that every internal link and heading anchor resolves; `doc-normalize` migrates `/`-prefixed internal links to document-relative form. The same engine ships in this package as an importable library.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @catheadowl/md-tools
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Node >= 18 and git on PATH. All three commands run inside a git repository — the repo root is discovered from the current directory. Outside a repository (or without git) they refuse cleanly with exit 2.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
# Move a file and rebase every in-repo Markdown reference to it
|
|
17
|
+
doc-rename docs/old-name.md docs/new-name.md
|
|
18
|
+
|
|
19
|
+
# Preview the plan before writing
|
|
20
|
+
doc-rename docs/old-name.md docs/new-name.md --dry-run
|
|
21
|
+
|
|
22
|
+
# Sink a whole directory tree under one new name as a single atomic plan
|
|
23
|
+
doc-rename --sink <dir> <sub>
|
|
24
|
+
|
|
25
|
+
# Check every internal link and anchor resolves (read-only audit)
|
|
26
|
+
doc-link
|
|
27
|
+
|
|
28
|
+
# Machine-readable violations (file:line, url, reason)
|
|
29
|
+
doc-link --json
|
|
30
|
+
|
|
31
|
+
# One-time migration of /-prefixed internal links to document-relative form
|
|
32
|
+
doc-normalize [--fix] [--json]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`doc-rename` is plan-then-apply and all-or-nothing — the worktree is never half-changed, and refusals are structured, never guessed. Flags, semantics and refusal codes are canonical in each command's `--help`.
|
|
36
|
+
|
|
37
|
+
## Exit codes
|
|
38
|
+
|
|
39
|
+
| Code | Meaning |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `0` | clean |
|
|
42
|
+
| `1` | findings, conflicts, or a startup-guard refusal |
|
|
43
|
+
| `2` | usage error (including the outside-repo and no-git refusals) |
|
|
44
|
+
|
|
45
|
+
## Declared freeze policy
|
|
46
|
+
|
|
47
|
+
A directory whose `manifest.yml` declares `archived: true` is frozen history, picked up automatically: `doc-link` exempts frozen files as *sources* (their out-links are still checked) and `doc-rename` treats them as read-only. `--frozen <dirName>` replaces the declared policy for one run; `--no-manifest-freeze` skips it. Flag semantics: `doc-link --help`; the pinned read and its fail-loud rules: `skills/md-tools/references/freeze.md`.
|
|
48
|
+
|
|
49
|
+
## Agent skill
|
|
50
|
+
|
|
51
|
+
The package ships an agent-facing skill payload at `skills/md-tools/` — the whole subtree is the install unit (the shape ecosystem skill installers scan; copy or link it into an agent skill directory). The package never writes an agent directory; the install/refresh contract rides inside the tree.
|
|
52
|
+
|
|
53
|
+
## Library
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npm install @catheadowl/md-tools
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
import { checkRepository } from '@catheadowl/md-tools'
|
|
61
|
+
|
|
62
|
+
for (const v of checkRepository(root)) {
|
|
63
|
+
console.log(`${v.file}:${v.line}: ${v.url} — ${v.reason}`)
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The engine classifies, extracts, resolves, anchor-checks and plans byte-preserving rewrites of links, images, definitions, `[[wikilinks]]` and registered scheme addresses over a git tree — the file universe is `git ls-files`; extraction and rewrite planning are pure string functions. It never decides when to check or what to exempt: freeze policy, deny lists and wiki disambiguation flow in as parameters. The typed surface is the API reference — `lib/index.d.ts`, with the data plane at `@catheadowl/md-tools/links/index.js` and the report face at `@catheadowl/md-tools/gate-check.js`.
|
|
68
|
+
|
|
69
|
+
Ports that do not import the library can prove agreement against the shipped conformance corpus at `@catheadowl/md-tools/conformance/cases.json` — pure data, one case per entry, tagged by capability.
|
|
70
|
+
|
|
71
|
+
## Development
|
|
72
|
+
|
|
73
|
+
Source checkouts, tests and the backlog are documented in the source repository, not in this package.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT.
|
package/cli/config.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// cli/config.mjs — freeze-policy discovery for the md-tools bins: the
|
|
2
|
+
// folder-manifest `archived: true` declaration is the policy's single source,
|
|
3
|
+
// read as a default-on base layer. Product-package face: manifest reading and
|
|
4
|
+
// tree-list assembly live here; the kernel receives the list as a data
|
|
5
|
+
// parameter (`frozen-trees`) and never learns about manifests.
|
|
6
|
+
//
|
|
7
|
+
// Pinned narrow read: only files named manifest.yml, parsed as YAML mappings
|
|
8
|
+
// with schema_version 1 and a boolean `archived`; every other key is
|
|
9
|
+
// folder-manifest territory and ignored. A manifest.yml that cannot be
|
|
10
|
+
// parsed, is not a mapping, carries an unsupported schema_version, or shapes
|
|
11
|
+
// `archived` non-boolean fails loud (exit 1, one line naming the file): a
|
|
12
|
+
// broken carrier of the freeze fact makes the policy unknowable and must not
|
|
13
|
+
// silently read as "no policy". The scan skips `.git` and `node_modules`
|
|
14
|
+
// (vendored trees are not governance homes); a repo with no manifest.yml
|
|
15
|
+
// never touches the YAML parser at all.
|
|
16
|
+
//
|
|
17
|
+
// The YAML parser is imported dynamically: bins must carry no static
|
|
18
|
+
// third-party imports, or a missing dependency would die at ESM link time
|
|
19
|
+
// with a raw module error before any diagnosis could run.
|
|
20
|
+
import { readdirSync, readFileSync } from 'node:fs'
|
|
21
|
+
import { join, relative, sep } from 'node:path'
|
|
22
|
+
|
|
23
|
+
export const MANIFEST_FILE = 'manifest.yml'
|
|
24
|
+
|
|
25
|
+
/** Directories never scanned for freeze declarations. */
|
|
26
|
+
const SKIPPED_DIRS = new Set(['.git', 'node_modules'])
|
|
27
|
+
|
|
28
|
+
function die(binName, problem) {
|
|
29
|
+
console.error(`${binName}: ${problem}`)
|
|
30
|
+
process.exit(1)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isPlainObject(value) {
|
|
34
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Recursive manifest.yml discovery (deterministic order; symlinked dirs are not descended). */
|
|
38
|
+
function findManifests(dir, found) {
|
|
39
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
40
|
+
if (entry.isDirectory()) {
|
|
41
|
+
if (SKIPPED_DIRS.has(entry.name)) continue
|
|
42
|
+
findManifests(join(dir, entry.name), found)
|
|
43
|
+
} else if (entry.name === MANIFEST_FILE) {
|
|
44
|
+
found.push(join(dir, entry.name))
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Read the repo's freeze declarations for one bin face. Returns
|
|
51
|
+
* `{ frozenTrees }` — repository-relative posix directory paths of trees
|
|
52
|
+
* whose manifest declares `archived: true` — or `{}` when nothing is
|
|
53
|
+
* declared. A repo without manifest.yml files returns `{}` without ever
|
|
54
|
+
* importing the parser.
|
|
55
|
+
*/
|
|
56
|
+
export async function loadFreezePolicy(binName, repoRoot) {
|
|
57
|
+
const manifests = []
|
|
58
|
+
findManifests(repoRoot, manifests)
|
|
59
|
+
if (manifests.length === 0) return {}
|
|
60
|
+
let YAML
|
|
61
|
+
try {
|
|
62
|
+
YAML = await import('yaml')
|
|
63
|
+
} catch {
|
|
64
|
+
die(binName, `freeze declarations are present but the YAML parser dependency is not installed — reinstall @catheadowl/md-tools`)
|
|
65
|
+
}
|
|
66
|
+
const frozenTrees = []
|
|
67
|
+
for (const filePath of manifests.sort()) {
|
|
68
|
+
const rel = relative(repoRoot, filePath).split(sep).join('/')
|
|
69
|
+
let doc
|
|
70
|
+
try {
|
|
71
|
+
doc = YAML.parse(readFileSync(filePath, 'utf8'))
|
|
72
|
+
} catch (error) {
|
|
73
|
+
die(binName, `${rel} is not valid YAML (${String(error.message).split('\n')[0]}) — the freeze-fact carrier is unreadable`)
|
|
74
|
+
}
|
|
75
|
+
if (doc === null || doc === undefined) continue // comments-only file: no declaration
|
|
76
|
+
if (!isPlainObject(doc)) die(binName, `${rel} must be a mapping at the top level`)
|
|
77
|
+
if (doc.schema_version !== 1) {
|
|
78
|
+
die(binName, `${rel}: unsupported schema_version ${JSON.stringify(doc.schema_version)} — this tool pins schema 1`)
|
|
79
|
+
}
|
|
80
|
+
if (doc.archived !== undefined && typeof doc.archived !== 'boolean') {
|
|
81
|
+
die(binName, `${rel}: archived must be a boolean (true = frozen history zone)`)
|
|
82
|
+
}
|
|
83
|
+
if (doc.archived === true) frozenTrees.push(rel.slice(0, rel.length - MANIFEST_FILE.length - 1))
|
|
84
|
+
}
|
|
85
|
+
return frozenTrees.length > 0 ? { frozenTrees } : {}
|
|
86
|
+
}
|
package/cli/doc-link.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* doc-link — whole-repo Markdown link-integrity check: every internal
|
|
4
|
+
* reference (link, image, definition) must resolve to an existing target and,
|
|
5
|
+
* for Markdown targets, a valid heading anchor.
|
|
6
|
+
*
|
|
7
|
+
* Thin CLI face over the Markdown reference kernel shipped in this package
|
|
8
|
+
* (lib/) — import, not a copy; semantics and their full test face live in the kernel.
|
|
9
|
+
* Drive-letter links classify as local absolute paths and are judged:
|
|
10
|
+
* missing targets and outside-repository targets are violations. The kernel
|
|
11
|
+
* import is guarded by ./kernel.mjs: a missing or stale kernel build exits 1
|
|
12
|
+
* with a reinstall remedy instead of a raw, misleading ESM error.
|
|
13
|
+
*
|
|
14
|
+
* Read-only: never writes.
|
|
15
|
+
*
|
|
16
|
+
* Freeze policy, default base layer: folder-manifest `archived: true`
|
|
17
|
+
* declarations (manifest.yml on the frozen tree itself) — every declared
|
|
18
|
+
* tree's files are exempt as *sources*, discovered automatically, no flags
|
|
19
|
+
* and no extra file needed. Narrow pinned read (schema 1, boolean archived,
|
|
20
|
+
* everything else ignored); a manifest.yml that is unparseable or shaped
|
|
21
|
+
* wrong exits 1 with a one-line diagnosis instead of silently dropping the
|
|
22
|
+
* policy. --frozen flags replace the whole policy for one run (not a union);
|
|
23
|
+
* --no-manifest-freeze skips manifest reading entirely (bare names-only run).
|
|
24
|
+
*
|
|
25
|
+
* Usage (run inside a git repository; the repo root is discovered from cwd):
|
|
26
|
+
* doc-link [--frozen <dirName>]... [--no-manifest-freeze] [--json]
|
|
27
|
+
*
|
|
28
|
+
* --frozen <name> directory name whose content is frozen (read-only by policy);
|
|
29
|
+
* exempt as *sources* — their rotting out-links are unfixable
|
|
30
|
+
* noise. Frozen targets stay in scope: an active document
|
|
31
|
+
* linking into a frozen dir must still resolve. Mirrors the
|
|
32
|
+
* extras `doc-link` gate's `frozen-dirs` option semantics
|
|
33
|
+
* (`frozenSourcePredicate`: an ancestor directory name
|
|
34
|
+
* hitting the list freezes the file — the file's own name
|
|
35
|
+
* alone never counts). Replaces the manifest freeze policy
|
|
36
|
+
* for this run.
|
|
37
|
+
* --no-manifest-freeze
|
|
38
|
+
* skip folder-manifest archived declarations entirely —
|
|
39
|
+
* neither read nor trusted for this run.
|
|
40
|
+
* --json machine-readable violation objects (gate shape)
|
|
41
|
+
* Agent skill: the shipped skill payload lives at `skills/md-tools/`
|
|
42
|
+
* (package root; the whole subtree is the install unit) — the agent installs.
|
|
43
|
+
* Exit codes: 0 clean, 1 violations found (or failed kernel-freshness startup
|
|
44
|
+
* guard, or a malformed freeze declaration), 2 usage error (also a cwd
|
|
45
|
+
* outside any git repository or no git on PATH — classified by the kernel,
|
|
46
|
+
* the same discovery its report face degrades on, so one engine answers in
|
|
47
|
+
* one voice on both faces).
|
|
48
|
+
*/
|
|
49
|
+
import { realpathSync } from 'node:fs'
|
|
50
|
+
import { pathToFileURL } from 'node:url'
|
|
51
|
+
|
|
52
|
+
import { loadKernel } from './kernel.mjs'
|
|
53
|
+
import { loadFreezePolicy } from './config.mjs'
|
|
54
|
+
|
|
55
|
+
// Dynamic by necessity: a static kernel import would link before any code
|
|
56
|
+
// runs, so the freshness guard in kernel.mjs could never fire first.
|
|
57
|
+
const { check, discoverRepositoryRoot } = await loadKernel('doc-link')
|
|
58
|
+
|
|
59
|
+
// The bin face runs through the global link's junction/symlink: argv[1] names
|
|
60
|
+
// the link path while import.meta.url carries the real path — accept either.
|
|
61
|
+
const isMain = process.argv[1] && (import.meta.url === pathToFileURL(process.argv[1]).href
|
|
62
|
+
|| import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href)
|
|
63
|
+
if (isMain) {
|
|
64
|
+
const argv = process.argv.slice(2)
|
|
65
|
+
const frozenNames = []
|
|
66
|
+
let json = false
|
|
67
|
+
let noManifestFreeze = false
|
|
68
|
+
for (let i = 0; i < argv.length; i++) {
|
|
69
|
+
const a = argv[i]
|
|
70
|
+
if (a === '--json') json = true
|
|
71
|
+
else if (a === '--no-manifest-freeze') noManifestFreeze = true
|
|
72
|
+
else if (a === '--frozen') {
|
|
73
|
+
const v = argv[++i]
|
|
74
|
+
if (!v) {
|
|
75
|
+
console.error('--frozen needs a directory name')
|
|
76
|
+
process.exit(2)
|
|
77
|
+
}
|
|
78
|
+
frozenNames.push(v)
|
|
79
|
+
} else if (a === '-h' || a === '--help') {
|
|
80
|
+
console.log(
|
|
81
|
+
'usage: doc-link [--frozen <dirName>]... [--no-manifest-freeze] [--json]\n' +
|
|
82
|
+
' freeze policy: folder-manifest archived: true declarations, discovered automatically;\n' +
|
|
83
|
+
' --frozen replaces the whole policy for this run, --no-manifest-freeze skips manifest reading')
|
|
84
|
+
process.exit(0)
|
|
85
|
+
} else {
|
|
86
|
+
console.error(`unexpected argument: ${a}`)
|
|
87
|
+
process.exit(2)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Pre-flight repo discovery: the kernel classifies "no git on PATH" vs
|
|
92
|
+
// "outside a repository" — the same classification the kernel's check()
|
|
93
|
+
// degrades on, so both faces of one engine answer in one voice. Refuse
|
|
94
|
+
// cleanly as a usage error either way.
|
|
95
|
+
const discovery = discoverRepositoryRoot(process.cwd())
|
|
96
|
+
if (!discovery.discovered) {
|
|
97
|
+
console.error(discovery.code === 'git-unavailable'
|
|
98
|
+
? 'git not found on PATH — this tool needs git.'
|
|
99
|
+
: 'cwd is not inside a git repository — the repo is discovered from cwd; cd into one and re-run.')
|
|
100
|
+
process.exit(2)
|
|
101
|
+
}
|
|
102
|
+
const repoRoot = discovery.topLevel
|
|
103
|
+
|
|
104
|
+
// Freeze policy: --frozen names replace the manifest declarations for this
|
|
105
|
+
// run; --no-manifest-freeze skips manifest reading; neither means declared
|
|
106
|
+
// trees apply, no declarations means no freeze.
|
|
107
|
+
let freezeOptions
|
|
108
|
+
if (frozenNames.length > 0) {
|
|
109
|
+
freezeOptions = { 'frozen-dirs': frozenNames }
|
|
110
|
+
} else if (!noManifestFreeze) {
|
|
111
|
+
const policy = await loadFreezePolicy('doc-link', repoRoot)
|
|
112
|
+
if (policy.frozenTrees !== undefined) freezeOptions = { 'frozen-trees': policy.frozenTrees }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const outcome = check(process.cwd(), undefined, freezeOptions)
|
|
116
|
+
// Unreachable past the pre-flight above (same memoized discovery answers
|
|
117
|
+
// both); kept so the kernel's not-applicable union face can never crash the
|
|
118
|
+
// bin with a raw type error if that ever changes.
|
|
119
|
+
if (!Array.isArray(outcome)) {
|
|
120
|
+
console.error(outcome.message)
|
|
121
|
+
process.exit(2)
|
|
122
|
+
}
|
|
123
|
+
const violations = outcome
|
|
124
|
+
|
|
125
|
+
if (json) {
|
|
126
|
+
console.log(JSON.stringify({ checked: 'repository', violations }, null, 2))
|
|
127
|
+
} else {
|
|
128
|
+
if (violations.length === 0) {
|
|
129
|
+
console.log('clean — every internal Markdown reference resolves')
|
|
130
|
+
} else {
|
|
131
|
+
console.log(`${violations.length} violation(s):`)
|
|
132
|
+
for (const v of violations) {
|
|
133
|
+
console.log(` ${v.file}:${v.line} ${v.reason}`)
|
|
134
|
+
console.log(` remedy: ${v.remedy.guidance}`)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
process.exit(violations.length ? 1 : 0)
|
|
139
|
+
}
|
package/cli/kernel.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// cli/kernel.mjs — startup freshness guard + kernel loader for the three
|
|
2
|
+
// md-tools bins (doc-link / doc-rename / doc-normalize).
|
|
3
|
+
//
|
|
4
|
+
// The bins are committed source, while the kernel entry they consume
|
|
5
|
+
// (lib/index.js at the package root, the tsc product of src/) is a build
|
|
6
|
+
// product: in a source checkout it only exists after a build (lib/ is
|
|
7
|
+
// gitignored and a pull never runs it), so every source advance opens a
|
|
8
|
+
// CLI-new/kernel-stale window.
|
|
9
|
+
// In that window a static import died at ESM link time (static imports link
|
|
10
|
+
// before any code runs) with errors naming neither build nor setup ("does not
|
|
11
|
+
// provide an export named 'planSink'", ERR_MODULE_NOT_FOUND), which reads as a
|
|
12
|
+
// version mismatch — a misdiagnosis. So the guard owns the import: bins call
|
|
13
|
+
// loadKernel(), which checks freshness first and only then dynamic-imports
|
|
14
|
+
// the kernel.
|
|
15
|
+
//
|
|
16
|
+
// Freshness judgment is the existence + src/lib mtime heuristic, not a
|
|
17
|
+
// version stamp written by the build step: a build rewrites every output
|
|
18
|
+
// file, so newest-lib-mtime equals last build time; anything in src newer
|
|
19
|
+
// than that is unbuilt source. An installed package ships lib/ without src/,
|
|
20
|
+
// so the comparison is skipped there — the entry-existence check already
|
|
21
|
+
// covers a broken install.
|
|
22
|
+
import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs'
|
|
23
|
+
import { dirname, join } from 'node:path'
|
|
24
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
25
|
+
|
|
26
|
+
const REMEDY = 'reinstall @catheadowl/md-tools (from a source checkout: run `npm run setup` in the checkout root to rebuild the kernel and relink the bins)'
|
|
27
|
+
|
|
28
|
+
function die(binName, problem) {
|
|
29
|
+
console.error(`${binName}: ${problem} — ${REMEDY}`)
|
|
30
|
+
process.exit(1)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Newest file mtime (ms) under dir (recursive), restricted to kept names; -Infinity when nothing matches. */
|
|
34
|
+
function newestMtime(dir, keep) {
|
|
35
|
+
let newest = -Infinity
|
|
36
|
+
const stack = [dir]
|
|
37
|
+
while (stack.length > 0) {
|
|
38
|
+
const current = stack.pop()
|
|
39
|
+
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
40
|
+
const path = join(current, entry.name)
|
|
41
|
+
try {
|
|
42
|
+
if (entry.isDirectory()) stack.push(path)
|
|
43
|
+
else if (keep(entry.name)) newest = Math.max(newest, statSync(path).mtimeMs)
|
|
44
|
+
} catch {
|
|
45
|
+
// vanished mid-scan — the survivors' timestamps still speak
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return newest
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Package root = this file's directory's parent (cli/kernel.mjs), realpath'd so a global link resolves to the checkout it points into. */
|
|
53
|
+
function packageRoot() {
|
|
54
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
55
|
+
try {
|
|
56
|
+
return realpathSync(join(here, '..'))
|
|
57
|
+
} catch {
|
|
58
|
+
return join(here, '..')
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Freshness-guarded kernel load for a bin face. Exits 1 with a one-line
|
|
64
|
+
* diagnosis + setup remedy when the kernel build is missing, its build is
|
|
65
|
+
* older than its source (the pull window), or the built graph fails to load
|
|
66
|
+
* (partial build). Returns the kernel module namespace otherwise.
|
|
67
|
+
*/
|
|
68
|
+
export async function loadKernel(binName) {
|
|
69
|
+
const pkgRoot = packageRoot()
|
|
70
|
+
const entry = join(pkgRoot, 'lib', 'index.js')
|
|
71
|
+
if (!existsSync(entry)) {
|
|
72
|
+
die(binName, `the kernel build is missing — ${entry} does not exist (lib/ is a gitignored tsc product: a pull freshens these bins but never the build)`)
|
|
73
|
+
}
|
|
74
|
+
// Staleness is a source-checkout concept: an installed package without src/
|
|
75
|
+
// has nothing to compare — the entry-existence check above already covers it.
|
|
76
|
+
const srcDir = join(pkgRoot, 'src')
|
|
77
|
+
if (existsSync(srcDir)
|
|
78
|
+
&& newestMtime(srcDir, (name) => name.endsWith('.ts')) > newestMtime(join(pkgRoot, 'lib'), () => true)) {
|
|
79
|
+
die(binName, `the kernel build is stale — ${pkgRoot} src/ changed after lib/ was last built (a pull freshens these bins instantly; the build only catches up on setup)`)
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
return await import(pathToFileURL(entry).href)
|
|
83
|
+
} catch (error) {
|
|
84
|
+
die(binName, `the kernel build failed to load (${error.code ?? error.name}: ${String(error.message).split('\n')[0]})`)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* doc-normalize — one-time migration CLI: rewrites existing `/`-prefixed internal
|
|
4
|
+
* Markdown references to document-relative form (the normalize face of the
|
|
5
|
+
* kernel shipped in this package's lib/ — import, not a copy).
|
|
6
|
+
*
|
|
7
|
+
* Only `/`-prefixed references whose target is a tracked repository path are
|
|
8
|
+
* rewritten — site-root (`/gates`), protocol-relative (`//`), scheme URLs, and
|
|
9
|
+
* unresolved `/` links are reported as skips and left verbatim. The kernel
|
|
10
|
+
* import is guarded by ./kernel.mjs: a missing or stale kernel build exits 1
|
|
11
|
+
* with a reinstall remedy instead of a raw, misleading ESM error.
|
|
12
|
+
*
|
|
13
|
+
* Usage (run inside a git repository; paths resolve from cwd's repo root):
|
|
14
|
+
* doc-normalize # check only (gate/pre-commit style)
|
|
15
|
+
* doc-normalize --fix # apply the rewrites
|
|
16
|
+
* doc-normalize --json # machine-readable plan
|
|
17
|
+
* Agent skill: the shipped skill payload lives at `skills/md-tools/`
|
|
18
|
+
* (package root; the whole subtree is the install unit) — the agent installs.
|
|
19
|
+
* Exit codes: check mode 1 when rewrites remain, 0 when clean or after --fix;
|
|
20
|
+
* 1 also covers the failed kernel-freshness startup guard; 2 usage error.
|
|
21
|
+
* Skips are honest reports, never failures.
|
|
22
|
+
*/
|
|
23
|
+
import { realpathSync } from 'node:fs'
|
|
24
|
+
import { pathToFileURL } from 'node:url'
|
|
25
|
+
|
|
26
|
+
import { loadKernel } from './kernel.mjs'
|
|
27
|
+
|
|
28
|
+
// Dynamic by necessity: a static kernel import would link before any code
|
|
29
|
+
// runs, so the freshness guard in kernel.mjs could never fire first.
|
|
30
|
+
const {
|
|
31
|
+
applyRootRelativeNormalization,
|
|
32
|
+
discoverRepositoryRoot,
|
|
33
|
+
planRootRelativeNormalization,
|
|
34
|
+
} = await loadKernel('doc-normalize')
|
|
35
|
+
|
|
36
|
+
function renderPlan(plan) {
|
|
37
|
+
const lines = [`${plan.rewrites.length} rewrite(s) planned, ${plan.skips.length} skip(s).`]
|
|
38
|
+
for (const r of plan.rewrites) lines.push(` ${r.file}:${r.line} ${r.url} -> ${r.href}`)
|
|
39
|
+
for (const s of plan.skips) lines.push(` [skip] ${s.file}:${s.line} ${s.url} (${s.reason})`)
|
|
40
|
+
return lines.join('\n')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The bin face runs through the global link's junction/symlink: argv[1] names
|
|
44
|
+
// the link path while import.meta.url carries the real path — accept either.
|
|
45
|
+
const isMain = process.argv[1] && (import.meta.url === pathToFileURL(process.argv[1]).href
|
|
46
|
+
|| import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href)
|
|
47
|
+
if (isMain) {
|
|
48
|
+
const argv = process.argv.slice(2)
|
|
49
|
+
let fix = false
|
|
50
|
+
let json = false
|
|
51
|
+
for (const a of argv) {
|
|
52
|
+
if (a === '--fix') fix = true
|
|
53
|
+
else if (a === '--json') json = true
|
|
54
|
+
else if (a === '-h' || a === '--help') {
|
|
55
|
+
console.log('usage: doc-normalize [--fix] [--json]')
|
|
56
|
+
process.exit(0)
|
|
57
|
+
} else {
|
|
58
|
+
console.error(`unknown option: ${a}`)
|
|
59
|
+
process.exit(2)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Pre-flight repo discovery: the kernel classifies "no git on PATH" vs
|
|
64
|
+
// "outside a repository" (the same discovery the kernel's report face
|
|
65
|
+
// degrades on) — refuse cleanly as a usage error either way.
|
|
66
|
+
const discovery = discoverRepositoryRoot(process.cwd())
|
|
67
|
+
if (!discovery.discovered) {
|
|
68
|
+
console.error(discovery.code === 'git-unavailable'
|
|
69
|
+
? 'git not found on PATH — this tool needs git.'
|
|
70
|
+
: 'cwd is not inside a git repository — the repo is discovered from cwd; cd into one and re-run.')
|
|
71
|
+
process.exit(2)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const plan = planRootRelativeNormalization(process.cwd())
|
|
75
|
+
|
|
76
|
+
if (json) {
|
|
77
|
+
console.log(JSON.stringify({
|
|
78
|
+
status: fix ? 'fixed' : plan.rewrites.length ? 'check' : 'clean',
|
|
79
|
+
rewrites: plan.rewrites,
|
|
80
|
+
skips: plan.skips,
|
|
81
|
+
}, null, 2))
|
|
82
|
+
} else {
|
|
83
|
+
console.log(renderPlan(plan))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (fix) {
|
|
87
|
+
applyRootRelativeNormalization(plan)
|
|
88
|
+
process.exit(0)
|
|
89
|
+
}
|
|
90
|
+
process.exit(plan.rewrites.length ? 1 : 0)
|
|
91
|
+
}
|