@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
@@ -0,0 +1,233 @@
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, REASON_OUTSIDE_REPOSITORY, REASON_TARGET_MISSING, canonicalPath, checkRepository, discoverRepositoryRoot, documentAnchorPairs, pathInside, repositoryRoot } from './links/index.js';
31
+ const TARGET_MISSING_REMEDY = {
32
+ kind: 'manual',
33
+ guidance: 'Update the reference to an existing target, or add/move the intended target into the repository.',
34
+ };
35
+ const ANCHOR_MISSING_REMEDY = {
36
+ kind: 'manual',
37
+ guidance: 'Update the #fragment to match a heading or explicit anchor in the target document.',
38
+ };
39
+ const OUTSIDE_REPOSITORY_REMEDY = {
40
+ kind: 'manual',
41
+ guidance: 'Confirm this outside-repository reference is intentional; doc-link cannot verify its target as part of this repository.',
42
+ };
43
+ /** Maximum hint lines appended to an anchor-missing remedy guidance. */
44
+ const MAX_ANCHOR_HINTS = 3;
45
+ /** Longest shared prefix length — the deterministic ranking key for anchor hints. */
46
+ function commonPrefixLength(a, b) {
47
+ let length = 0;
48
+ while (length < a.length && length < b.length && a[length] === b[length])
49
+ length += 1;
50
+ return length;
51
+ }
52
+ /** The percent-decoded `#fragment` of a link target (query stripped); raw on a malformed escape. */
53
+ function fragmentOf(url) {
54
+ const hash = url.indexOf('#');
55
+ if (hash === -1)
56
+ return '';
57
+ const raw = url.slice(hash + 1).replace(/\?.*$/, '');
58
+ try {
59
+ return decodeURIComponent(raw);
60
+ }
61
+ catch {
62
+ return raw;
63
+ }
64
+ }
65
+ /**
66
+ * Deterministic repair hint for one broken anchor: the target's headings whose
67
+ * slug shares the longest prefix with the failed fragment, tie-broken by
68
+ * document order, each shown with its rendered heading text and exact
69
+ * `#anchor`. The model claims the heading it meant and copies the fragment —
70
+ * no slug-rule knowledge required. Headings only: explicit `<a id="…">`
71
+ * anchors are never hinted (they have no heading text to present). Empty when
72
+ * the target is unreadable or nothing shares a prefix.
73
+ */
74
+ function anchorHints(fragment, targetAbs) {
75
+ if (targetAbs === undefined || !targetAbs.toLowerCase().endsWith('.md'))
76
+ return '';
77
+ let pairs;
78
+ try {
79
+ pairs = documentAnchorPairs(readFileSync(targetAbs, 'utf8'));
80
+ }
81
+ catch {
82
+ return '';
83
+ }
84
+ const scored = pairs
85
+ .map(pair => ({ pair, score: commonPrefixLength(fragment, pair.anchor) }))
86
+ .filter(candidate => candidate.score > 0)
87
+ .sort((a, b) => b.score - a.score || a.pair.heading.index - b.pair.heading.index)
88
+ .slice(0, MAX_ANCHOR_HINTS);
89
+ if (scored.length === 0)
90
+ return '';
91
+ const lines = scored.map(({ pair }) => `- ${JSON.stringify(pair.heading.text)} → #${pair.anchor}`);
92
+ return ` The #fragment matches no anchor in this document; the heading(s) whose slug shares the longest prefix with it:\n${lines.join('\n')}`;
93
+ }
94
+ /**
95
+ * Build the attribution predicate from a gate change set. `root` is the
96
+ * session workspace cwd, the resolution base for raw `file_path` entries.
97
+ * Canonicalized through md-links `canonicalPath` so membership is exact.
98
+ */
99
+ function buildAttributionPredicate(root, changes) {
100
+ const written = new Set((changes.paths ?? []).map(path => canonicalPath(path, root)));
101
+ const opaque = changes.opaque === true;
102
+ return (sourceFile, targetAbs) => {
103
+ if (opaque)
104
+ return true;
105
+ if (written.has(sourceFile))
106
+ return true;
107
+ if (targetAbs !== undefined && written.has(targetAbs))
108
+ return true;
109
+ return false;
110
+ };
111
+ }
112
+ function toReportViolation(violation) {
113
+ const reason = `unresolved Markdown reference ${JSON.stringify(violation.url)} (${violation.reason})`;
114
+ let violationClass;
115
+ let guidance;
116
+ if (violation.reason === REASON_ANCHOR_MISSING) {
117
+ violationClass = 'anchor-missing';
118
+ guidance = ANCHOR_MISSING_REMEDY.guidance + anchorHints(fragmentOf(violation.url), violation.targetAbs);
119
+ }
120
+ else if (violation.reason === REASON_TARGET_MISSING) {
121
+ violationClass = 'target-missing';
122
+ guidance = TARGET_MISSING_REMEDY.guidance;
123
+ }
124
+ else if (violation.reason === REASON_OUTSIDE_REPOSITORY) {
125
+ violationClass = 'outside-repository';
126
+ guidance = OUTSIDE_REPOSITORY_REMEDY.guidance;
127
+ }
128
+ else {
129
+ throw new Error(`doc-link report: unclassified violation reason ${JSON.stringify(violation.reason)}`);
130
+ }
131
+ return {
132
+ class: violationClass,
133
+ file: violation.file,
134
+ line: violation.line,
135
+ reason,
136
+ remedy: { kind: 'manual', guidance },
137
+ };
138
+ }
139
+ /**
140
+ * Report face: full scan, then filter to session-attributable violations (the
141
+ * stop-tier consumer semantics). A workspace whose root cannot be discovered
142
+ * through git degrades first: the structured not-applicable outcome returns
143
+ * before any option is parsed or any file is read, so attribution and freeze
144
+ * overlays never run on ground the scan cannot apply to.
145
+ */
146
+ export function check(root, changes, options) {
147
+ const discovery = discoverRepositoryRoot(root);
148
+ if (!discovery.discovered) {
149
+ return { applicable: false, code: discovery.code, message: discovery.message };
150
+ }
151
+ const frozenDirs = parseFrozenDirs(options?.['frozen-dirs']);
152
+ const frozenTrees = parseFrozenTrees(options?.['frozen-trees']);
153
+ const includeParts = [];
154
+ if (changes !== undefined)
155
+ includeParts.push(buildAttributionPredicate(root, changes));
156
+ if (frozenDirs !== undefined || frozenTrees !== undefined) {
157
+ // Frozen sources are exempt as *sources*: their outbound references rot by
158
+ // design (frozen content is never repaired) and reporting them is
159
+ // unfixable noise. Frozen targets stay in scope — an active document
160
+ // linking into a frozen tree must still resolve.
161
+ const repoRoot = repositoryRoot(root);
162
+ if (frozenDirs !== undefined) {
163
+ const frozen = frozenSourcePredicate(repoRoot, frozenDirs);
164
+ includeParts.push(sourceFile => !frozen(sourceFile));
165
+ }
166
+ if (frozenTrees !== undefined) {
167
+ const frozen = frozenTreePredicate(repoRoot, frozenTrees);
168
+ includeParts.push(sourceFile => !frozen(sourceFile));
169
+ }
170
+ }
171
+ const include = includeParts.length === 0
172
+ ? undefined
173
+ : (sourceFile, targetAbs) => includeParts.every(predicate => predicate(sourceFile, targetAbs));
174
+ return checkRepository(root, include === undefined ? undefined : { include }).map(toReportViolation);
175
+ }
176
+ /**
177
+ * The `frozen-dirs` gate option: directory names whose content is frozen
178
+ * (read-only by repo policy, e.g. DOC-style `archived/` trees). Must be a
179
+ * list of strings when present; anything else fails loud (a typo'd policy
180
+ * must not silently widen or narrow the check). Shared with the `md_rename`
181
+ * tool face so a bad shape fails on BOTH faces, never just one.
182
+ */
183
+ export function parseFrozenDirs(value) {
184
+ if (value === undefined)
185
+ return undefined;
186
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
187
+ throw new Error('doc-link gate options: frozen-dirs must be a list of directory names');
188
+ }
189
+ return value;
190
+ }
191
+ /**
192
+ * Frozen-source predicate for a `frozen-dirs` name set: a file is frozen when
193
+ * any ancestor directory name (repo-root-relative, any depth) hits the
194
+ * declared set — the `{subtree}/archived/{original path}` shape. Shared by
195
+ * the gate (source exemption) and the `md_rename` tool (read-only holders),
196
+ * so both faces keep one freeze semantics.
197
+ */
198
+ export function frozenSourcePredicate(repoRoot, frozenDirs) {
199
+ const names = new Set(frozenDirs);
200
+ return (absSource) => {
201
+ const segments = absSource.slice(repoRoot.length + 1).split(/[\\/]/);
202
+ segments.pop(); // the file name is never a frozen directory
203
+ return segments.some(segment => names.has(segment));
204
+ };
205
+ }
206
+ /**
207
+ * The `frozen-trees` gate option: repository-root-relative directory paths
208
+ * (forward slashes) whose content is frozen by a declaration living on the
209
+ * tree itself (the folder-manifest `archived: true` gesture). Must be a list
210
+ * of strings when present; anything else fails loud, exactly like
211
+ * `parseFrozenDirs` — a typo'd policy must not silently widen or narrow the
212
+ * check. The path twin of the name-list gesture: the caller (product face or
213
+ * gate adapter) reads the declarations and passes the tree list; this module
214
+ * never reads manifests.
215
+ */
216
+ export function parseFrozenTrees(value) {
217
+ if (value === undefined)
218
+ return undefined;
219
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
220
+ throw new Error('doc-link gate options: frozen-trees must be a list of repository-relative directory paths');
221
+ }
222
+ return value;
223
+ }
224
+ /**
225
+ * Frozen-source predicate for a `frozen-trees` path set: a file is frozen
226
+ * when it sits inside any declared tree (the tree's own root included). Unlike
227
+ * the name-list gesture this freezes exactly the declared trees — a
228
+ * same-named directory elsewhere stays in scope.
229
+ */
230
+ export function frozenTreePredicate(repoRoot, trees) {
231
+ const treeRoots = trees.map(tree => join(repoRoot, ...tree.split('/')));
232
+ return (absSource) => treeRoots.some(treeRoot => pathInside(treeRoot, absSource));
233
+ }
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,33 @@
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
+ * `options.win32Shell` launches through the platform shell on win32. CLIs
17
+ * that arrive as script shims — npm bin entries are `name`/`name.cmd`/
18
+ * `name.ps1` wrappers, never .exe — cannot be launched by a direct spawn:
19
+ * CreateProcess has no executable to run and spawn ENOENTs even though the
20
+ * CLI is installed and healthy. Opt in ONLY for fixed literal args: under
21
+ * the shell the args array is joined into one command line that cmd
22
+ * re-parses, so variable args (paths, revs — the git seam's shape) must stay
23
+ * on the default direct spawn. Inert off win32. Side effect of the opt-in:
24
+ * a missing CLI answers as a non-zero exit (cmd's not-found code) instead of
25
+ * a spawn throw — for probes both land in the same degrade classification.
26
+ */
27
+ export declare function captureCliExit(command: string, args: readonly string[], tempName: string, options?: {
28
+ win32Shell?: boolean;
29
+ }): {
30
+ status: number | null;
31
+ stdout: string;
32
+ stderr: string;
33
+ };
@@ -0,0 +1,86 @@
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
+ * `options.win32Shell` launches through the platform shell on win32. CLIs
46
+ * that arrive as script shims — npm bin entries are `name`/`name.cmd`/
47
+ * `name.ps1` wrappers, never .exe — cannot be launched by a direct spawn:
48
+ * CreateProcess has no executable to run and spawn ENOENTs even though the
49
+ * CLI is installed and healthy. Opt in ONLY for fixed literal args: under
50
+ * the shell the args array is joined into one command line that cmd
51
+ * re-parses, so variable args (paths, revs — the git seam's shape) must stay
52
+ * on the default direct spawn. Inert off win32. Side effect of the opt-in:
53
+ * a missing CLI answers as a non-zero exit (cmd's not-found code) instead of
54
+ * a spawn throw — for probes both land in the same degrade classification.
55
+ */
56
+ export function captureCliExit(command, args, tempName, options = {}) {
57
+ const dir = mkdtempSync(join(tmpdir(), 'doc-core-cli-'));
58
+ const outFile = join(dir, tempName);
59
+ const errFile = join(dir, `${tempName}-err`);
60
+ try {
61
+ const outFd = openSync(outFile, 'w');
62
+ const errFd = openSync(errFile, 'w');
63
+ try {
64
+ try {
65
+ execFileSync(command, args, {
66
+ stdio: ['ignore', outFd, errFd],
67
+ ...(options.win32Shell && process.platform === 'win32' ? { shell: true } : {}),
68
+ });
69
+ }
70
+ catch (error) {
71
+ const status = error.status;
72
+ if (typeof status !== 'number')
73
+ throw error;
74
+ return { status, stdout: readFileSync(outFile, 'utf8'), stderr: readFileSync(errFile, 'utf8') };
75
+ }
76
+ return { status: 0, stdout: readFileSync(outFile, 'utf8'), stderr: '' };
77
+ }
78
+ finally {
79
+ closeSync(outFd);
80
+ closeSync(errFd);
81
+ }
82
+ }
83
+ finally {
84
+ rmSync(dir, { recursive: true, force: true });
85
+ }
86
+ }
@@ -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;