@venizia/vulcan-okf 0.2.0-0 → 0.2.0-2

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/README.md CHANGED
@@ -34,28 +34,41 @@ allowed; links inside code are examples, never edges. Files may use LF or CRLF l
34
34
 
35
35
  Two mechanisms, both driven from source. Never hand-edit either.
36
36
 
37
- 1. **Whole generated files** - the `RENDERERS` registry in `src/generate/renderers.ts` writes `reference/*.md`, each
38
- with `generated.by: process:okf-gen` (§5.2). No `generated.at`: a timestamp would make every
39
- regeneration look like a change.
40
- 2. **Managed regions** - the `REGIONS` registry replaces content between
41
- `<!-- okf:generated:<id> start -->` and `<!-- okf:generated:<id> end -->` inside an otherwise
42
- hand-authored file.
37
+ 1. **Whole generated files** - each renderer in `okf.renderers` writes one page, by default under
38
+ `reference/`, with `generated.by: process:okf-gen` (§5.2). No `generated.at`: a timestamp would
39
+ make every regeneration look like a change.
40
+ 2. **Managed regions** - each `okf.regions` entry (`{ id, file, renderer }`) replaces the content
41
+ between `<!-- okf:generated:<id> start -->` and `<!-- okf:generated:<id> end -->` inside an
42
+ otherwise hand-authored file.
43
+
44
+ `gen` renders every page and region in memory first: a renderer that throws, a path outside the
45
+ bundle or two renderers on one path stop it before anything is written. A `gen` that changes nothing
46
+ prints `gen: up to date`.
43
47
 
44
48
  `reference/public-surface.md` is generated by `@venizia/vulcan-atlas` (`vulcan x atlas surface gen`),
45
49
  not by `gen`; its `generated:` frontmatter tells `gen` to leave it whole. Long agent-read files get a
46
50
  generated contents list near the top; a file with `generated:` frontmatter and the bundle's `log.md`
47
- get none.
51
+ get none. The id `contents` is reserved for that list: a region named `contents` stops `gen`.
52
+
53
+ A project module (`okf.renderers[]` with `module`) may take the id of a built-in renderer such as
54
+ `source-map`. The module then replaces the built-in, and `gen`, `check` and `coverage` say so once on
55
+ stderr: `okf: module 'source-map' replaces the built-in renderer`.
48
56
 
49
57
  ## Adding a renderer
50
58
 
51
- 1. Write a `collect*` function that extracts the fact from source.
52
- **Use it for both the renderer and the coverage counter** - a second heuristic for the same fact
53
- drifts, and the numbers disagree.
54
- 2. Write a `render*` returning `{ path, content }` and add it to `RENDERERS`.
55
- 3. Run `gen`, then `check --strict` twice: it must pass and be idempotent.
59
+ A built-in renderer (`source-map`, `makefile-targets`, `packages-table`, `binding-keys`) is listed by
60
+ id, with `options`. A project's own renderer is a module:
61
+
62
+ 1. Default-export `defineRenderer({ id, collect, render?, region?, coverage? })` from a file in the
63
+ project, importing the API from `@venizia/vulcan/okf`.
64
+ 2. `collect` extracts the fact from source, once. **`render`, `region` and `coverage` all read
65
+ it** - a second heuristic for the same fact drifts, and the numbers disagree.
66
+ 3. List it in the config: `okf: { renderers: [{ id, module: '.agents/okf/<file>.ts' }] }`, and in
67
+ `okf.regions` when it renders a region.
68
+ 4. Run `vulcan x okf gen`, then `vulcan x okf check --strict`: it passes, and a second `gen` prints
69
+ `gen: up to date`.
56
70
 
57
- The renderers and coverage rows are IGNIS-specific today (`src/config.ts`); making them project
58
- config is planned.
71
+ The [adoption guide](../../docs/wiki/content/guides/adopting-vulcan.md) shows a complete module.
59
72
 
60
73
  ## Layout
61
74
 
