gcf-aif-ext 0.5.1 → 0.5.3

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.
@@ -4,9 +4,9 @@
4
4
  // inside a file the next upgrade overwrote.
5
5
 
6
6
  import { existsSync } from 'node:fs';
7
- import { glob, readdir, readFile } from 'node:fs/promises';
7
+ import { glob, readdir, readFile, realpath } from 'node:fs/promises';
8
8
  import path from 'node:path';
9
- import { bodyIssues, loadProfileAt, pageRefs, resolveDoc } from './cnlp.js';
9
+ import { bodyIssues, lexiconApplies, loadProfileAt, pageRefs, parseBlocks, resolveDoc } from './cnlp.js';
10
10
 
11
11
  export const CONFIG_NAME = 'cnlp.config.json';
12
12
 
@@ -124,24 +124,48 @@ export function readingOrder(sets) {
124
124
  return out;
125
125
  }
126
126
 
127
+ /** `pageIdOf`, with the set renamed when the caller named it apart from its directory. */
128
+ const renamedIdOf = (rel, docsets, rename) => {
129
+ const id = pageIdOf(rel, docsets);
130
+ return id && { ...id, docset: rename[id.docset] ?? id.docset };
131
+ };
132
+
127
133
  /**
128
134
  * §9 reference conformance across a corpus, which is the 1 check no single document can make.
129
135
  * `docs` is every file already read, so this adds no read of its own.
136
+ *
137
+ * `context` holds the pages of companion sets as `{ set, page, raw }`: they resolve references and
138
+ * are never checked. Their id comes with them rather than from a path, because a companion may sit
139
+ * outside the root, in a folder named by a version rather than by its set.
130
140
  */
