@venizia/vulcan 0.4.5 → 0.4.7

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 (54) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +13 -0
  3. package/base/checks/wiki-anchors.ts +8 -0
  4. package/base/checks/wiki-source-links.ts +8 -0
  5. package/base/hooks/guard-git.ts +9 -2
  6. package/base/hooks/guard-writes.ts +4 -0
  7. package/base/hooks/session-start.ts +14 -4
  8. package/base/make/vulcan.mk +12 -1
  9. package/base/references/delegation-brief.md +5 -4
  10. package/base/rules.md +2 -2
  11. package/base/skills/docs-writing/SKILL.md +1 -1
  12. package/base/skills/docs-writing/references/agent-documents.md +1 -1
  13. package/base/skills/knowledge-sync/SKILL.md +1 -1
  14. package/base/skills/plan-a-change/SKILL.md +2 -2
  15. package/base/skills/plan-a-change/evals/evals.json +6 -0
  16. package/base/skills/plan-a-change/references/spec-card.md +1 -0
  17. package/base/skills/report-back/SKILL.md +1 -1
  18. package/base/skills/retro/SKILL.md +1 -1
  19. package/base/skills/review-a-change/SKILL.md +1 -1
  20. package/base/skills/ship/SKILL.md +1 -1
  21. package/base/skills/visualize-work/SKILL.md +33 -11
  22. package/base/skills/visualize-work/references/spec.md +77 -12
  23. package/package.json +4 -4
  24. package/src/config/schema.ts +58 -4
  25. package/src/doctor/checks.ts +29 -1
  26. package/src/doctor/runner.ts +2 -0
  27. package/src/hooks/command-view.ts +24 -0
  28. package/src/hooks/common/constants.ts +10 -0
  29. package/src/hooks/guard-git.ts +78 -2
  30. package/src/hooks/guard-outside.ts +20 -3
  31. package/src/hooks/guard-writes.ts +17 -6
  32. package/src/hooks/index.ts +2 -0
  33. package/src/hooks/project-guards.ts +123 -0
  34. package/src/hooks/project-tmp.ts +36 -0
  35. package/src/hooks/session-digest.ts +5 -0
  36. package/src/manifest/render.ts +38 -0
  37. package/src/sync/claude-launch.ts +48 -0
  38. package/src/sync/index.ts +1 -0
  39. package/src/sync/local-choice.ts +2 -0
  40. package/src/visualize/assets.ts +195 -54
  41. package/src/visualize/charts.ts +235 -0
  42. package/src/visualize/constants.ts +106 -1
  43. package/src/visualize/diagrams.ts +224 -0
  44. package/src/visualize/icons.ts +28 -0
  45. package/src/visualize/layout.ts +58 -8
  46. package/src/visualize/page.ts +152 -146
  47. package/src/visualize/schema.ts +246 -0
  48. package/src/visualize/sections.ts +370 -0
  49. package/src/visualize/validate.ts +100 -7
  50. package/src/wiki/anchors.ts +118 -0
  51. package/src/wiki/command.ts +110 -0
  52. package/src/wiki/constants.ts +30 -0
  53. package/src/wiki/index.ts +4 -0
  54. package/src/wiki/source-links.ts +186 -0
@@ -39,14 +39,10 @@ const blockersOf = (opts: { from: ICell; to: ICell; cells: Map<string, string> }
39
39
  return crossed.flatMap((cell) => cells.get(`${cell.row},${cell.col}`) ?? []);
40
40
  };
41
41
 