@@ -64,10 +77,11 @@ config is planned.
64
77
  | `src/cli.ts` | `vulcan-okf` entry; spawns `src/run.ts`, the command runner |
65
78
  | `src/index.ts` | the public API: the OKF v0.2 conformance layer |
66
79
  | `src/source/` | source scanning and the shared fact collectors (one per fact, used by gen and coverage) |
67
- | `src/generate/` | `gen`: managed regions and the `RENDERERS` / `REGIONS` registries |
80
+ | `src/generate/` | `gen`: the built-in renderers, project modules (`defineRenderer`), regions and contents lists |
68
81
  | `src/check/` | `check`: OKF conformance, plus the house rules under `--strict` |
69
82
  | `src/coverage-report/` | `coverage`: the bundle against the source inventory |
70
83
  | `src/lib.ts` | bundle loader: frontmatter, links, concept model |
71
84
  | `src/spec/` | OKF v0.2 conformance - pure, never throws |
72
85
  | `src/viz/` | explorer: builder (Bun), typed browser client, template |
73
- | `src/config.ts` | the only project-specific file: paths, section order, explorer copy |
86
+ | `src/project/` | reads the project config `vulcan x` hands okf - everything project-specific |
87
+ | `src/config.ts` | constants that hold for every project: pruned directories, reserved files |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/vulcan-okf",
3
- "version": "0.2.0-0",
3
+ "version": "0.2.0-2",
4
4
  "description": "VULCAN knowledge tooling: OKF v0.2 conformance check (plus --strict house rules), gen, coverage and the offline graph explorer for a project's .agents/knowledge bundle. Bun-only.",
5
5
  "homepage": "https://github.com/VENIZIA-AI/vulcan/tree/main/packages/okf",
