@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
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The report face of doc-core: every internal Markdown reference (link,
|
|
3
|
+
* image, definition) must resolve to an existing target and, for Markdown
|
|
4
|
+
* targets, a valid heading anchor. This module shapes `checkRepository`
|
|
5
|
+
* output into caller-facing violations plus the attribution predicate —
|
|
6
|
+
* policy (frozen dirs, change sets) flows in through parameters and is
|
|
7
|
+
* never decided here. For anchor-missing violations the remedy guidance
|
|
8
|
+
* carries a deterministic hint: the target's headings whose slug shares the
|
|
9
|
+
* longest prefix with the failed fragment, each with its exact `#anchor`,
|
|
10
|
+
* so the model can claim the heading it meant without knowing the slug rules.
|
|
11
|
+
*
|
|
12
|
+
* Where git discovers no worktree (a workspace outside any
|
|
13
|
+
* repository, or no git binary at all) the scan has no file set and cannot
|
|
14
|
+
* apply: `check` answers with the structured not-applicable outcome instead
|
|
15
|
+
* of throwing, so hosts can pass with a note rather than wrapping an
|
|
16
|
+
* infrastructure error into a block that no content edit could clear.
|
|
17
|
+
*
|
|
18
|
+
* External targets (`//`, `/`, scheme) and fragments onto non-Markdown
|
|
19
|
+
* targets are out of scope and never flagged; absolute local paths
|
|
20
|
+
* (`D:/…`) resolve and are judged. Repo policy via the
|
|
21
|
+
* caller's `options` overlay, in two gestures: `frozen-dirs` (a list of
|
|
22
|
+
* directory names) and `frozen-trees` (repository-relative tree paths — the
|
|
23
|
+
* declared-freeze form; callers read the declarations, e.g. a folder's
|
|
24
|
+
* `manifest.yml` declaring `archived: true`, and pass the list). Each
|
|
25
|
+
* exempts files inside as *sources* — frozen content is read-only by
|
|
26
|
+
* policy, so its rotting out-links are unfixable noise, never findings.
|
|
27
|
+
*/
|
|
28
|
+
import { readFileSync } from 'node:fs';
|
|
29
|
+
import { join } from 'node:path';
|
|
30
|
+
import { REASON_ANCHOR_MISSING, canonicalPath, checkRepository, discoverRepositoryRoot, documentAnchorPairs, pathInside, repositoryRoot } from './links/index.js';
|
|
31
|
+
const MANUAL_REMEDY = {
|
|
32
|
+
kind: 'manual',
|
|
33
|
+
guidance: 'Repair the reference so its target file and #fragment resolve (document-relative path; '
|
|
34
|
+
+ '//, /, and scheme targets are skipped; absolute local paths such as D:/… are reported '
|
|
35
|
+
+ 'as outside the repository), or create/move the target it points to.',
|
|
36
|
+
};
|
|
37
|
+
/** Maximum hint lines appended to an anchor-missing remedy guidance. */
|
|
38
|
+
const MAX_ANCHOR_HINTS = 3;
|
|
39
|
+
/** Longest shared prefix length — the deterministic ranking key for anchor hints. */
|
|
40
|
+
function commonPrefixLength(a, b) {
|
|
41
|
+
let length = 0;
|
|
42
|
+
while (length < a.length && length < b.length && a[length] === b[length])
|
|
43
|
+
length += 1;
|
|
44
|
+
return length;
|
|
45
|
+
}
|
|
46
|
+
/** The percent-decoded `#fragment` of a link target (query stripped); raw on a malformed escape. */
|
|
47
|
+
function fragmentOf(url) {
|
|
48
|
+
const hash = url.indexOf('#');
|
|
49
|
+
if (hash === -1)
|
|
50
|
+
return '';
|
|
51
|
+
const raw = url.slice(hash + 1).replace(/\?.*$/, '');
|
|
52
|
+
try {
|
|
53
|
+
return decodeURIComponent(raw);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return raw;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Deterministic repair hint for one broken anchor: the target's headings whose
|
|
61
|
+
* slug shares the longest prefix with the failed fragment, tie-broken by
|
|
62
|
+
* document order, each shown with its rendered heading text and exact
|
|
63
|
+
* `#anchor`. The model claims the heading it meant and copies the fragment —
|
|
64
|
+
* no slug-rule knowledge required. Headings only: explicit `<a id="…">`
|
|
65
|
+
* anchors are never hinted (they have no heading text to present). Empty when
|
|
66
|
+
* the target is unreadable or nothing shares a prefix.
|
|
67
|
+
*/
|
|
68
|
+
function anchorHints(fragment, targetAbs) {
|
|
69
|
+
if (targetAbs === undefined || !targetAbs.toLowerCase().endsWith('.md'))
|
|
70
|
+
return '';
|
|
71
|
+
let pairs;
|
|
72
|
+
try {
|
|
73
|
+
pairs = documentAnchorPairs(readFileSync(targetAbs, 'utf8'));
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return '';
|
|
77
|
+
}
|
|
78
|
+
const scored = pairs
|
|
79
|
+
.map(pair => ({ pair, score: commonPrefixLength(fragment, pair.anchor) }))
|
|
80
|
+
.filter(candidate => candidate.score > 0)
|
|
81
|
+
.sort((a, b) => b.score - a.score || a.pair.heading.index - b.pair.heading.index)
|
|
82
|
+
.slice(0, MAX_ANCHOR_HINTS);
|
|
83
|
+
if (scored.length === 0)
|
|
84
|
+
return '';
|
|
85
|
+
const lines = scored.map(({ pair }) => `- ${JSON.stringify(pair.heading.text)} → #${pair.anchor}`);
|
|
86
|
+
return ` The #fragment matches no anchor in this document; the heading(s) whose slug shares the longest prefix with it:\n${lines.join('\n')}`;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Build the attribution predicate from a gate change set. `root` is the
|
|
90
|
+
* session workspace cwd, the resolution base for raw `file_path` entries.
|
|
91
|
+
* Canonicalized through md-links `canonicalPath` so membership is exact.
|
|
92
|
+
*/
|
|
93
|
+
function buildAttributionPredicate(root, changes) {
|
|
94
|
+
const written = new Set((changes.paths ?? []).map(path => canonicalPath(path, root)));
|
|
95
|
+
const opaque = changes.opaque === true;
|
|
96
|
+
return (sourceFile, targetAbs) => {
|
|
97
|
+
if (opaque)
|
|
98
|
+
return true;
|
|
99
|
+
if (written.has(sourceFile))
|
|
100
|
+
return true;
|
|
101
|
+
if (targetAbs !== undefined && written.has(targetAbs))
|
|
102
|
+
return true;
|
|
103
|
+
return false;
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function toReportViolation(violation) {
|
|
107
|
+
const reason = `unresolved Markdown reference ${JSON.stringify(violation.url)} (${violation.reason})`;
|
|
108
|
+
const guidance = violation.reason === REASON_ANCHOR_MISSING
|
|
109
|
+
? MANUAL_REMEDY.guidance + anchorHints(fragmentOf(violation.url), violation.targetAbs)
|
|
110
|
+
: MANUAL_REMEDY.guidance;
|
|
111
|
+
return {
|
|
112
|
+
file: violation.file,
|
|
113
|
+
line: violation.line,
|
|
114
|
+
reason,
|
|
115
|
+
remedy: { kind: 'manual', guidance },
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Report face: full scan, then filter to session-attributable violations (the
|
|
120
|
+
* stop-tier consumer semantics). A workspace whose root cannot be discovered
|
|
121
|
+
* through git degrades first: the structured not-applicable outcome returns
|
|
122
|
+
* before any option is parsed or any file is read, so attribution and freeze
|
|
123
|
+
* overlays never run on ground the scan cannot apply to.
|
|
124
|
+
*/
|
|
125
|
+
export function check(root, changes, options) {
|
|
126
|
+
const discovery = discoverRepositoryRoot(root);
|
|
127
|
+
if (!discovery.discovered) {
|
|
128
|
+
return { applicable: false, code: discovery.code, message: discovery.message };
|
|
129
|
+
}
|
|
130
|
+
const frozenDirs = parseFrozenDirs(options?.['frozen-dirs']);
|
|
131
|
+
const frozenTrees = parseFrozenTrees(options?.['frozen-trees']);
|
|
132
|
+
const includeParts = [];
|
|
133
|
+
if (changes !== undefined)
|
|
134
|
+
includeParts.push(buildAttributionPredicate(root, changes));
|
|
135
|
+
if (frozenDirs !== undefined || frozenTrees !== undefined) {
|
|
136
|
+
// Frozen sources are exempt as *sources*: their outbound references rot by
|
|
137
|
+
// design (frozen content is never repaired) and reporting them is
|
|
138
|
+
// unfixable noise. Frozen targets stay in scope — an active document
|
|
139
|
+
// linking into a frozen tree must still resolve.
|
|
140
|
+
const repoRoot = repositoryRoot(root);
|
|
141
|
+
if (frozenDirs !== undefined) {
|
|
142
|
+
const frozen = frozenSourcePredicate(repoRoot, frozenDirs);
|
|
143
|
+
includeParts.push(sourceFile => !frozen(sourceFile));
|
|
144
|
+
}
|
|
145
|
+
if (frozenTrees !== undefined) {
|
|
146
|
+
const frozen = frozenTreePredicate(repoRoot, frozenTrees);
|
|
147
|
+
includeParts.push(sourceFile => !frozen(sourceFile));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const include = includeParts.length === 0
|
|
151
|
+
? undefined
|
|
152
|
+
: (sourceFile, targetAbs) => includeParts.every(predicate => predicate(sourceFile, targetAbs));
|
|
153
|
+
return checkRepository(root, include === undefined ? undefined : { include }).map(toReportViolation);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* The `frozen-dirs` gate option: directory names whose content is frozen
|
|
157
|
+
* (read-only by repo policy, e.g. DOC-style `archived/` trees). Must be a
|
|
158
|
+
* list of strings when present; anything else fails loud (a typo'd policy
|
|
159
|
+
* must not silently widen or narrow the check). Shared with the `md_rename`
|
|
160
|
+
* tool face so a bad shape fails on BOTH faces, never just one.
|
|
161
|
+
*/
|
|
162
|
+
export function parseFrozenDirs(value) {
|
|
163
|
+
if (value === undefined)
|
|
164
|
+
return undefined;
|
|
165
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
|
|
166
|
+
throw new Error('doc-link gate options: frozen-dirs must be a list of directory names');
|
|
167
|
+
}
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Frozen-source predicate for a `frozen-dirs` name set: a file is frozen when
|
|
172
|
+
* any ancestor directory name (repo-root-relative, any depth) hits the
|
|
173
|
+
* declared set — the `{subtree}/archived/{original path}` shape. Shared by
|
|
174
|
+
* the gate (source exemption) and the `md_rename` tool (read-only holders),
|
|
175
|
+
* so both faces keep one freeze semantics.
|
|
176
|
+
*/
|
|
177
|
+
export function frozenSourcePredicate(repoRoot, frozenDirs) {
|
|
178
|
+
const names = new Set(frozenDirs);
|
|
179
|
+
return (absSource) => {
|
|
180
|
+
const segments = absSource.slice(repoRoot.length + 1).split(/[\\/]/);
|
|
181
|
+
segments.pop(); // the file name is never a frozen directory
|
|
182
|
+
return segments.some(segment => names.has(segment));
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The `frozen-trees` gate option: repository-root-relative directory paths
|
|
187
|
+
* (forward slashes) whose content is frozen by a declaration living on the
|
|
188
|
+
* tree itself (the folder-manifest `archived: true` gesture). Must be a list
|
|
189
|
+
* of strings when present; anything else fails loud, exactly like
|
|
190
|
+
* `parseFrozenDirs` — a typo'd policy must not silently widen or narrow the
|
|
191
|
+
* check. The path twin of the name-list gesture: the caller (product face or
|
|
192
|
+
* gate adapter) reads the declarations and passes the tree list; this module
|
|
193
|
+
* never reads manifests.
|
|
194
|
+
*/
|
|
195
|
+
export function parseFrozenTrees(value) {
|
|
196
|
+
if (value === undefined)
|
|
197
|
+
return undefined;
|
|
198
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
|
|
199
|
+
throw new Error('doc-link gate options: frozen-trees must be a list of repository-relative directory paths');
|
|
200
|
+
}
|
|
201
|
+
return value;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Frozen-source predicate for a `frozen-trees` path set: a file is frozen
|
|
205
|
+
* when it sits inside any declared tree (the tree's own root included). Unlike
|
|
206
|
+
* the name-list gesture this freezes exactly the declared trees — a
|
|
207
|
+
* same-named directory elsewhere stays in scope.
|
|
208
|
+
*/
|
|
209
|
+
export function frozenTreePredicate(repoRoot, trees) {
|
|
210
|
+
const treeRoots = trees.map(tree => join(repoRoot, ...tree.split('/')));
|
|
211
|
+
return (absSource) => treeRoots.some(treeRoot => pathInside(treeRoot, absSource));
|
|
212
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @catheadowl/md-tools public face — the data plane (links) and the report
|
|
3
|
+
* face (gate-check) re-exported from one root. Consumers may import this root
|
|
4
|
+
* or the subpath modules directly (`./links/index.js`, `./gate-check.js`).
|
|
5
|
+
* @module @catheadowl/md-tools
|
|
6
|
+
*/
|
|
7
|
+
export * from './links/index.js';
|
|
8
|
+
export * from './gate-check.js';
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @catheadowl/md-tools public face — the data plane (links) and the report
|
|
3
|
+
* face (gate-check) re-exported from one root. Consumers may import this root
|
|
4
|
+
* or the subpath modules directly (`./links/index.js`, `./gate-check.js`).
|
|
5
|
+
* @module @catheadowl/md-tools
|
|
6
|
+
*/
|
|
7
|
+
export * from './links/index.js';
|
|
8
|
+
export * from './gate-check.js';
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Heading anchors for Markdown documents: GitHub-compatible heading slug
|
|
3
|
+
* generation, per-document anchor collection (heading slugs plus explicit
|
|
4
|
+
* `<a id>` targets, repeated slugs bump-suffixed), and a shared anchor
|
|
5
|
+
* cache so a target document parses once per scan.
|
|
6
|
+
*/
|
|
7
|
+
import { type MarkdownHeadingLine } from './markdown.js';
|
|
8
|
+
/**
|
|
9
|
+
* GitHub's heading-slug algorithm (lowercase; drop everything but letters,
|
|
10
|
+
* numbers, underscores, spaces, hyphens; spaces become hyphens).
|
|
11
|
+
* @param heading - the RENDERED heading text (Markdown syntax already gone).
|
|
12
|
+
* @returns the anchor GitHub assigns the first occurrence of the heading.
|
|
13
|
+
*/
|
|
14
|
+
export declare function githubSlug(heading: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* Every anchor one Markdown document exposes: each heading's GitHub slug plus
|
|
17
|
+
* every explicit `<a id="…">` in real HTML flow. Repeated slugs get GitHub's
|
|
18
|
+
* occupied-set `-1`, `-2`, … suffixes. Matching is exact — ids are case-sensitive.
|
|
19
|
+
* @param source - the document's full Markdown text.
|
|
20
|
+
* @returns the set of valid fragments for links into this document.
|
|
21
|
+
*/
|
|
22
|
+
export declare function documentAnchors(source: string): Set<string>;
|
|
23
|
+
/** One heading and the exact fragment it exposes (bump-suffixed when repeated). */
|
|
24
|
+
export interface DocumentAnchorPair {
|
|
25
|
+
heading: MarkdownHeadingLine;
|
|
26
|
+
anchor: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Self-written extension on top of the base primitives:
|
|
30
|
+
* every heading paired with the exact anchor it exposes, in document order,
|
|
31
|
+
* using the same occupied-set bumping as `documentAnchors`. Headings only —
|
|
32
|
+
* explicit `<a id="…">` anchors are exposed by `documentAnchors` but have no
|
|
33
|
+
* heading text to pair, so hint consumers must treat them as unpairable.
|
|
34
|
+
* @param source - the document's full Markdown text.
|
|
35
|
+
* @returns heading → anchor pairs, one per heading, document-ordered.
|
|
36
|
+
*/
|
|
37
|
+
export declare function documentAnchorPairs(source: string): DocumentAnchorPair[];
|
|
38
|
+
/**
|
|
39
|
+
* Lazily collect and cache the anchor set of any existing Markdown file —
|
|
40
|
+
* shared across all scanned sources so a target parses once.
|
|
41
|
+
* @returns the memoized absolute-path → anchor-set lookup.
|
|
42
|
+
*/
|
|
43
|
+
export declare function anchorCache(): (absPath: string) => Set<string>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Heading anchors for Markdown documents: GitHub-compatible heading slug
|
|
3
|
+
* generation, per-document anchor collection (heading slugs plus explicit
|
|
4
|
+
* `<a id>` targets, repeated slugs bump-suffixed), and a shared anchor
|
|
5
|
+
* cache so a target document parses once per scan.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { markdownHeadingLines, parseMarkdown, visitMarkdown } from './markdown.js';
|
|
9
|
+
/**
|
|
10
|
+
* GitHub's heading-slug algorithm (lowercase; drop everything but letters,
|
|
11
|
+
* numbers, underscores, spaces, hyphens; spaces become hyphens).
|
|
12
|
+
* @param heading - the RENDERED heading text (Markdown syntax already gone).
|
|
13
|
+
* @returns the anchor GitHub assigns the first occurrence of the heading.
|
|
14
|
+
*/
|
|
15
|
+
export function githubSlug(heading) {
|
|
16
|
+
return heading.toLowerCase().replace(/[^\p{L}\p{N}_ -]/gu, '').replaceAll(' ', '-');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Every anchor one Markdown document exposes: each heading's GitHub slug plus
|
|
20
|
+
* every explicit `<a id="…">` in real HTML flow. Repeated slugs get GitHub's
|
|
21
|
+
* occupied-set `-1`, `-2`, … suffixes. Matching is exact — ids are case-sensitive.
|
|
22
|
+
* @param source - the document's full Markdown text.
|
|
23
|
+
* @returns the set of valid fragments for links into this document.
|
|
24
|
+
*/
|
|
25
|
+
export function documentAnchors(source) {
|
|
26
|
+
const anchors = new Set();
|
|
27
|
+
const occurrences = new Map();
|
|
28
|
+
for (const heading of markdownHeadingLines(source)) {
|
|
29
|
+
const base = githubSlug(heading.text);
|
|
30
|
+
let result = base;
|
|
31
|
+
let bump = occurrences.get(base) ?? 0;
|
|
32
|
+
while (anchors.has(result)) {
|
|
33
|
+
bump += 1;
|
|
34
|
+
result = `${base}-${bump}`;
|
|
35
|
+
}
|
|
36
|
+
occurrences.set(base, bump);
|
|
37
|
+
anchors.add(result);
|
|
38
|
+
}
|
|
39
|
+
visitMarkdown(parseMarkdown(source), (node) => {
|
|
40
|
+
if (node.type !== 'html')
|
|
41
|
+
return;
|
|
42
|
+
const html = node.value.replace(/<!--[\s\S]*?-->/g, '');
|
|
43
|
+
for (const match of html.matchAll(/<a id="([^"]+)"/g))
|
|
44
|
+
anchors.add(match[1] ?? '');
|
|
45
|
+
});
|
|
46
|
+
return anchors;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Self-written extension on top of the base primitives:
|
|
50
|
+
* every heading paired with the exact anchor it exposes, in document order,
|
|
51
|
+
* using the same occupied-set bumping as `documentAnchors`. Headings only —
|
|
52
|
+
* explicit `<a id="…">` anchors are exposed by `documentAnchors` but have no
|
|
53
|
+
* heading text to pair, so hint consumers must treat them as unpairable.
|
|
54
|
+
* @param source - the document's full Markdown text.
|
|
55
|
+
* @returns heading → anchor pairs, one per heading, document-ordered.
|
|
56
|
+
*/
|
|
57
|
+
export function documentAnchorPairs(source) {
|
|
58
|
+
const pairs = [];
|
|
59
|
+
const anchors = new Set();
|
|
60
|
+
const occurrences = new Map();
|
|
61
|
+
for (const heading of markdownHeadingLines(source)) {
|
|
62
|
+
const base = githubSlug(heading.text);
|
|
63
|
+
let result = base;
|
|
64
|
+
let bump = occurrences.get(base) ?? 0;
|
|
65
|
+
while (anchors.has(result)) {
|
|
66
|
+
bump += 1;
|
|
67
|
+
result = `${base}-${bump}`;
|
|
68
|
+
}
|
|
69
|
+
occurrences.set(base, bump);
|
|
70
|
+
anchors.add(result);
|
|
71
|
+
pairs.push({ heading, anchor: result });
|
|
72
|
+
}
|
|
73
|
+
return pairs;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Lazily collect and cache the anchor set of any existing Markdown file —
|
|
77
|
+
* shared across all scanned sources so a target parses once.
|
|
78
|
+
* @returns the memoized absolute-path → anchor-set lookup.
|
|
79
|
+
*/
|
|
80
|
+
export function anchorCache() {
|
|
81
|
+
const cache = new Map();
|
|
82
|
+
return (absPath) => {
|
|
83
|
+
const hit = cache.get(absPath);
|
|
84
|
+
if (hit)
|
|
85
|
+
return hit;
|
|
86
|
+
const anchors = documentAnchors(readFileSync(absPath, 'utf8'));
|
|
87
|
+
cache.set(absPath, anchors);
|
|
88
|
+
return anchors;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/*
|
|
92
|
+
* Fork duty details live in the development-face fork duty record.
|
|
93
|
+
*/
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throwing single-spawn capture of stdout. Non-zero exits throw (the error
|
|
3
|
+
* carries `status`); spawn-level failures throw as-is. Callers whose non-zero
|
|
4
|
+
* exits are answers, not failures, use `captureCliExit`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function captureCliStdout(command: string, args: readonly string[], tempName: string): string;
|
|
7
|
+
/**
|
|
8
|
+
* Non-throwing twin for probes whose non-zero exits are answers, not
|
|
9
|
+
* failures: captures stdout AND stderr through temp files (pipe capture is
|
|
10
|
+
* EPERM under sandboxed hosts) and returns the exit status instead of
|
|
11
|
+
* throwing, so callers can classify the CLI's own refusal text. Spawn-level
|
|
12
|
+
* errors that never produced a subprocess (binary missing, sandbox refusal)
|
|
13
|
+
* still throw — they carry no exit status to return — and callers that treat
|
|
14
|
+
* an absent binary as a degrade shape catch that throw at their boundary.
|
|
15
|
+
*/
|
|
16
|
+
export declare function captureCliExit(command: string, args: readonly string[], tempName: string): {
|
|
17
|
+
status: number | null;
|
|
18
|
+
stdout: string;
|
|
19
|
+
stderr: string;
|
|
20
|
+
};
|
package/lib/links/cli.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI capture (generalized from the git seam's temp-file spawn primitives —
|
|
3
|
+
* the same law, now shared by every seam that runs a one-shot subprocess:
|
|
4
|
+
* stdout/stderr capture goes through temp files, never pipes, because pipe
|
|
5
|
+
* capture is EPERM under sandboxed hosts that forbid named pipes; a temp file
|
|
6
|
+
* is equally valid for a one-shot synchronous read. Pure node — no host deps,
|
|
7
|
+
* so it stays node:test-able. Seams consume this instead of growing their own
|
|
8
|
+
* spawn shapes: one capture discipline, no per-seam drift.
|
|
9
|
+
*/
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from 'node:fs';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
/**
|
|
15
|
+
* Throwing single-spawn capture of stdout. Non-zero exits throw (the error
|
|
16
|
+
* carries `status`); spawn-level failures throw as-is. Callers whose non-zero
|
|
17
|
+
* exits are answers, not failures, use `captureCliExit`.
|
|
18
|
+
*/
|
|
19
|
+
export function captureCliStdout(command, args, tempName) {
|
|
20
|
+
const dir = mkdtempSync(join(tmpdir(), 'doc-core-cli-'));
|
|
21
|
+
const outFile = join(dir, tempName);
|
|
22
|
+
try {
|
|
23
|
+
const fd = openSync(outFile, 'w');
|
|
24
|
+
try {
|
|
25
|
+
execFileSync(command, args, { stdio: ['ignore', fd, 'ignore'] });
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
closeSync(fd);
|
|
29
|
+
}
|
|
30
|
+
return readFileSync(outFile, 'utf8');
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
rmSync(dir, { recursive: true, force: true });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Non-throwing twin for probes whose non-zero exits are answers, not
|
|
38
|
+
* failures: captures stdout AND stderr through temp files (pipe capture is
|
|
39
|
+
* EPERM under sandboxed hosts) and returns the exit status instead of
|
|
40
|
+
* throwing, so callers can classify the CLI's own refusal text. Spawn-level
|
|
41
|
+
* errors that never produced a subprocess (binary missing, sandbox refusal)
|
|
42
|
+
* still throw — they carry no exit status to return — and callers that treat
|
|
43
|
+
* an absent binary as a degrade shape catch that throw at their boundary.
|
|
44
|
+
*/
|
|
45
|
+
export function captureCliExit(command, args, tempName) {
|
|
46
|
+
const dir = mkdtempSync(join(tmpdir(), 'doc-core-cli-'));
|
|
47
|
+
const outFile = join(dir, tempName);
|
|
48
|
+
const errFile = join(dir, `${tempName}-err`);
|
|
49
|
+
try {
|
|
50
|
+
const outFd = openSync(outFile, 'w');
|
|
51
|
+
const errFd = openSync(errFile, 'w');
|
|
52
|
+
try {
|
|
53
|
+
try {
|
|
54
|
+
execFileSync(command, args, { stdio: ['ignore', outFd, errFd] });
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
const status = error.status;
|
|
58
|
+
if (typeof status !== 'number')
|
|
59
|
+
throw error;
|
|
60
|
+
return { status, stdout: readFileSync(outFile, 'utf8'), stderr: readFileSync(errFile, 'utf8') };
|
|
61
|
+
}
|
|
62
|
+
return { status: 0, stdout: readFileSync(outFile, 'utf8'), stderr: '' };
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
closeSync(outFd);
|
|
66
|
+
closeSync(errFd);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
rmSync(dir, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/** Injectable git-list delegate: `(root) -> repository-relative file paths`. */
|
|
2
|
+
export type GitLsFiles = (root: string) => string[];
|
|
3
|
+
/**
|
|
4
|
+
* Single safe-spawn primitive, git-flavored: prepends `-C root` to every
|
|
5
|
+
* invocation and delegates to the shared CLI capture (`cli.ts`). Exported so
|
|
6
|
+
* the rename kernel (git grep / git mv) and any future consumer share one
|
|
7
|
+
* source — never hand-roll another spawn in per-item loops.
|
|
8
|
+
*/
|
|
9
|
+
export declare function captureGitStdout(root: string, args: readonly string[], tempName: string): string;
|
|
10
|
+
/**
|
|
11
|
+
* Why repository-root discovery produced no root. Stable codes are the
|
|
12
|
+
* branching key consumers program against; `message` is face-neutral wording
|
|
13
|
+
* each delivery face may reword (never parse).
|
|
14
|
+
*/
|
|
15
|
+
export type RepositoryUnavailableCode = 'not-a-git-repository' | 'git-unavailable';
|
|
16
|
+
/**
|
|
17
|
+
* Structured outcome of worktree-root discovery: either the absolute
|
|
18
|
+
* top-level, or a classified reason why there is none. A workspace outside
|
|
19
|
+
* any git repository is a first-class answer here — the scan's file set is
|
|
20
|
+
* discovered through git, so where git sees no worktree the check does not
|
|
21
|
+
* apply, and callers that would otherwise wrap a thrown error as a violation
|
|
22
|
+
* can degrade on this shape instead.
|
|
23
|
+
*/
|
|
24
|
+
export type RepositoryRootDiscovery = {
|
|
25
|
+
discovered: true;
|
|
26
|
+
topLevel: string;
|
|
27
|
+
} | {
|
|
28
|
+
discovered: false;
|
|
29
|
+
code: RepositoryUnavailableCode;
|
|
30
|
+
message: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Discover the worktree root for a session cwd or any path inside the
|
|
34
|
+
* worktree, as a structured outcome — `undefined`-free, exception-free for
|
|
35
|
+
* the two shapes a session routinely hits (no worktree, no git binary);
|
|
36
|
+
* anything else (unreadable path, exotic git failure) still throws. Memoized
|
|
37
|
+
* per resolved path like `gitTopLevel`, and a memoized failure answers repeat
|
|
38
|
+
* calls without re-spawning git — a consumer re-checking in the same session
|
|
39
|
+
* gets the same verdict at zero cost.
|
|
40
|
+
*/
|
|
41
|
+
export declare function discoverRepositoryRoot(root: string): RepositoryRootDiscovery;
|
|
42
|
+
/** `gitTopLevel` failed — carries the classified code so callers branch without string matching. */
|
|
43
|
+
export declare class RepositoryRootError extends Error {
|
|
44
|
+
/** Which discovery failure this was (`not-a-git-repository` / `git-unavailable`). */
|
|
45
|
+
readonly code: RepositoryUnavailableCode;
|
|
46
|
+
constructor(code: RepositoryUnavailableCode, message: string);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Absolute git worktree root for a session cwd or any path inside the worktree,
|
|
50
|
+
* throwing `RepositoryRootError` when discovery is answered structurally
|
|
51
|
+
* (no worktree / no git binary) — callers that prefer the non-throwing shape
|
|
52
|
+
* use `discoverRepositoryRoot`. Memoized per resolved path: `rev-parse
|
|
53
|
+
* --show-toplevel` spawns a fresh `git` subprocess (~60–250ms on Windows), and
|
|
54
|
+
* the gate scan calls this once per missing reference through `gitLinkPaths`
|
|
55
|
+
* (see `temporarilyUnverifiable`). Without the cache that turns dozens of dead
|
|
56
|
+
* wikilinks into seconds of redundant subprocess spawns. The worktree root
|
|
57
|
+
* never moves within a session, so caching is safe; a different input path
|
|
58
|
+
* (another repo) gets its own key. Success feeds the shared discovery memo;
|
|
59
|
+
* failure reads from it without re-spawning.
|
|
60
|
+
*/
|
|
61
|
+
export declare function gitTopLevel(root: string): string;
|
|
62
|
+
/** Absolute paths recorded as gitlinks (mode 160000) in the current worktree. */
|
|
63
|
+
export declare function gitLinkPaths(root: string): Set<string>;
|
|
64
|
+
/**
|
|
65
|
+
* Tracked files plus untracked-not-ignored files (`--cached --others
|
|
66
|
+
* --exclude-standard`), NUL-separated so any filename survives. The command
|
|
67
|
+
* first canonicalizes `root` to git's toplevel so paths are always repository
|
|
68
|
+
* root-relative, even when invoked from a subdirectory.
|
|
69
|
+
*/
|
|
70
|
+
export declare function gitLsFiles(root: string): string[];
|
|
71
|
+
/**
|
|
72
|
+
* Tracked Markdown files whose content contains the fixed string `pattern`
|
|
73
|
+
* (candidate localization for rename in-links: 1 spawn, then per-candidate
|
|
74
|
+
* resolution filters to real targets). Fixed-string (`-F`) so a basename with
|
|
75
|
+
* `.`/`-`/`(` never acts as a regex. Absolute paths, sorted.
|
|
76
|
+
*/
|
|
77
|
+
export declare function gitGrep(root: string, pattern: string): string[];
|
|
78
|
+
/** One `git status --porcelain -z` record. */
|
|
79
|
+
export interface GitStatusRecord {
|
|
80
|
+
/** Two-character porcelain XY (e.g. `'R '` staged rename, `' D'` unstaged delete, `'??'` untracked). */
|
|
81
|
+
xy: string;
|
|
82
|
+
/** Repo-root-relative current path (a rename record's NEW side). */
|
|
83
|
+
path: string;
|
|
84
|
+
/** Repo-root-relative original path — present on rename/copy records only (the rename's OLD side). */
|
|
85
|
+
origPath?: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Worktree state as `git status --porcelain -z` records (1 spawn). Renames and
|
|
89
|
+
* copies carry their original path as the next NUL-separated entry. This is
|
|
90
|
+
* the post-hoc repair evidence data plane: git witnessing that an old path was
|
|
91
|
+
* tracked and is now gone (`R old→new` staged, or `D old` in either column).
|
|
92
|
+
*/
|
|
93
|
+
export declare function gitStatusPorcelain(root: string): GitStatusRecord[];
|
|
94
|
+
/**
|
|
95
|
+
* Whether `<revision>:<repoRelativePath>` resolves in that tree — the post-hoc
|
|
96
|
+
* HEAD-tier evidence (D1 ②): old is recorded in HEAD while absent from the
|
|
97
|
+
* worktree, i.e. the worktree status cannot witness the move (e.g. a
|
|
98
|
+
* skip-worktree-hidden deletion). One spawn, no stdout; a non-zero exit (also
|
|
99
|
+
* `fatal: invalid object name` in a commit-less repo) simply means "no record".
|
|
100
|
+
*/
|
|
101
|
+
export declare function gitTreeHas(root: string, revision: string, repoRelativePath: string): boolean;
|
|
102
|
+
/**
|
|
103
|
+
* Tracked (index) files at or under the given repo-root-relative paths, one
|
|
104
|
+
* spawn for the whole list — the rename plan's source-tracking probe: `git mv`
|
|
105
|
+
* refuses a source with nothing tracked at/under it ('not under version
|
|
106
|
+
* control' / 'source directory is empty'), so an empty match for a pair's old
|
|
107
|
+
* path means the move cannot stage. Pathspecs are literal (`:(literal)`), so a
|
|
108
|
+
* filename carrying glob characters is probed as itself, never as a pattern.
|
|
109
|
+
*/
|
|
110
|
+
export declare function gitTrackedUnder(root: string, repoRelativePaths: readonly string[]): string[];
|
|
111
|
+
/** One rename record from history: the commit plus both repo-root-relative sides. */
|
|
112
|
+
export interface GitRenameRecord {
|
|
113
|
+
/** Commit that performed the rename (full hash). */
|
|
114
|
+
commit: string;
|
|
115
|
+
/** Repo-root-relative pre-image path (the rename's old side). */
|
|
116
|
+
oldPath: string;
|
|
117
|
+
/** Repo-root-relative post-image path (the rename's new side). */
|
|
118
|
+
newPath: string;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Rename records from history (`git log -M --diff-filter=R --name-status -z`,
|
|
122
|
+
* one spawn, newest first). Pathspec ground truth: an R record surfaces only
|
|
123
|
+
* when BOTH of its sides fall under the pathspec — a single-side pathspec
|
|
124
|
+
* never matches an R entry (probed: `-M --diff-filter=R -- <old>` alone stays
|
|
125
|
+
* empty even for a twice-renamed path) — so pair queries pass both sides.
|
|
126
|
+
* Output shape per record: `<commit>\0\nR100\0<newPath>\0<oldPath>\0`.
|
|
127
|
+
* `limit` caps the commit walk (history defense); ambiguity beyond the cap is
|
|
128
|
+
* a cost bound, not a verdict — callers list what is found, never adjudicate.
|
|
129
|
+
*/
|
|
130
|
+
export declare function gitLogRenameRecords(root: string, repoRelativePaths: readonly string[], limit?: number): GitRenameRecord[];
|
|
131
|
+
/**
|
|
132
|
+
* The newest commit that touched the repo-root-relative path, or `undefined`
|
|
133
|
+
* when the path has no history at all (one spawn: `git log --format=%H -n 1`).
|
|
134
|
+
* The never-existed probe: an old path with no history was never tracked —
|
|
135
|
+
* the strongest typo signal the informational refusal payload can carry.
|
|
136
|
+
*/
|
|
137
|
+
export declare function gitLogLastTouched(root: string, repoRelativePath: string): string | undefined;
|
|
138
|
+
/** `git mv` exited non-zero — carries git's own stderr so callers relay it instead of a raw spawn error. */
|
|
139
|
+
export declare class GitMoveError extends Error {
|
|
140
|
+
/** Repo-root-relative source of the failed move. */
|
|
141
|
+
readonly from: string;
|
|
142
|
+
/** Repo-root-relative destination of the failed move. */
|
|
143
|
+
readonly to: string;
|
|
144
|
+
/** git's stderr, trimmed (e.g. `fatal: not under version control, source=…`). */
|
|
145
|
+
readonly stderr: string;
|
|
146
|
+
constructor(from: string, to: string, stderr: string);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Move one tracked path (file or directory) with `git mv`, staging the rename
|
|
150
|
+
* so git remains the state (no runtime). `fromRepoRelative`/`toRepoRelative`
|
|
151
|
+
* are repo-root-relative. On a failed move (non-zero git exit — e.g.
|
|
152
|
+
* destination parent missing, path not under version control — or git never
|
|
153
|
+
* launching) throws `GitMoveError` with the captured stderr, never a raw
|
|
154
|
+
* spawn error.
|
|
155
|
+
*/
|
|
156
|
+
export declare function gitMove(root: string, fromRepoRelative: string, toRepoRelative: string): void;
|