131
- export function linkIssues(docs, docsets) {
141
+ export function linkIssues(docs, docsets, { context = [], rename = {} } = {}) {
132
142
  const pages = new Map();
133
143
  const sets = new Set();
134
144
  for (const { rel } of docs) {
135
- const id = pageIdOf(rel, docsets);
145
+ const id = renamedIdOf(rel, docsets, rename);
136
146
  if (!id) continue;
137
147
  pages.set(`${id.docset}:${id.page}`, rel);
138
148
  sets.add(id.docset);
139
149
  }
150
+ const known = new Set(pages.keys());
151
+ for (const { set, page } of context) {
152
+ known.add(`${set}:${page}`);
153
+ sets.add(set);
154
+ }
140
155
 
141
156
  const issues = [];
142
157
  const reached = new Set();
158
+ // A companion's references are not this run's to report, but they count toward reach: a page of
159
+ // an integration set is reached only from the companion that overrides it.
160
+ for (const { set, page, raw } of context) {
161
+ for (const ref of pageRefs(raw)) {
162
+ if (ref.key === 'docset') continue;
163
+ const qualified = ref.target.includes(':') ? ref.target : `${set}:${ref.target}`;
164
+ if (qualified !== `${set}:${page}`) reached.add(qualified);
165
+ }
166
+ }
143
167
  for (const { rel, raw } of docs) {
144
- const from = pageIdOf(rel, docsets);
168
+ const from = renamedIdOf(rel, docsets, rename);
145
169
  if (!from) continue;
146
170
  const self = `${from.docset}:${from.page}`;
147
171
  for (const ref of pageRefs(raw)) {
@@ -157,7 +181,7 @@ export function linkIssues(docs, docsets) {
157
181
  if (ref.key === 'by' && ref.target.includes(':')) {
158
182
  issues.push({ file: rel, line: ref.line, message: `"by: ${ref.target}" carries a document set prefix — a "by:" value names a page of this set` });
159
183
  }
160
- if (!pages.has(qualified)) {
184
+ if (!known.has(qualified)) {
161
185
  issues.push({ file: rel, line: ref.line, message: `page "${qualified}" does not resolve to a file under ${docsets}/` });
162
186
  } else if (qualified !== self) {
163
187
  reached.add(qualified);
@@ -217,6 +241,85 @@ export async function skillDrift(root, agents, version) {
217
241
  return out;
218
242
  }
219
243
 
244
+ /**
245
+ * The standing rules `cnlp init` hands an operator to paste into the file their agent reads. 1
246
+ * value and not a string inside the command, because `cnlp check` reads it too: a pasted copy is a
247
+ * copy that goes stale, and nothing else in the project records that it was taken.
248
+ */
249
+ export const AGENT_BLOCK = [
250
+ '- the CNL-P standard is the authority on document form: read it with `npx cnlp print format`',
251
+ '- run `npx cnlp check` before a commit that touches a document the corpus names',
252
+ "- load a library's documentation with `npx cnlp docs`, which writes every set's index in reading order",
253
+ ];
254
+
255
+ // The 2 files an agent reads by convention, which are the 2 the corpus proposal below already
256
+ // knows. The block is pasted by hand, so nothing records which file took it.
257
+ const AGENT_FILES = ['AGENTS.md', 'CLAUDE.md'];
258
+
259
+ /**
260
+ * The agent files carrying a copy of `AGENT_BLOCK` from an earlier version. A bullet naming
261
+ * `npx cnlp print format` is the block's own opener and is what finds the copy.
262
+ * ponytail: that phrase is the anchor — a version that stops naming it loses the watch on every
263
+ * copy already pasted, and the answer then is markers written into the file.
264
+ */
265
+ export async function agentBlockDrift(root) {
266
+ const out = [];
267
+ for (const name of AGENT_FILES) {
268
+ const at = path.join(root, name);
269
+ if (!existsSync(at)) continue;
270
+ const lines = (await readFile(at, 'utf8')).split(/\r?\n/).map((l) => l.trimEnd());
271
+ const start = lines.findIndex((l) => /^-\s.*`npx cnlp print format`/.test(l));
272
+ if (start < 0) continue; // the project never took the block
273
+ if (lines.slice(start, start + AGENT_BLOCK.length).join('\n') !== AGENT_BLOCK.join('\n')) out.push(name);
274
+ }
275
+ return out;
276
+ }
277
+
278
+ /**
279
+ * The local profiles a packaged profile of the same name has outgrown. A project copies a packaged
280
+ * profile to fill its own `custom_sections`, and `profileFor` reads the copy from then on: an
281
+ * upgrade moves the original underneath it, and the check reports a conformant corpus against a
282
+ * declaration this package has since changed. What a copy adds is the vocabulary it was copied for
283
+ * and is never drift; what the packaged profile declares and the copy does not is.
284
+ */
285
+ export async function profileDrift(config) {
286
+ const out = [];
287
+ if (!config.profilesDir) return out;
288
+ for (const name of [...new Set(config.corpus.map((e) => e.profile))].sort()) {
289
+ const local = path.join(config.profilesDir, `${name}.md`);
290
+ const packagedAt = resolveDoc(name);
291
+ if (!existsSync(local) || !existsSync(packagedAt) || path.resolve(packagedAt) === path.resolve(local)) continue;
292
+ const packaged = await loadProfileAt(packagedAt);
293
+ const mine = await loadProfileAt(local);
294
+ const byKey = new Map(mine.sections.map((s) => [s.key, s]));
295
+ const missing = [];
296
+ for (const want of packaged.sections) {
297
+ const has = byKey.get(want.key);
298
+ if (!has) {
299
+ missing.push(`section "${want.key}"`);
300
+ continue;
301
+ }
302
+ if (has.form !== want.form) missing.push(`section "${want.key}" as a ${want.form}`);
303
+ if (want.required && !has.required) missing.push(`section "${want.key}" as required`);
304
+ for (const k of want.recordKeys) {
305
+ if (!has.recordKeys.includes(k)) missing.push(`record key "${want.key}.${k}"`);
306
+ }
307
+ }
308
+ for (const h of packaged.headings) {
309
+ if (!mine.headings.includes(h)) missing.push(`heading "${h}"`);
310
+ }
311
+ for (const f of packaged.frontmatterFields) {
312
+ if (!mine.frontmatterFields.includes(f)) missing.push(`frontmatter field "${f}"`);
313
+ }
314
+ if (packaged.mood && packaged.mood !== mine.mood) missing.push(`mood "${packaged.mood}"`);
315
+ // Forward slashes, like every other path this reports: the checker names a file the same way
316
+ // on every platform.
317
+ const rel = path.relative(config.root, local).split(path.sep).join('/');
318
+ if (missing.length) out.push({ profile: name, file: rel, missing });
319
+ }
320
+ return out;
321
+ }
322
+
220
323
  // The layouts a corpus entry is usually written for. `cnlp init` keeps the ones that match a file,
221
324
  // so a project adopting the format starts from its own layout rather than from an example of one.
222
325
  // ponytail: path convention only, never content — a decision record filed under docs/references
@@ -272,21 +375,69 @@ export async function proposeCorpus(root) {
272
375
  * An entry matching no file is dropped here, which a written config is right to refuse: a glob a
273
376
  * project typed and no file answers is a mistake, and a glob this function guessed is a folder the
274
377
  * set does not have yet.
378
+ *
379
+ * 1 set checked alone still resolves its crossings: `companions` names the sets it crosses into,
380
+ * each `{ name, dir }`, and the sets beside it join as companions named by their directories. A
381
+ * companion is read to resolve a reference and never checked. `name` names the checked set when
382
+ * its directory does not, as in a layout of `<set>/<version>/`.
275
383
  */
276
- export async function configForPath(dir) {
277
- const abs = path.resolve(dir);
278
- if (!existsSync(abs)) throw new Error(`no such directory: ${dir}`);
384
+ export async function configForPath(dir, { name, companions: named = [] } = {}) {
385
+ if (!existsSync(path.resolve(dir))) throw new Error(`no such directory: ${dir}`);
386
+ // The spelling on disk, not the one typed: on a case-insensitive disk `DragonECS-Unity` would
387
+ // otherwise miss its own directory among the siblings and read itself as a companion.
388
+ const abs = await realpath(path.resolve(dir));
389
+ if (!Array.isArray(named)) throw new Error(`companions is a list of { name, dir }, found ${JSON.stringify(named)}`);
279
390
  let root;
280
391
  let docsets = null;
281
392
  let corpus;
282
- if (existsSync(path.join(abs, 'index.md'))) {
393
+ const oneSet = existsSync(path.join(abs, 'index.md'));
394
+ // A root check already reads every set under it, and a project has no single set to name.
395
+ if (!oneSet && (name !== undefined || named.length)) {
396
+ throw new Error(`${abs} is not 1 document set — a name and companions apply to a directory holding an index.md`);
397
+ }
398
+ const base = path.basename(abs);
399
+ const setName = name ?? base;
400
+ const companions = [];
401
+ if (oneSet) {
402
+ if (name !== undefined) checkSetName(name, 'the checked set');
403
+ for (const c of named) {
404
+ checkSetName(c.name, 'a companion');
405
+ if (!c.dir) throw new Error(`companion "${c.name}" names no dir — give the directory of 1 document set`);
406
+ if (!existsSync(path.resolve(c.dir))) throw new Error(`companion "${c.name}": no such directory: ${path.resolve(c.dir)}`);
407
+ const at = await realpath(path.resolve(c.dir));
408
+ // The checked set read again under another name would reach its own pages through the copy.
409
+ if (at === abs) throw new Error(`companion "${c.name}" is the checked set itself — name another set`);
410
+ if (!existsSync(path.join(at, 'index.md'))) {
411
+ throw new Error(`companion "${c.name}": ${at} holds no index.md — name the directory of 1 document set`);
412
+ }
413
+ if (c.name === setName) throw new Error(`companion "${c.name}" carries the name of the checked set — name it apart`);
414
+ if (companions.some((o) => o.name === c.name)) throw new Error(`companion "${c.name}" is named twice — name each set once`);
415
+ companions.push({ name: c.name, dir: at });
416
+ }
417
+ // A set is present because a project vendors it, so the sets beside it are its companions.
418
+ // A name apart from the directory means no flat layout: the siblings there are other versions
419
+ // of the same set, and reading them as sets would resolve nothing.
420
+ // ponytail: a sibling's name is its directory's and is not held to `checkSetName`; a directory
421
+ // carrying ":" is possible only off Windows, and it would print as a set nobody can reference.
422
+ if (setName === base) {
423
+ const parent = path.dirname(abs);
424
+ for (const entry of (await readdir(parent, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
425
+ const at = path.join(parent, entry.name);
426
+ if (!entry.isDirectory() || entry.name === base || !existsSync(path.join(at, 'index.md'))) continue;
427
+ // An explicit companion wins, by name or by directory: 1 set is read once.
428
+ if (companions.some((o) => o.name === entry.name || o.dir === at)) continue;
429
+ companions.push({ name: entry.name, dir: at });
430
+ }
431
+ }
432
+ }
433
+ if (oneSet) {
283
434
  root = path.dirname(path.dirname(abs));
284
435
  docsets = path.basename(path.dirname(abs));
285
- corpus = docsetCorpus(`${docsets}/${path.basename(abs)}`);
436
+ corpus = docsetCorpus(`${globLiteral(docsets)}/${globLiteral(base)}`);
286
437
  } else if (await holdsASet(abs)) {
287
438
  root = path.dirname(abs);
288
439
  docsets = path.basename(abs);
289
- corpus = docsetCorpus(`${docsets}/*`);
440
+ corpus = docsetCorpus(`${globLiteral(docsets)}/*`);
290
441
  } else {
291
442
  // Neither shape: fall back to the layouts `cnlp init` already knows, so pointing at a project
292
443
  // reads the same as pointing at a set.
@@ -301,7 +452,29 @@ export async function configForPath(dir) {
301
452
  if (kept.length === 0) {
302
453
  throw new Error(`${abs} holds no document this kit knows the layout of — a document set is an index.md beside concepts, api and tasks`);
303
454
  }
304
- return { path: null, root, profilesDir: null, docsets, corpus: kept, agents: [] };
455
+ // `companions` is always present, `[]` included: a caller tells a kit that ignores the option
456
+ // from a set that failed by this field's absence.
457
+ const rename = setName === base ? {} : { [base]: setName };
458
+ return { path: null, root, profilesDir: null, docsets, corpus: kept, agents: [], companions, rename };
459
+ }
460
+
461
+ /** A set name keys every page id, and `:` separates `<set>:<name>`, so a name carrying it reads as a page. */
462
+ function checkSetName(name, whose) {
463
+ if (typeof name !== 'string' || name === '' || /[:/\\]/.test(name)) {
464
+ throw new Error(`${JSON.stringify(name)} is no name for ${whose} — a set name is not empty and carries no ":", "/" or "\\"`);
465
+ }
466
+ }
467
+
468
+ /**
469
+ * A directory name as a glob that matches only itself. The corpus is a glob, and a set in
470
+ * `2.0.0-[rc]` otherwise reads as a character class that matches no directory, which reports
471
+ * the set as holding no document. A class of 1 character is the escape `fs.glob` honours: it
472
+ * reads `\` as a separator on Windows.
473
+ * ponytail: a `{` still opens a brace set, which no escape reaches through `fs.glob`; a set
474
+ * directory named with braces needs a config instead of a path.
475
+ */
476
+ function globLiteral(name) {
477
+ return name.replace(/[[*?]/g, (c) => `[${c}]`);
305
478
  }
306
479
 
307
480
  /** Whether an immediate subdirectory carries an index.md, which is what makes a directory a root. */
@@ -329,10 +502,40 @@ export async function filesFor(entry, root) {
329
502
  * Run every corpus entry. Returns the files checked and the issues found, each carrying the
330
503
  * project-relative path it came from. Severity is the caller's: an issue is an issue here.
331
504
  */
505
+ /**
506
+ * The bytes a document set costs a reader, split by when they are paid. The index is loaded to
507
+ * answer any question and a page is loaded to answer 1, so the 2 numbers are different kinds of
508
+ * cost, and an author trimming the wrong one saves a reader nothing.
509
+ *
510
+ * Computed from the documents the caller has already read, so this adds no read of its own.
511
+ */
512
+ export function setSizes(docs, docsets, rename = {}) {
513
+ const sets = new Map();
514
+ for (const { rel, raw } of docs) {
515
+ const id = renamedIdOf(rel, docsets, rename);
516
+ if (!id) continue;
517
+ const set = sets.get(id.docset) ?? { name: id.docset, indexBytes: 0, pages: 0, pageBytes: 0 };
518
+ const bytes = Buffer.byteLength(raw, 'utf8');
519
+ if (id.page === 'index') set.indexBytes += bytes;
520
+ else {
521
+ set.pages += 1;
522
+ set.pageBytes += bytes;
523
+ }
524
+ sets.set(id.docset, set);
525
+ }
526
+ return [...sets.values()].sort((a, b) => a.name.localeCompare(b.name));
527
+ }
528
+
332
529
  export async function checkProject(config) {
333
530
  const issues = [];
334
531
  const checked = [];
335
532
  const docs = [];
533
+ // A document the §5 word lists never reach. It is not an issue — nothing in it is wrong — but a
534
+ // run that says nothing about it reports a conformant corpus over rules that never ran.
535
+ const foreign = [];
536
+ // §3: a marked region the file's profile did not shape. Reported for the same reason: a run that
537
+ // names no exemption reads as a check of every line, and a region is an exemption anybody can write.
538
+ const regions = [];
336
539
  for (const entry of config.corpus) {
337
540
  const files = await filesFor(entry, config.root);
338
541
  if (files.length === 0) {
@@ -343,10 +546,25 @@ export async function checkProject(config) {
343
546
  const raw = await readFile(path.join(config.root, rel), 'utf8');
344
547
  checked.push(rel);
345
548
  docs.push({ rel, raw });
549
+ if (!lexiconApplies(raw)) foreign.push(rel);
550
+ for (const r of parseBlocks(raw).regions) regions.push({ file: rel, ...r });
346
551
  for (const issue of bodyIssues(raw, profile)) issues.push({ file: rel, ...issue });
347
552
  }
348
553
  }
554
+ // A config from `readConfig` carries neither field: it already reads every set under its root.
555
+ const rename = config.rename ?? {};
556
+ // A companion's pages resolve references and are counted nowhere: the run reports on the set it
557
+ // was pointed at. `docsetCorpus` is the 1 place the shape of a set is written, so it is read here too.
558
+ const context = [];
559
+ for (const { name, dir } of config.companions ?? []) {
560
+ for (const entry of docsetCorpus('.')) {
561
+ for (const rel of await filesFor(entry, dir)) {
562
+ const page = rel.split(path.sep).join('/').slice(0, -3);
563
+ context.push({ set: name, page, raw: await readFile(path.join(dir, rel), 'utf8') });
564
+ }
565
+ }
566
+ }
349
567
  // §9 is the 1 rule that needs the whole corpus, so it runs once over the files already read.
350
- if (config.docsets) issues.push(...linkIssues(docs, config.docsets));
351
- return { checked, issues };
568
+ if (config.docsets) issues.push(...linkIssues(docs, config.docsets, { context, rename }));
569
+ return { checked, issues, foreign, regions, sets: config.docsets ? setSizes(docs, config.docsets, rename) : [] };
352
570
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-aif-ext",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Game Context Framework for AI Factory",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -42,7 +42,7 @@
42
42
  "README.md"
43
43
  ],
44
44
  "dependencies": {
45
- "cnlp-kit": "^3.1.3",
45
+ "cnlp-kit": "^3.9.1",
46
46
  "yaml": "^2.5.1"
47
47
  },
48
48
  "bundleDependencies": [
@@ -19,10 +19,11 @@ workflow:
19
19
  1. run `ai-factory gcf audit --json` and read the report
20
20
  2. state the first line verbatim: items waiting too long block dependent work, so they lead
21
21
  3. for each stale until record: name the file, the trigger that fired and the line to re-check; for each entry of `stale_questions`: name the question id and ask the human for the answer
22
- 4. read the `design` summary: blocking findings first (run `ai-factory gcf design check` for the list), then the count of ready units
23
- 5. semantic pass, only when the mechanical report is clean or the human asks: read the systems docs of ONE subsystem the human names and report pairs of lines that contradict each other as D1 questions
24
- 6. list the pragmas: each `gcf:allow` is a standing exception, and a growing list is the linter rotting
25
- 7. propose the next actions, ranked, proposed actions <= 3: playtest, answer a D1, take a ready unit, or collapse a stale record
22
+ 4. for a stale until record of `gcf/open-questions.md`: the D2 assumption its `id` names expired - ask the human to confirm it, then cite `answer: <id>` and remove the record, or to replace the value
23
+ 5. read the `design` summary: blocking findings first (run `ai-factory gcf design check` for the list), then the count of ready units
24
+ 6. semantic pass, only when the mechanical report is clean or the human asks: read the systems docs of ONE subsystem the human names and report pairs of lines that contradict each other as D1 questions
25
+ 7. list the pragmas: each `gcf:allow` is a standing exception, and a growing list is the linter rotting
26
+ 8. propose the next actions, ranked, proposed actions <= 3: playtest, answer a D1, take a ready unit, or collapse a stale record
26
27
 
27
28
  invocation:
28
29
  - run at session start, after a long break, or on demand
@@ -15,7 +15,7 @@ preconditions:
15
15
  - the project is a git repository with AI Factory initialized
16
16
 
17
17
  forbidden_behaviors:
18
- - do not overwrite an existing gcf/ tree: re-running repairs missing files only
18
+ - do not overwrite an existing gcf/ tree: re-running repairs missing files, refreshes the AGENTS.md block and restamps a 0.4.0 `frozen:`
19
19
  - do not write pillars the human did not confirm: pillar authorship is human
20
20
  - pillar count <= 7, and do not pad the list to reach 7
21
21