6
6
  "repository": {
@@ -61,7 +61,18 @@ export const collectChangelogProblems = (): string[] => {
61
61
  .filter(name => DATED_ENTRY.test(name))
62
62
  .sort()) {
63
63
  const path = relative(project.root, join(directory, file));
64
- const frontmatter = frontmatterOf({ text: readFileSync(join(directory, file), 'utf8') });
64
+ let frontmatter: TRecord;
65
+
66
+ // One broken entry is one problem; the rest of the directory is still checked.
67
+ try {
68
+ frontmatter = frontmatterOf({ text: readFileSync(join(directory, file), 'utf8') });
69
+ } catch (error) {
70
+ problems.push(
71
+ `changelog: ${path}: the frontmatter is not valid YAML (${error instanceof Error ? error.message : String(error)})`,
72
+ );
73
+ continue;
74
+ }
75
+
65
76
  // `packages: []` is a decision - an entry about no package, such as repository tooling. Only a
66
77
  // missing list is undecided.
67
78
  if (!Array.isArray(frontmatter.packages)) {
@@ -102,7 +113,8 @@ export const collectChangelogProblems = (): string[] => {
102
113
  if (!tags.some(tag => pattern.test(tag))) {
103
114
  const expected = project.tagPattern
104
115
  .replace(/<(?:dir|package)>/g, dir)
105
- .replace(/<version>/g, override[2]);
116
+ .replace(/<version>/g, override[2])
117
+ .replace(/<date>/g, 'YYYY-MM-DD');
106
118
 
107
119
  problems.push(
108
120
  `changelog: ${path}: release '${frontmatter.release}' names no tag (${expected})`,
@@ -93,7 +93,11 @@ export const collectHouseProblems = (opts: {
93
93
 
94
94
  const paths = new Set(opts.files.map(file => file.path));
95
95
 
96
- for (const axis of collectCoverageAxes()) {
96
+ const { axes, problems: axisProblems } = collectCoverageAxes();
97
+
98
+ problems.push(...axisProblems);
99
+
100
+ for (const axis of axes) {
97
101
  const section = axis.name;
98
102
 
99
103
  for (const name of axis.items) {
@@ -111,9 +115,23 @@ export const collectHouseProblems = (opts: {
111
115
  continue;
112
116
  }
113
117
 
114
- const actual = extractRegion({ text: readFileSync(region.file, 'utf8'), id: region.id });
118
+ let actual: string;
119
+
120
+ // Broken markers are the person's to fix by hand - gen refuses them, so never call them stale.
121
+ try {
122
+ actual = extractRegion({
123
+ text: readFileSync(region.file, 'utf8'),
124
+ id: region.id,
125
+ file: repoRelative({ path: region.file }),
126
+ });
127
+ } catch (error) {
128
+ problems.push(
129
+ `freshness: ${(error instanceof Error ? error.message : String(error)).replace(/^okf: /, '')}`,
130
+ );
131
+ continue;
132
+ }
115
133
 
116
- if (actual === null || !sameContent({ left: actual, right: region.render() })) {
134
+ if (!sameContent({ left: actual, right: region.render() })) {
117
135
  problems.push(`freshness: region '${region.id}' is stale - ${REGENERATE_HINT}`);
118
136
  }
119
137
  }
@@ -5,22 +5,30 @@ import { readOkfProject } from '../project/index.ts';
5
5
  /**
6
6
  * The structural coverage axes (`okf.coverage`): each `path` globs directories under the root, and
7
7
  * every matched directory, minus the denylist, needs a concept at `<name>/<directory>.md`. A path that
8
- * matches no directory fails - an axis that covers nothing passes by accident.
8
+ * matches no directory is a problem - an axis that covers nothing passes by accident.
9
9
  */
10
- export const collectCoverageAxes = (): { name: string; items: string[] }[] => {
10
+ export const collectCoverageAxes = (): {
11
+ axes: { name: string; items: string[] }[];
12
+ problems: string[];
13
+ } => {
11
14
  const project = readOkfProject();
15
+ const axes: { name: string; items: string[] }[] = [];
16
+ const problems: string[] = [];
12
17
 
13
- return project.coverage.map(axis => {
18
+ for (const axis of project.coverage) {
14
19
  const matched = [
15
20
  ...new Bun.Glob(axis.path).scanSync({ cwd: project.root, onlyFiles: false, dot: false }),
16
21
  ].filter(path => statSync(join(project.root, path)).isDirectory());
17
22
 
18
23
  if (matched.length === 0) {
19
- throw new Error(`okf: coverage axis '${axis.name}' matches no directory (${axis.path})`);
24
+ problems.push(`coverage: axis '${axis.name}' (${axis.path}) matches no directory`);
25
+ continue;
20
26
  }
21
27
 
22
28
  const items = matched.map(path => basename(path)).filter(name => !project.denylist.has(name));
23
29
 
24
- return { name: axis.name, items: [...new Set(items)].sort() };
25
- });
30
+ axes.push({ name: axis.name, items: [...new Set(items)].sort() });
31
+ }
32
+
33
+ return { axes, problems };
26
34
  };
@@ -44,8 +44,15 @@ export const coverage = async (): Promise<void> => {
44
44
  );
45
45
  };
46
46
 
47
+ const { axes, problems } = collectCoverageAxes();
48
+
49
+ // The report would count an axis that covers nothing as fully covered.
50
+ if (problems.length > 0) {
51
+ throw new Error(`okf: ${problems.join('; ')}`);
52
+ }
53
+
47
54
  lines.push('STRUCTURAL (target 100% - one curated concept each)');
48
- for (const axis of collectCoverageAxes()) {
55
+ for (const axis of axes) {
49
56
  struct({
50
57
  name: axis.name,
51
58
  items: axis.items,
@@ -6,15 +6,22 @@ import { renderPages } from './pages.ts';
6
6
  import { loadGeneration } from './registry.ts';
7
7
  import { repoRelative } from '../source/index.ts';
8
8
 
9
+ /** The file as it is on disk, or undefined when it does not exist yet. */
10
+ const currentOf = (opts: { path: string }): string | undefined =>
11
+ existsSync(opts.path) ? readFileSync(opts.path, 'utf8') : undefined;
12
+
9
13
  /**
10
14
  * Writes exactly the configured regions and renderers, then the contents lists. Everything renders in
11
15
  * memory first, so a failure writes nothing; the contents lists go last, so one `gen` is a fixed point
12
- * - they see what the regions wrote, and skip every page a renderer owns.
16
+ * - they see what the regions wrote, and skip every page a renderer owns. Only a file whose content
17
+ * changed is written and named, so a run with nothing to do says so in one line.
13
18
  */
14
19
  export const gen = async (): Promise<void> => {
15
20
  const { renderers, regions } = await loadGeneration();
16
21
  const regionWrites = regions.flatMap(region => {
17
- if (!existsSync(region.file)) {
22
+ const current = currentOf({ path: region.file });
23
+
24
+ if (current === undefined) {
18
25
  console.warn(
19
26
  `gen: skipped region '${region.id}' - ${repoRelative({ path: region.file })} does not exist yet`,
20
27
  );
@@ -22,18 +29,17 @@ export const gen = async (): Promise<void> => {
22
29
  return [];
23
30
  }
24
31
 
25
- return [
26
- {
27
- region,
28
- text: replaceRegion({
29
- text: readFileSync(region.file, 'utf8'),
30
- id: region.id,
31
- body: region.render(),
32
- }),
33
- },
34
- ];
32
+ const text = replaceRegion({
33
+ text: current,
34
+ id: region.id,
35
+ file: repoRelative({ path: region.file }),
36
+ body: region.render(),
37
+ });
38
+
39
+ return text === current ? [] : [{ region, text }];
35
40
  });
36
- const pages = renderPages({ renderers });
41
+ const rendered = renderPages({ renderers });
42
+ const pages = rendered.filter(page => currentOf({ path: page.path }) !== page.content);
37
43
 
38
44
  for (const { region, text } of regionWrites) {
39
45
  writeFileSync(region.file, text);
@@ -47,7 +53,7 @@ export const gen = async (): Promise<void> => {
47
53
  }
48
54
 
49
55
  // Every project's long agent-read files carry a contents list, whatever it renders.
50
- const contents = writeContents({ skip: new Set(pages.map(page => page.path)) });
56
+ const contents = writeContents({ skip: new Set(rendered.map(page => page.path)) });
51
57
 
52
58
  for (const file of contents) {
53
59
  console.log(`gen: wrote the contents list of ${file}`);
@@ -55,5 +61,7 @@ export const gen = async (): Promise<void> => {
55
61
 
56
62
  if (renderers.length === 0 && regions.length === 0 && contents.length === 0) {
57
63
  console.log('gen: nothing configured - okf.renderers and okf.regions are empty');
64
+ } else if (regionWrites.length === 0 && pages.length === 0 && contents.length === 0) {
65
+ console.log('gen: up to date');
58
66
  }
59
67
  };
@@ -7,36 +7,133 @@ import { markers } from './regions.ts';
7
7
  */
8
8
  export const CONTENTS_MIN_LINES = 100;
9
9
 
10
- const CONTENTS_ID = 'contents';
11
- const FENCE = /^(```|~~~)/;
10
+ /** The managed region okf writes the contents list into; no `okf.regions` entry may take it. */
11
+ export const CONTENTS_ID = 'contents';
12
12
  const FRONTMATTER = /^---\n[\s\S]*?\n---\n/;
13
+ /** A fence line: up to three spaces, a run of three or more backticks or tildes, then the rest. */
14
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
15
+ const HEADING = /^(#{1,6})[ \t]+(.+?)[ \t]*$/;
16
+ /** A link, inline or by reference: its text is what the heading shows. */
17
+ const LINK = /\[([^\]]*)\](?:\([^)]*\)|\[[^\]]*\])/g;
18
+ /** What GitHub strips from a heading for its anchor: punctuation but `-` and `_`, symbols, separators but the space. */
19
+ const ANCHOR_STRIPPED =
20
+ /(?![ -])(?!\p{Alphabetic})[\p{No}\p{Pd}\p{Ps}\p{Pe}\p{Pi}\p{Pf}\p{Po}\p{S}\p{C}\p{Z}]/gu;
13
21
 
14
- /** The `##` headings outside code fences, in order. */
15
- const headingsOf = (opts: { text: string }): string[] => {
16
- const headings: string[] = [];
17
- let fenced = false;
22
+ /**
23
+ * The lines outside code fences, by index. A fence closes only on its own character, at least as long
24
+ * as it opened, with nothing after it - so a ```` block can quote a ``` one (CommonMark).
25
+ */
26
+ const unfencedLines = (opts: { lines: string[] }): { index: number; line: string }[] => {
27
+ const unfenced: { index: number; line: string }[] = [];
28
+ let open: string | undefined;
29
+
30
+ for (const [index, line] of opts.lines.entries()) {
31
+ const fence = FENCE.exec(line);
32
+
33
+ if (open !== undefined) {
34
+ if (
35
+ fence !== null &&
36
+ fence[1][0] === open[0] &&
37
+ fence[1].length >= open.length &&
38
+ fence[2].trim() === ''
39
+ ) {
40
+ open = undefined;
41
+ }
18
42
 
19
- for (const line of opts.text.split('\n')) {
20
- if (FENCE.test(line)) {
21
- fenced = !fenced;
22
43
  continue;
23
44
  }
24
45
 
25
- if (!fenced && line.startsWith('## ')) {
26
- headings.push(line.slice(3).trim());
46
+ // A backtick fence's info string holds no backtick; a line that does is inline code.
47
+ if (fence !== null && !(fence[1][0] === '`' && fence[2].includes('`'))) {
48
+ open = fence[1];
49
+ continue;
27
50
  }
51
+
52
+ unfenced.push({ index, line });
28
53
  }
29
54
 
30
- return headings;
55
+ return unfenced;
56
+ };
57
+
58
+ /** The lines a file has, as `wc -l` counts them: a final newline ends the last line, it opens none. */
59
+ const lineCountOf = (opts: { text: string }): number => {
60
+ const count = opts.text.split('\n').length;
61
+
62
+ return opts.text.endsWith('\n') ? count - 1 : count;
63
+ };
64
+
65
+ /** Emphasis as markdown renders it away: `_word_`, `**word**`, `***word***` - never `snake_case`. */
66
+ const EMPHASIS = /(?<![\p{L}\p{N}])([*_]{1,3})(?=\S)(.+?)(?<=\S)\1(?![\p{L}\p{N}])/gu;
67
+
68
+ const NAMED_ENTITIES: Record<string, string> = {
69
+ amp: '&',
70
+ lt: '<',
71
+ gt: '>',
72
+ quot: '"',
73
+ apos: "'",
74
+ nbsp: ' ',
75
+ };
76
+
77
+ /** A heading's text as GitHub renders it, which is what its anchor is made from: entities decoded, emphasis gone. */
78
+ const renderedOf = (opts: { text: string }): string =>
79
+ opts.text
80
+ .replace(EMPHASIS, '$2')
81
+ .replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, body: string) => {
82
+ if (body.startsWith('#')) {
83
+ const code =
84
+ body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : Number(body.slice(1));
85
+
86
+ return Number.isFinite(code) ? String.fromCodePoint(code) : entity;
87
+ }
88
+
89
+ return NAMED_ENTITIES[body.toLowerCase()] ?? entity;
90
+ });
91
+
92
+ /**
93
+ * A heading's anchor as GitHub writes it (github-slugger): lower case; punctuation and symbols gone,
94
+ * `-` and `_` kept; each space a hyphen; a repeat of an earlier anchor takes `-1`, `-2`. `taken`
95
+ * holds the anchors the page has used so far, every heading level counted.
96
+ */
97
+ const anchorOf = (opts: { text: string; taken: Map<string, number> }): string => {
98
+ const { taken } = opts;
99
+ const slug = opts.text.toLowerCase().replace(ANCHOR_STRIPPED, '').replace(/ /g, '-');
100
+ let anchor = slug;
101
+
102
+ while (taken.has(anchor)) {
103
+ const count = (taken.get(slug) ?? 0) + 1;
104
+
105
+ taken.set(slug, count);
106
+ anchor = `${slug}-${count}`;
107
+ }
108
+
109
+ taken.set(anchor, 0);
110
+
111
+ return anchor;
31
112
  };
32
113
 
33
- /** A heading's anchor as GitHub and VitePress write it: lower case, punctuation gone, spaces as hyphens. */
34
- const anchorOf = (opts: { heading: string }): string =>
35
- opts.heading
36
- .toLowerCase()
37
- .replace(/[^\p{L}\p{N}\s-]/gu, '')
38
- .trim()
39
- .replace(/\s+/g, '-');
114
+ /** The `##` headings outside code fences and frontmatter, in order: the text each shows, its anchor. */
115
+ const headingsOf = (opts: { text: string }): { text: string; anchor: string }[] => {
116
+ const body = opts.text.slice(FRONTMATTER.exec(opts.text)?.[0].length ?? 0);
117
+ const taken = new Map<string, number>();
118
+ const headings: { text: string; anchor: string }[] = [];
119
+
120
+ for (const { line } of unfencedLines({ lines: body.split('\n') })) {
121
+ const heading = HEADING.exec(line);
122
+
123
+ if (heading === null) {
124
+ continue;
125
+ }
126
+
127
+ const text = heading[2].replace(LINK, '$1');
128
+ const anchor = anchorOf({ text: renderedOf({ text }), taken });
129
+
130
+ if (heading[1] === '##') {
131
+ headings.push({ text, anchor });
132
+ }
133
+ }
134
+
135
+ return headings;
136
+ };
40
137
 
41
138
  /**
42
139
  * The text with the contents region and the blank line after it taken out. A marker counts only on a
@@ -46,20 +143,10 @@ const anchorOf = (opts: { heading: string }): string =>
46
143
  const withoutContents = (opts: { text: string }): string => {
47
144
  const { start, end } = markers({ id: CONTENTS_ID });
48
145
  const lines = opts.text.split('\n');
49
- let fenced = false;
50
146
  let startLine = -1;
51
147
  let endLine = -1;
52
148
 
53
- for (const [index, line] of lines.entries()) {
54
- if (FENCE.test(line)) {
55
- fenced = !fenced;
56
- continue;
57
- }
58
-
59
- if (fenced) {
60
- continue;
61
- }
62
-
149
+ for (const { index, line } of unfencedLines({ lines })) {
63
150
  if (startLine === -1 && line === start) {
64
151
  startLine = index;
65
152
  } else if (startLine !== -1 && line === end) {
@@ -103,12 +190,12 @@ export const withContents = (opts: { text: string }): string => {
103
190
  const bare = withoutContents({ text: opts.text });
104
191
  const headings = headingsOf({ text: bare });
105
192
 
106
- if (bare.split('\n').length <= CONTENTS_MIN_LINES || headings.length === 0) {
193
+ if (lineCountOf({ text: bare }) <= CONTENTS_MIN_LINES || headings.length === 0) {
107
194
  return bare;
108
195
  }
109
196
 
110
197
  const { start, end } = markers({ id: CONTENTS_ID });
111
- const list = headings.map(heading => `- [${heading}](#${anchorOf({ heading })})`).join('\n');
198
+ const list = headings.map(heading => `- [${heading.text}](#${heading.anchor})`).join('\n');
112
199
  const block = `${start}\n**Contents**\n\n${list}\n${end}\n\n`;
113
200
  const at = insertionPointOf({ text: bare });
114
201
 
@@ -7,56 +7,57 @@ export const markers = (opts: { id: string }): { start: string; end: string } =>
7
7
  };
8
8
  };
9
9
 
10
- /** Locate a managed region, rejecting malformed or duplicated markers rather than corrupting the file. */
10
+ /**
11
+ * Locate a managed region, rejecting malformed or duplicated markers rather than corrupting the file.
12
+ * `file` is the host file as the person sees it, named in every error.
13
+ */
11
14
  export const locateRegion = (opts: {
12
15
  text: string;
13
16
  id: string;
17
+ file: string;
14
18
  }): { start: string; end: string; startAt: number; endAt: number } => {
15
- const { text, id } = opts;
19
+ const { text, id, file } = opts;
16
20
 
17
21
  const { start, end } = markers({ id });
18
22
  const startAt = text.indexOf(start);
19
23
  const endAt = text.indexOf(end);
24
+ const region = `okf: ${file}: managed region '${id}'`;
20
25
 
21
26
  if (startAt === -1 || endAt === -1) {
22
- throw new Error(`managed region '${id}' not found`);
27
+ throw new Error(`${region} is missing its markers - add ${start} and ${end}`);
23
28
  }
24
29
 
25
30
  if (text.indexOf(start, startAt + 1) !== -1) {
26
- throw new Error(`managed region '${id}' has a duplicate start marker`);
31
+ throw new Error(`${region} is malformed - a duplicate start marker`);
27
32
  }
28
33
 
29
34
  if (text.indexOf(end, endAt + 1) !== -1) {
30
- throw new Error(`managed region '${id}' has a duplicate end marker`);
35
+ throw new Error(`${region} is malformed - a duplicate end marker`);
31
36
  }
32
37
 
33
38
  if (startAt + start.length > endAt) {
34
- throw new Error(`managed region '${id}' is malformed - end marker precedes start marker`);
39
+ throw new Error(`${region} is malformed - the end marker precedes the start marker`);
35
40
  }
36
41
 
37
42
  return { start, end, startAt, endAt };
38
43
  };
39
44
 
40
- export const replaceRegion = (opts: { text: string; id: string; body: string }): string => {
41
- const { text, id, body } = opts;
45
+ export const replaceRegion = (opts: {
46
+ text: string;
47
+ id: string;
48
+ file: string;
49
+ body: string;
50
+ }): string => {
51
+ const { text, id, file, body } = opts;
42
52
 
43
- const { start, startAt, endAt } = locateRegion({ text, id });
53
+ const { start, startAt, endAt } = locateRegion({ text, id, file });
44
54
 
45
55
  return text.slice(0, startAt + start.length) + '\n' + body + '\n' + text.slice(endAt);
46
56
  };
47
57
 
48
- export const extractRegion = (opts: { text: string; id: string }): string | null => {
49
- const { text, id } = opts;
50
-
51
- let located;
52
-
53
- try {
54
- located = locateRegion({ text, id });
55
- } catch (error) {
56
- console.warn(`okf: ${(error as Error).message}`);
57
-
58
- return null;
59
- }
58
+ /** The region's current body; throws like `locateRegion` when its markers are broken. */
59
+ export const extractRegion = (opts: { text: string; id: string; file: string }): string => {
60
+ const { start, startAt, endAt } = locateRegion(opts);
60
61
 
61
- return text.slice(located.startAt + located.start.length, located.endAt).trim();
62
+ return opts.text.slice(startAt + start.length, endAt).trim();
62
63
  };
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { readOkfProject } from '../project/index.ts';
4
4
  import type { IOkfRendererEntry } from '../project/index.ts';
5
+ import { CONTENTS_ID } from './contents.ts';
5
6
  import { createRenderContext } from './define.ts';
6
7
  import type { IRenderContext, IRenderer } from './define.ts';
7
8
  import { BUILT_IN_RENDERERS } from './renderers.ts';
@@ -78,6 +79,12 @@ const loadRenderer = async (opts: {
78
79
  entry: IOkfRendererEntry;
79
80
  }): Promise<ILoadedRenderer> => {
80
81
  const { entry } = opts;
82
+
83
+ // Allowed - a project may own a built-in's output - but never silent.
84
+ if (entry.module !== undefined && Object.hasOwn(BUILT_IN_RENDERERS, entry.id)) {
85
+ console.warn(`okf: module '${entry.id}' replaces the built-in renderer`);
86
+ }
87
+
81
88
  const renderer =
82
89
  entry.module === undefined
83
90
  ? builtInRenderer({ id: entry.id })
@@ -106,6 +113,12 @@ export const loadGeneration = async (): Promise<{
106
113
  }
107
114
 
108
115
  const regions = project.regions.map(region => {
116
+ if (region.id === CONTENTS_ID) {
117
+ throw new Error(
118
+ `okf: region id '${CONTENTS_ID}' is reserved for the contents list okf writes - rename the region`,
119
+ );
120
+ }
121
+
109
122
  const loaded = renderers.find(candidate => candidate.renderer.id === region.renderer) ?? {
110
123
  renderer: builtInRenderer({ id: region.renderer }),
111
124
  context: createRenderContext({ options: {} }),
@@ -99,6 +99,17 @@ const coverageOf = (opts: { value: unknown }): { name: string; path: string }[]
99
99
  : [];
100
100
  });
101
101
 
102
+ /** The handoff, parsed: only `vulcan x` writes it, so anything else is okf run by hand. */
103
+ const parsedOf = (opts: { text: string }): unknown => {
104
+ try {
105
+ return JSON.parse(opts.text);
106
+ } catch (error) {
107
+ throw new Error('okf: VULCAN_CONFIG is not valid JSON - run okf through `vulcan x`', {
108
+ cause: error,
109
+ });
110
+ }
111
+ };
112
+
102
113
  /** The last handoff read and what it gave: okf reads its project once per process. */
103
114
  let cached: { text: string; root: string; project: IOkfProject } | undefined;
104
115
 
@@ -111,16 +122,14 @@ export const readOkfProject = (): IOkfProject => {
111
122
  const root = process.env[OkfProjectConstants.ROOT_ENV];
112
123
 
113
124
  if (text === undefined || root === undefined) {
114
- throw new Error(
115
- 'okf: no project config - run through `vulcan x okf` (or add .configs/vulcan.config.ts)',
116
- );
125
+ throw new Error('okf: no project config - run through `vulcan x okf`');
117
126
  }
118
127
 
119
128
  if (cached?.text === text && cached.root === root) {
120
129
  return cached.project;
121
130
  }
122
131
 
123
- const config = recordOf({ value: JSON.parse(text) });
132
+ const config = recordOf({ value: parsedOf({ text }) });
124
133
  const knowledge = recordOf({ value: config.knowledge });
125
134
  const okf = recordOf({ value: config.okf });
126
135
  const sections = recordOf({ value: okf.sections });
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
- import { join, relative } from 'node:path';
2
+ import { isAbsolute, join, relative } from 'node:path';
3
3
  import { readOkfProject } from '../project/index.ts';
4
4
  import type { BindingClass, MakeTarget, SourceMapEntry } from './common/types.ts';
5
5
  import { listDirs, listPackages, sourceFiles } from './scanner.ts';
@@ -100,10 +100,12 @@ export const collectMakefileTargets = (): MakeTarget[] => {
100
100
  .filter(Boolean);
101
101
 
102
102
  for (const makefile of makefiles) {
103
- const file = projectPath({ path: makefile });
103
+ // make lists an include by the path it was given: relative to the root, or absolute.
104
+ const file = isAbsolute(makefile) ? makefile : projectPath({ path: makefile });
104
105
  const makefileText = existsSync(file) ? readFileSync(file, 'utf8') : '';
105
106
 
106
- for (const row of makefileText.matchAll(/^([a-z][\w-]*):[^#=\n]*##\s*(.+)$/gm)) {
107
+ // A `;` starts an inline recipe: a `##` after it is the recipe's, never the description.
108
+ for (const row of makefileText.matchAll(/^([a-z][\w-]*):[^#=;\n]*##\s*(.+)$/gm)) {
107
109
  commented.set(row[1], row[2].trim());
108
110
  }
109
111
  }