42
- /** What a schema cannot say: ids are unique, every edge and step points at something that exists, a cell holds one box. */
43
- export const checkSpec = (opts: { spec: TVisualizeSpec }): string[] => {
42
+ /** The flow: ids are unique, every edge and step points at something that exists, a cell holds one box. */
43
+ const checkFlow = (opts: { flow: NonNullable<TVisualizeSpec['flow']> }): string[] => {
44
44
  const problems: string[] = [];
45
- const { flow } = opts.spec;
46
-
47
- if (flow === undefined) {
48
- return problems;
49
- }
45
+ const { flow } = opts;
50
46
 
51
47
  const ids = new Set<string>();
52
48
  const cells = new Map<string, string>();
@@ -125,3 +121,100 @@ export const checkSpec = (opts: { spec: TVisualizeSpec }): string[] => {
125
121
 
126
122
  return problems;
127
123
  };
124
+
125
+ /** The other kinds: scores match the criteria, links point at boxes, chart data lines up with its labels. */
126
+ const checkKinds = (opts: { spec: TVisualizeSpec }): string[] => {
127
+ const problems: string[] = [];
128
+ const { comparison, architecture, findings, explainer, decisionRecord } = opts.spec;
129
+
130
+ if (comparison !== undefined) {
131
+ for (const option of comparison.options) {
132
+ if (option.scores.length !== comparison.criteria.length) {
133
+ problems.push(
134
+ `comparison.options: '${option.name}' has ${option.scores.length} scores for ${comparison.criteria.length} criteria`,
135
+ );
136
+ }
137
+ }
138
+
139
+ if (comparison.options.filter((option) => option.recommended === true).length > 1) {
140
+ problems.push('comparison.options: only one option can be recommended');
141
+ }
142
+ }
143
+
144
+ if (architecture !== undefined) {
145
+ const ids = new Set<string>();
146
+
147
+ for (const box of architecture.layers.flatMap((layer) => layer.boxes)) {
148
+ if (ids.has(box.id)) {
149
+ problems.push(`architecture: id '${box.id}' is used twice`);
150
+ }
151
+
152
+ ids.add(box.id);
153
+ }
154
+
155
+ for (const link of architecture.links) {
156
+ for (const end of [link.from, link.to]) {
157
+ if (!ids.has(end)) {
158
+ problems.push(
159
+ `architecture.links: '${link.from}>${link.to}' names '${end}', which is not a box`,
160
+ );
161
+ }
162
+ }
163
+
164
+ if (link.from === link.to) {
165
+ problems.push(`architecture.links: '${link.from}>${link.to}' loops to itself`);
166
+ }
167
+ }
168
+ }
169
+
170
+ for (const [index, chart] of (findings?.charts ?? []).entries()) {
171
+ if (chart.type === 'bar' && chart.labels.length !== chart.values.length) {
172
+ problems.push(
173
+ `findings.charts[${index}]: ${chart.labels.length} labels for ${chart.values.length} values`,
174
+ );
175
+ }
176
+
177
+ if (chart.type === 'line') {
178
+ for (const series of chart.series) {
179
+ if (series.values.length !== chart.labels.length) {
180
+ problems.push(
181
+ `findings.charts[${index}]: series '${series.name}' has ${series.values.length} values for ${chart.labels.length} labels`,
182
+ );
183
+ }
184
+ }
185
+ }
186
+
187
+ if (chart.type === 'donut' && chart.parts.every((part) => part.value === 0)) {
188
+ problems.push(`findings.charts[${index}]: every part of the donut is zero`);
189
+ }
190
+ }
191
+
192
+ for (const [index, step] of (explainer?.steps ?? []).entries()) {
193
+ const { diagram } = step;
194
+
195
+ if (
196
+ diagram?.type === 'row' &&
197
+ diagram.arrows !== undefined &&
198
+ diagram.arrows.length !== diagram.nodes.length - 1
199
+ ) {
200
+ problems.push(
201
+ `explainer.steps[${index}]: a row of ${diagram.nodes.length} boxes takes ${diagram.nodes.length - 1} arrow labels`,
202
+ );
203
+ }
204
+ }
205
+
206
+ if (
207
+ decisionRecord !== undefined &&
208
+ decisionRecord.options.filter((option) => option.chosen === true).length > 1
209
+ ) {
210
+ problems.push('decisionRecord.options: only one option can be chosen');
211
+ }
212
+
213
+ return problems;
214
+ };
215
+
216
+ /** What a schema cannot say, for every kind on the page. */
217
+ export const checkSpec = (opts: { spec: TVisualizeSpec }): string[] => [
218
+ ...(opts.spec.flow === undefined ? [] : checkFlow({ flow: opts.spec.flow })),
219
+ ...checkKinds({ spec: opts.spec }),
220
+ ];
@@ -0,0 +1,118 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { AnchorProblems } from './constants.ts';
4
+ import type { TAnchorProblem } from './constants.ts';
5
+
6
+ /**
7
+ * Every in-page anchor the wiki links to must exist on the page it names. The truth is the BUILT html:
8
+ * VitePress does not slugify the way GitHub does (`Construction - Sentinel` is `construction-sentinel`
9
+ * here), so a reimplemented slugifier reports working links as broken. Reading the emitted `id="..."`
10
+ * removes the guess; the check needs a build.
11
+ */
12
+ export interface IBrokenAnchor {
13
+ file: string;
14
+ line: number;
15
+ target: string;
16
+ reason: TAnchorProblem;
17
+ }
18
+
19
+ const walk = (opts: { directory: string; extension: string }): string[] =>
20
+ readdirSync(opts.directory).flatMap((name) => {
21
+ const full = join(opts.directory, name);
22
+
23
+ if (statSync(full).isDirectory()) {
24
+ return walk({ directory: full, extension: opts.extension });
25
+ }
26
+
27
+ return full.endsWith(opts.extension) ? [full] : [];
28
+ });
29
+
30
+ /** `a/b.html` and `a/index.html` answer to `/a/b` and `/a`. */
31
+ const routeOf = (opts: { file: string; root: string; extension: string }): string => {
32
+ const bare = opts.file.slice(opts.root.length + 1).slice(0, -opts.extension.length);
33
+
34
+ return `/${bare.replace(/\/?index$/, '')}`.replace(/\/$/, '') || '/';
35
+ };
36
+
37
+ const normalizeRoute = (opts: { route: string }): string =>
38
+ opts.route.replace(/\/?index$/, '').replace(/\/$/, '') || '/';
39
+
40
+ /** Resolves a link target - empty (same page), absolute or relative - to a dist route. */
41
+ const resolveRoute = (opts: { file: string; target: string; content: string }): string => {
42
+ const { file, target, content } = opts;
43
+
44
+ if (target === '') {
45
+ return routeOf({ file, root: content, extension: '.md' });
46
+ }
47
+
48
+ const bare = target.replace(/\.md$/, '');
49
+
50
+ if (bare.startsWith('/')) {
51
+ return normalizeRoute({ route: bare });
52
+ }
53
+
54
+ const directory = file
55
+ .slice(content.length + 1)
56
+ .split('/')
57
+ .slice(0, -1)
58
+ .join('/');
59
+
60
+ return normalizeRoute({ route: `/${join(directory, bare)}` });
61
+ };
62
+
63
+ const readAnchors = (opts: { dist: string }): Map<string, Set<string>> => {
64
+ const anchorsByRoute = new Map<string, Set<string>>();
65
+
66
+ for (const file of walk({ directory: opts.dist, extension: '.html' })) {
67
+ const ids = new Set(
68
+ [...readFileSync(file, 'utf8').matchAll(/\sid="([^"]+)"/g)].flatMap((match) =>
69
+ match[1] === undefined ? [] : [match[1]],
70
+ ),
71
+ );
72
+
73
+ anchorsByRoute.set(routeOf({ file, root: opts.dist, extension: '.html' }), ids);
74
+ }
75
+
76
+ return anchorsByRoute;
77
+ };
78
+
79
+ /** Checks every `](page#fragment)` link of the markdown under `content` against the ids built in `dist`. */
80
+ export const checkAnchors = (opts: {
81
+ content: string;
82
+ dist: string;
83
+ }): { checked: number; broken: IBrokenAnchor[] } => {
84
+ const { content } = opts;
85
+ const anchorsByRoute = readAnchors({ dist: opts.dist });
86
+ const broken: IBrokenAnchor[] = [];
87
+ let checked = 0;
88
+
89
+ for (const file of walk({ directory: content, extension: '.md' })) {
90
+ // Fenced code carries example links that are not ours to resolve.
91
+ const body = readFileSync(file, 'utf8').replace(/```[\s\S]*?```/g, (match) =>
92
+ match.replace(/[^\n]/g, ' '),
93
+ );
94
+
95
+ for (const [index, text] of body.split('\n').entries()) {
96
+ for (const match of text.matchAll(/\]\(([^)\s]*?)#([\w.-]+)\)/g)) {
97
+ const [, page = '', anchor = ''] = match;
98
+
99
+ if (page.startsWith('http')) {
100
+ continue;
101
+ }
102
+
103
+ checked += 1;
104
+
105
+ const ids = anchorsByRoute.get(resolveRoute({ file, target: page, content }));
106
+ const target = `${page}#${anchor}`;
107
+
108
+ if (ids === undefined) {
109
+ broken.push({ file, line: index + 1, target, reason: AnchorProblems.MISSING_PAGE });
110
+ } else if (!ids.has(anchor)) {
111
+ broken.push({ file, line: index + 1, target, reason: AnchorProblems.DEAD_ANCHOR });
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ return { checked, broken };
118
+ };
@@ -0,0 +1,110 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { ExitCodes } from '../common/index.ts';
3
+ import { checkAnchors } from './anchors.ts';
4
+ import { WikiDefaults, WikiFlags } from './constants.ts';
5
+ import { checkSourceLinks } from './source-links.ts';
6
+
7
+ /** The value after `--flag`, or the fallback; `undefined` when the flag has no value after it. */
8
+ const valueOf = (opts: { args: string[]; flag: string; fallback?: string }): string | undefined => {
9
+ const at = opts.args.indexOf(opts.flag);
10
+
11
+ if (at === -1) {
12
+ return opts.fallback;
13
+ }
14
+
15
+ const value = opts.args[at + 1];
16
+
17
+ return value === undefined || value.startsWith('--') ? undefined : value;
18
+ };
19
+
20
+ const listOf = (opts: { value: string }): string[] =>
21
+ opts.value
22
+ .split(',')
23
+ .map((item) => item.trim())
24
+ .filter((item) => item !== '');
25
+
26
+ /**
27
+ * `wiki-source-links --repo <owner/name>`: every source path the wiki names is tracked by git. Run from the
28
+ * repository root; the other flags replace the defaults (comma-separated lists).
29
+ */
30
+ export const runSourceLinksCommand = (opts: { args: string[]; root: string }): number => {
31
+ const { args } = opts;
32
+ const repo = valueOf({ args, flag: WikiFlags.REPO });
33
+ const directories = valueOf({
34
+ args,
35
+ flag: WikiFlags.DIRS,
36
+ fallback: `${WikiDefaults.CONTENT_DIRECTORY},${WikiDefaults.KNOWLEDGE_DIRECTORY}`,
37
+ });
38
+ const skipProse = valueOf({
39
+ args,
40
+ flag: WikiFlags.SKIP_PROSE,
41
+ fallback: WikiDefaults.CHANGELOG_DIRECTORY,
42
+ });
43
+ const skip = valueOf({ args, flag: WikiFlags.SKIP, fallback: '' });
44
+
45
+ if (repo === undefined || !/^[\w.-]+\/[\w.-]+$/.test(repo)) {
46
+ console.error(
47
+ `wiki-source-links: ${WikiFlags.REPO} <owner/name> is required, for example ${WikiFlags.REPO} VENIZIA-AI/vulcan`,
48
+ );
49
+
50
+ return ExitCodes.FAILURE;
51
+ }
52
+
53
+ if (directories === undefined || skipProse === undefined || skip === undefined) {
54
+ console.error('wiki-source-links: a flag has no value after it');
55
+
56
+ return ExitCodes.FAILURE;
57
+ }
58
+
59
+ const { checked, missing } = checkSourceLinks({
60
+ root: opts.root,
61
+ repo,
62
+ directories: listOf({ value: directories }),
63
+ skipProseUnder: listOf({ value: skipProse }),
64
+ skipFiles: listOf({ value: skip }),
65
+ });
66
+
67
+ for (const miss of missing) {
68
+ console.log(`${miss.file}:${miss.line} ${miss.path}`);
69
+ }
70
+
71
+ console.log(`wiki-source-links: ${checked} paths checked, ${missing.length} missing`);
72
+
73
+ return missing.length > 0 ? ExitCodes.FAILURE : ExitCodes.OK;
74
+ };
75
+
76
+ /** `wiki-anchors`: every in-page anchor the wiki links to exists in the built site. Needs a build. */
77
+ export const runAnchorsCommand = (opts: { args: string[]; root: string }): number => {
78
+ const content = valueOf({
79
+ args: opts.args,
80
+ flag: WikiFlags.CONTENT,
81
+ fallback: WikiDefaults.CONTENT_DIRECTORY,
82
+ });
83
+ const dist = valueOf({
84
+ args: opts.args,
85
+ flag: WikiFlags.DIST,
86
+ fallback: WikiDefaults.DIST_DIRECTORY,
87
+ });
88
+
89
+ if (content === undefined || dist === undefined) {
90
+ console.error('wiki-anchors: a flag has no value after it');
91
+
92
+ return ExitCodes.FAILURE;
93
+ }
94
+
95
+ if (!existsSync(dist)) {
96
+ console.log('wiki-anchors: no build found - run `make docs` first');
97
+
98
+ return ExitCodes.FAILURE;
99
+ }
100
+
101
+ const { checked, broken } = checkAnchors({ content, dist });
102
+
103
+ for (const entry of broken) {
104
+ console.log(`${entry.file}:${entry.line} ${entry.reason}: ${entry.target}`);
105
+ }
106
+
107
+ console.log(`wiki-anchors: ${checked} anchors checked, ${broken.length} broken`);
108
+
109
+ return broken.length > 0 ? ExitCodes.FAILURE : ExitCodes.OK;
110
+ };
@@ -0,0 +1,30 @@
1
+ import type { TConstValue } from '../common/index.ts';
2
+
3
+ /** Why a wiki link is broken: its page does not exist, or the page has no such fragment. */
4
+ export class AnchorProblems {
5
+ static readonly MISSING_PAGE = 'missing page';
6
+ static readonly DEAD_ANCHOR = 'dead anchor';
7
+ static readonly SCHEME_SET = new Set<string>([this.MISSING_PAGE, this.DEAD_ANCHOR]);
8
+ static isValid(value: string): boolean {
9
+ return this.SCHEME_SET.has(value);
10
+ }
11
+ }
12
+
13
+ export type TAnchorProblem = TConstValue<typeof AnchorProblems>;
14
+
15
+ /** The folders and flags of the two wiki gates; a project overrides each with a flag. */
16
+ export class WikiDefaults {
17
+ static readonly CONTENT_DIRECTORY = 'docs/wiki/content';
18
+ static readonly DIST_DIRECTORY = 'docs/wiki/site/.vitepress/dist';
19
+ static readonly KNOWLEDGE_DIRECTORY = '.agents/knowledge';
20
+ static readonly CHANGELOG_DIRECTORY = 'docs/wiki/content/changelogs';
21
+ }
22
+
23
+ export class WikiFlags {
24
+ static readonly REPO = '--repo';
25
+ static readonly DIRS = '--dirs';
26
+ static readonly SKIP_PROSE = '--skip-prose';
27
+ static readonly SKIP = '--skip';
28
+ static readonly CONTENT = '--content';
29
+ static readonly DIST = '--dist';
30
+ }
@@ -0,0 +1,4 @@
1
+ export * from './anchors.ts';
2
+ export * from './command.ts';
3
+ export * from './constants.ts';
4
+ export * from './source-links.ts';
@@ -0,0 +1,186 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { WikiDefaults } from './constants.ts';
4
+
5
+ /**
6
+ * Every source path the wiki and the knowledge bundle name must be tracked by git. Three kinds of
7
+ * reference are read from each `.md` file: a `<repo>/blob/main/<path>` or `tree/main/<path>` GitHub link
8
+ * (a link into another repository is never checked), a backticked path under a source root (checked
9
+ * outside `skipProseUnder`, where a changelog may name history), and a knowledge concept's `resource:`
10
+ * value (checked only under `.agents/knowledge`). `git ls-files` is the truth, not the disk: a
11
+ * gitignored artifact is not on GitHub.
12
+ */
13
+ const SOURCE_ROOTS = ['packages/', 'examples/', 'scripts/', 'docs/', '.agents/'];
14
+ const SOURCE_EXTENSIONS = ['ts', 'tsx', 'md', 'json', 'mjs', 'js', 'yaml', 'yml'];
15
+ const RESOURCE_LINE_PATTERN = /^resource:\s*(.+)$/;
16
+ const LINE_SUFFIX_PATTERN = /(:\d+|#L\d+)$/;
17
+
18
+ const escapeRegExp = (opts: { text: string }): string =>
19
+ opts.text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+
21
+ // `{}` and `*` mark a template or a glob and `<>` a placeholder, never one real file.
22
+ const BACKTICK_PATTERN = new RegExp(
23
+ `\`((?:${SOURCE_ROOTS.map((root) => escapeRegExp({ text: root })).join('|')})[^\`{}*<>]+?\\.(?:${SOURCE_EXTENSIONS.join('|')})(?::\\d+|#L\\d+)?)\``,
24
+ 'g',
25
+ );
26
+
27
+ export interface IMissingSourceLink {
28
+ file: string;
29
+ line: number;
30
+ path: string;
31
+ }
32
+
33
+ interface ITrackedPaths {
34
+ files: Set<string>;
35
+ directories: Set<string>;
36
+ }
37
+
38
+ const loadTracked = (opts: { root: string }): ITrackedPaths => {
39
+ const result = Bun.spawnSync(['git', 'ls-files', '-z'], { cwd: opts.root, timeout: 30_000 });
40
+
41
+ if (result.exitCode !== 0) {
42
+ throw new Error(`git ls-files failed in ${opts.root}: ${result.stderr.toString().trim()}`);
43
+ }
44
+
45
+ const files = new Set(result.stdout.toString().split('\0').filter(Boolean));
46
+ const directories = new Set<string>();
47
+
48
+ for (const file of files) {
49
+ const segments = file.split('/');
50
+
51
+ for (let depth = 1; depth < segments.length; depth += 1) {
52
+ directories.add(segments.slice(0, depth).join('/'));
53
+ }
54
+ }
55
+
56
+ return { files, directories };
57
+ };
58
+
59
+ const isUnder = (opts: { path: string; directory: string }): boolean =>
60
+ opts.path === opts.directory || opts.path.startsWith(`${opts.directory}/`);
61
+
62
+ const walkMarkdown = (opts: { directory: string }): string[] => {
63
+ if (!existsSync(opts.directory)) {
64
+ return [];
65
+ }
66
+
67
+ return readdirSync(opts.directory, { withFileTypes: true }).flatMap((entry) => {
68
+ const full = join(opts.directory, entry.name);
69
+
70
+ if (entry.isDirectory()) {
71
+ return walkMarkdown({ directory: full });
72
+ }
73
+
74
+ return entry.isFile() && entry.name.endsWith('.md') ? [full] : [];
75
+ });
76
+ };
77
+
78
+ const extractPaths = (opts: { text: string; repo: string; skipProse: boolean }): string[] => {
79
+ const github = new RegExp(
80
+ `${escapeRegExp({ text: opts.repo })}/(?:blob|tree)/main/([^\\s)\\]"'\`<>]+)`,
81
+ 'g',
82
+ );
83
+ const found = [...opts.text.matchAll(github)].map((match) =>
84
+ (match[1] ?? '').replace(LINE_SUFFIX_PATTERN, ''),
85
+ );
86
+
87
+ if (opts.skipProse) {
88
+ return found;
89
+ }
90
+
91
+ const prose = [...opts.text.matchAll(BACKTICK_PATTERN)].map((match) =>
92
+ (match[1] ?? '').replace(LINE_SUFFIX_PATTERN, ''),
93
+ );
94
+
95
+ return [...found, ...prose];
96
+ };
97
+
98
+ /** The `resource:` line of a concept's frontmatter, or none when it has no tracked prefix. */
99
+ const extractResource = (opts: { lines: string[] }): { line: number; path: string } | undefined => {
100
+ const { lines } = opts;
101
+
102
+ if (lines[0] !== '---') {
103
+ return undefined;
104
+ }
105
+
106
+ const close = lines.indexOf('---', 1);
107
+
108
+ if (close === -1) {
109
+ return undefined;
110
+ }
111
+
112
+ for (let index = 1; index < close; index += 1) {
113
+ const match = RESOURCE_LINE_PATTERN.exec(lines[index] ?? '');
114
+ const value = match?.[1]
115
+ ?.trim()
116
+ .replace(/^["']|["']$/g, '')
117
+ .replace(/\/+$/, '');
118
+
119
+ if (
120
+ value !== undefined &&
121
+ value !== '' &&
122
+ SOURCE_ROOTS.some((root) => value.startsWith(root))
123
+ ) {
124
+ return { line: index + 1, path: value };
125
+ }
126
+ }
127
+
128
+ return undefined;
129
+ };
130
+
131
+ /**
132
+ * Walks the `.md` files under `directories` (paths relative to `root`) and reports every source path
133
+ * that git does not track. `skipFiles` are generated pages that are never held to the gate.
134
+ */
135
+ export const checkSourceLinks = (opts: {
136
+ root: string;
137
+ repo: string;
138
+ directories: string[];
139
+ skipProseUnder: string[];
140
+ skipFiles: string[];
141
+ }): { checked: number; missing: IMissingSourceLink[] } => {
142
+ const { root, repo, skipFiles, skipProseUnder } = opts;
143
+ const tracked = loadTracked({ root });
144
+ const exists = (path: string): boolean =>
145
+ tracked.files.has(path) || tracked.directories.has(path);
146
+ const missing: IMissingSourceLink[] = [];
147
+ let checked = 0;
148
+
149
+ for (const directory of opts.directories) {
150
+ for (const file of walkMarkdown({ directory: resolve(root, directory) })) {
151
+ const path = relative(root, file);
152
+
153
+ if (skipFiles.some((skip) => isUnder({ path, directory: skip }))) {
154
+ continue;
155
+ }
156
+
157
+ const skipProse = skipProseUnder.some((skip) => isUnder({ path, directory: skip }));
158
+ const lines = readFileSync(file, 'utf8').split('\n');
159
+ const resource = isUnder({ path, directory: WikiDefaults.KNOWLEDGE_DIRECTORY })
160
+ ? extractResource({ lines })
161
+ : undefined;
162
+
163
+ if (resource !== undefined) {
164
+ checked += 1;
165
+
166
+ if (!exists(resource.path)) {
167
+ missing.push({ file: path, line: resource.line, path: resource.path });
168
+ }
169
+ }
170
+
171
+ for (const [index, text] of lines.entries()) {
172
+ for (const found of extractPaths({ text, repo, skipProse })) {
173
+ checked += 1;
174
+
175
+ if (!exists(found)) {
176
+ missing.push({ file: path, line: index + 1, path: found });
177
+ }
178
+ }
179
+ }
180
+ }
181
+ }
182
+
183
+ missing.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);
184
+
185
+ return { checked, missing };
186
+ };