@delurio/cli 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/check.js CHANGED
@@ -5,21 +5,27 @@
5
5
  import { createHash } from 'node:crypto';
6
6
  import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { basename, dirname, join, relative, resolve } from 'node:path';
8
- import { keyAt, readYaml } from './yaml.js';
9
- import { GraphError, load } from './graph.js';
8
+ import { keyAt, parsingOnce, readYaml } from './yaml.js';
9
+ import { alternatives, GraphError, load, placed } from './graph.js';
10
10
  import { checkAssertions, explore, Model, ModelError } from './model.js';
11
11
  import { stepsByEvents } from './story.js';
12
12
  import { renderScreens } from './wireframe.js';
13
13
  import { checkStarts } from './starts.js';
14
- import { checkChanges } from './changes.js';
14
+ import { checkChanges, flowDomain } from './changes.js';
15
+ import { checkUi } from './ui-check.js';
16
+ import { checkInvokes } from './invokes.js';
17
+ import { checkTutorial } from './tutorial-check.js';
15
18
  import { KitError, resolveKit } from './kit.js';
16
19
  import { checkGoals, findings, loadNav, viewOf } from './nav.js';
17
20
  import { schemaKindOf, validateFile } from './schemas.js';
18
21
  import { inReadingOrder, mergeDomain } from './domain.js';
22
+ import { checkDomainNames } from './domain-names.js';
23
+ import { checkNeeds } from './needs.js';
19
24
  export const CHECK_USAGE = [
20
- ' node src/cli.ts check <graphs folder> [--strict] [--baseline <sarif>] [--format sarif --output <file>]',
21
- ' checks every graph under the folder and writes nothing else: GNU error lines on stdout, or SARIF 2.1.0;',
22
- ' exit 0 clean, 1 a graph cannot be loaded or needs a newer format, 2 an error under --strict (new since --baseline)',
25
+ ' node src/cli.ts check <graphs folder>... [--strict] [--baseline <sarif>] [--format sarif --output <file>] [--app <dir>]',
26
+ ' checks every graph under the folders and writes nothing else: GNU error lines on stdout, or SARIF 2.1.0;',
27
+ ' exit 0 clean, 1 a graph cannot be loaded or needs a newer format, 2 an error under --strict (new since --baseline);',
28
+ ' the evidence of needs is found under --app, the application\'s repository root (default: the working directory)',
23
29
  ].join('\n');
24
30
  const FORMAT = 'delurio-graph/0';
25
31
  const SKIP = new Set(['viz', 'video', 'recording', 'node_modules', '.git']);
@@ -30,9 +36,11 @@ const RULES = [
30
36
  { id: 'domain-twice', text: 'A value of a domain is given in two of its files (SPEC.md §5)', level: 'error' },
31
37
  { id: 'domain-place', text: 'A domain file is not with the rest of its domain (SPEC.md §1)', level: 'error' },
32
38
  { id: 'server-fn-http', text: 'A server function is given a route, a query or an operationId, which only an HTTP operation has (SPEC.md §5)', level: 'error' },
39
+ { id: 'entity-unknown', text: "An action's returns or a references names an entity its domain does not have (SPEC.md §5)", level: 'error' },
40
+ { id: 'field-unknown', text: "An entity's key or required names a field the entity does not have (SPEC.md §5)", level: 'error' },
33
41
  { id: 'assertion-violated', text: 'A guarantee of the flow is broken by a reachable situation', level: 'error' },
34
42
  { id: 'main-story-unwalkable', text: 'The declared main story cannot be walked', level: 'error' },
35
- { id: 'catalog-key-missing', text: 'A catalog key the screens use is missing', level: 'error' },
43
+ { id: 'catalog-key-missing', text: "A catalog key the screens use is missing from a locale's catalog", level: 'error' },
36
44
  { id: 'sample-missing', text: 'A catalog message has a placeholder with no sample value', level: 'error' },
37
45
  { id: 'no-renderer', text: 'A component has no renderer', level: 'error' },
38
46
  { id: 'kit-uncovered', text: "The kit does not cover a component or an intent", level: 'error' },
@@ -40,12 +48,32 @@ const RULES = [
40
48
  { id: 'hand-over', text: 'A started flow cannot begin with what it is given', level: 'error' },
41
49
  { id: 'changes-note-missing', text: 'A flow whose steps write has no changes note (SPEC.md §4)', level: 'error' },
42
50
  { id: 'changes-note-locale', text: "The changes note is missing from a locale's catalog", level: 'error' },
51
+ { id: 'changes-note-gap', text: 'A writing flow says why it has no changes note yet: counted, and fails nothing (SPEC.md §4)', level: 'note' },
52
+ { id: 'task-locale', text: "The flow's name for its users is missing from a locale's catalog (SPEC.md §4)", level: 'error' },
43
53
  { id: 'source-missing', text: 'A state of a captured flow names no code (SPEC.md §9)', level: 'error' },
54
+ { id: 'focus-not-shown', text: 'A focus or a returnsFocus gives the focus to a node that is not shown there (SPEC.md §4)', level: 'error' },
55
+ { id: 'returns-focus-not-dialog', text: 'A returnsFocus does not start at a dialog (SPEC.md §4)', level: 'error' },
56
+ { id: 'state-no-way-out', text: 'A state that is not an exit has no way out (SPEC.md §2)', level: 'error' },
57
+ { id: 'state-unreachable', text: 'No situation the flow starts in reaches the state (SPEC.md §2)', level: 'error' },
58
+ { id: 'tutorial-mismatch', text: 'A tutorial no longer matches its flow (SPEC.md §7)', level: 'error' },
59
+ { id: 'evidence-unresolved', text: "A need's evidence names what is not there (SPEC.md §13)", level: 'error' },
60
+ { id: 'need-no-evidence', text: 'A need that is not missing names no evidence outside the graph (SPEC.md §13)', level: 'error' },
61
+ { id: 'need-unlisted', text: "A missing need is not in the product's gaps (SPEC.md §13)", level: 'error' },
62
+ { id: 'need-twice', text: "A need's id is given twice in its flow's needs (SPEC.md §13)", level: 'error' },
63
+ { id: 'needs-place', text: 'A needs file is beside no flow, or is the needs of another one (SPEC.md §13)', level: 'error' },
64
+ { id: 'gap-met', text: 'The gaps list a need that is met (SPEC.md §13)', level: 'error' },
65
+ { id: 'gap-unknown', text: 'The gaps list a need that no flow under them has (SPEC.md §13)', level: 'error' },
66
+ { id: 'need-gap', text: 'A need that is missing, listed in the gaps: counted, and fails nothing (SPEC.md §13)', level: 'note' },
67
+ { id: 'invoke-unknown', text: "An invoke or a failures entry names an action its flow's domain does not have, or the domain is not found (SPEC.md §5)", level: 'error' },
68
+ { id: 'refusal-unknown', text: 'A failure class lists a code that is neither a refusal of its action nor a transport code (SPEC.md §2, §5)', level: 'error' },
69
+ { id: 'policy-unknown', text: 'A policy names an action or an entity its domain does not have (SPEC.md §5)', level: 'error' },
44
70
  { id: 'graph-warning', text: 'Another warning of the graph', level: 'error' },
45
71
  { id: 'nav-problem', text: 'A problem of the navigation graph', level: 'error' },
46
72
  { id: 'nav-note', text: 'A note on the navigation graph', level: 'warning' },
47
73
  ];
48
74
  const LEVEL = new Map(RULES.map((r) => [r.id, r.level]));
75
+ // the rules whose errors stop the run (exit 1) however --strict and --baseline read them
76
+ const BREAKING = new Set(['load', 'format-newer']);
49
77
  export const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
50
78
  // the 1-based line and column of the first occurrence of `needle`, else the file's start
51
79
  function placeOf(abs, needle) {
@@ -122,13 +150,83 @@ function fromWarning(dir, graph, w) {
122
150
  return result('changes-note-locale', ui, placeOf(ui, 'changes:'), w, graph, `changes/${m[2]}`);
123
151
  return result('graph-warning', existsSync(ui) ? ui : flow, { line: 1, column: 1 }, w, graph, w);
124
152
  }
125
- function checkFlow(dir) {
153
+ // the words of the screens in each locale but the one ui.yaml names (SPEC.md §4): a key the screens use that a locale's
154
+ // catalog lacks, at the key's line, as for the catalog ui.yaml names; a locale whose catalog is not there, at `locales`
155
+ function checkLocales(g, dir) {
156
+ if (g.ui.absent === true)
157
+ return [];
158
+ const ui = join(dir, 'ui.yaml');
159
+ const named = join(dir, g.ui.catalog);
160
+ const out = [];
161
+ for (const locale of g.ui.locales ?? []) {
162
+ const name = join(dirname(g.ui.catalog), `${locale}.json`);
163
+ const abs = join(dir, name);
164
+ if (abs === named)
165
+ continue;
166
+ let catalog;
167
+ try {
168
+ catalog = JSON.parse(readFileSync(abs, 'utf8'));
169
+ }
170
+ catch (err) {
171
+ const text = readFileSync(ui, 'utf8');
172
+ const why = existsSync(abs) ? `is not JSON: ${err.message}` : 'does not exist';
173
+ out.push(result('catalog-key-missing', ui, keyAt(text, ['locales']), `the ${locale} catalog, ${name}, ${why}: every word the screens use is missing in ${locale}`, g.flow.id, `catalog/${locale}`));
174
+ continue;
175
+ }
176
+ const missing = [];
177
+ const collect = (m) => {
178
+ const key = /^catalog key (\S+) is missing/.exec(m)?.[1];
179
+ if (key !== undefined && !missing.includes(key))
180
+ missing.push(key);
181
+ };
182
+ const other = { ...g, catalog: catalog !== null && typeof catalog === 'object' ? catalog : {} };
183
+ renderScreens(other, collect, null);
184
+ checkUi(other, collect);
185
+ for (const key of missing)
186
+ out.push(result('catalog-key-missing', ui, placeOf(ui, key), `catalog key ${key} is missing from the ${locale} catalog, ${name}`, g.flow.id, `${key}/${locale}`));
187
+ }
188
+ return out;
189
+ }
190
+ // the states that some transition leads to, whatever its guard
191
+ function targeted(g) {
192
+ const out = new Set();
193
+ for (const st of Object.values(g.flow.states)) {
194
+ for (const a of st.always ?? [])
195
+ out.add(a.target);
196
+ for (const spec of Object.values(st.on ?? {}))
197
+ for (const a of alternatives(spec))
198
+ out.add(a.target);
199
+ }
200
+ return out;
201
+ }
202
+ function checkFlow(dir, domains) {
126
203
  const file = join(dir, 'flow.yaml');
127
204
  const g = load(dir);
128
- const kit = resolveKit(dir, g.ui.kit, undefined);
205
+ let kit;
206
+ try {
207
+ kit = resolveKit(dir, g.ui.kit, undefined);
208
+ }
209
+ catch (err) {
210
+ throw g.ui.kit === undefined ? err : placed(err, { file: 'ui.yaml', path: ['kit'] });
211
+ }
129
212
  const model = new Model(g.flow);
130
213
  const ex = explore(model);
131
214
  const out = [];
215
+ const flowText = readFileSync(file, 'utf8');
216
+ // a state the flow stops in for good though it is no exit, and a state no situation reaches (SPEC.md §2)
217
+ const led = targeted(g);
218
+ for (const [name, st] of Object.entries(g.flow.states)) {
219
+ const at = () => keyAt(flowText, ['states', name]);
220
+ const element = `states/${name}`;
221
+ const ways = Object.keys(st.on ?? {}).length + (st.always ?? []).length;
222
+ if (st.type !== 'final' && ways === 0 && st.invoke === undefined) {
223
+ out.push(result('state-no-way-out', file, at(), `state ${name} is not an exit and has no way out: it has no on, always or invoke, so the flow stops there; make it an exit (type: final) or give it a transition (SPEC.md §2)`, g.flow.id, element));
224
+ }
225
+ if (!ex.atState.has(name)) {
226
+ const why = led.has(name) ? 'the transitions that lead to it are never taken: the states they leave are not reached, or their guards never hold' : 'no transition leads to it';
227
+ out.push(result('state-unreachable', file, at(), `state ${name} is reached by no situation the flow starts in: ${why} (SPEC.md §2)`, g.flow.id, element));
228
+ }
229
+ }
132
230
  const warnings = [];
133
231
  const warn = (m) => {
134
232
  if (!warnings.includes(m))
@@ -147,21 +245,47 @@ function checkFlow(dir) {
147
245
  if (g.flow.main !== undefined && stepsByEvents(model, g.flow.main) === null)
148
246
  warn('the declared main story cannot be walked: an event is not possible where it is sent');
149
247
  renderScreens(g, warn, kit);
248
+ if (g.ui.absent !== true) {
249
+ const ui = join(dir, 'ui.yaml');
250
+ const text = readFileSync(ui, 'utf8');
251
+ for (const p of checkUi(g, warn))
252
+ out.push(result(p.rule, ui, keyAt(text, p.path), p.message, g.flow.id, p.element));
253
+ }
254
+ out.push(...checkLocales(g, dir));
150
255
  for (const h of checkStarts(g, model, ex))
151
256
  for (const p of h.problems)
152
257
  warn(`${h.from} starts ${h.flow}: ${p}`);
153
- for (const p of checkChanges(g)?.problems ?? [])
258
+ // the flow's domain, looked up once for the rules that read it
259
+ let domain;
260
+ const domainOf = () => (domain === undefined ? (domain = flowDomain(g, domains)) : domain);
261
+ const changes = checkChanges(g, domainOf);
262
+ for (const p of changes?.problems ?? [])
154
263
  warn(p);
155
264
  for (const w of warnings)
156
265
  out.push(fromWarning(dir, g.flow.id, w));
266
+ // a writing flow whose app has no changes message yet says why: a gap of the flow, at the level note (SPEC.md §4)
267
+ if (changes !== null && changes.missing !== null) {
268
+ const ui = join(dir, 'ui.yaml');
269
+ const message = `its steps write (${changes.writes.join(', ')}), and its changes note is missing: ${changes.missing}; Rehber does not guide its writing steps (SPEC.md §4)`;
270
+ out.push(result('changes-note-gap', ui, keyAt(readFileSync(ui, 'utf8'), ['changes', 'missing']), message, g.flow.id, 'changes/missing'));
271
+ }
272
+ for (const p of checkInvokes(g, domainOf))
273
+ out.push(result(p.rule, file, keyAt(flowText, p.path), p.message, g.flow.id, p.element));
274
+ const tutorial = join(dir, 'tutorial.yaml');
275
+ if (existsSync(tutorial)) {
276
+ const text = readFileSync(tutorial, 'utf8');
277
+ for (const p of checkTutorial(g, model, ex, text)) {
278
+ const at = p.line === undefined ? keyAt(text, p.path) : { line: p.line, column: p.column ?? 1 };
279
+ out.push(result('tutorial-mismatch', tutorial, at, p.message, g.flow.id, `tutorial.yaml#/${p.path.join('/')}`));
280
+ }
281
+ }
157
282
  // a captured flow is read from code, so every state names the code that makes it true; an exit may leave it out, as
158
283
  // the transition into it names that code (SPEC.md §9)
159
284
  if (g.flow.status === 'captured') {
160
- const text = readFileSync(file, 'utf8');
161
285
  for (const [name, st] of Object.entries(g.flow.states)) {
162
286
  if (st.source !== undefined || st.type === 'final')
163
287
  continue;
164
- out.push(result('source-missing', file, keyAt(text, ['states', name]), `state ${name} names no code: in a captured flow every state but an exit carries source: <path>:<line> (SPEC.md §9)`, g.flow.id, `states/${name}`));
288
+ out.push(result('source-missing', file, keyAt(flowText, ['states', name]), `state ${name} names no code: in a captured flow every state but an exit carries source: <path>:<line> (SPEC.md §9)`, g.flow.id, `states/${name}`));
165
289
  }
166
290
  }
167
291
  return out;
@@ -207,9 +331,19 @@ function checkServerFunctions(parts, doc, id) {
207
331
  }
208
332
  return out;
209
333
  }
334
+ // whether a domain's file gives the entity
335
+ function givesEntity(text, entity) {
336
+ try {
337
+ const entities = readYaml(text)?.entities;
338
+ return entities !== null && typeof entities === 'object' && Object.hasOwn(entities, entity);
339
+ }
340
+ catch {
341
+ return false;
342
+ }
343
+ }
210
344
  // the domains under root, each the domain files of one directory read as one (SPEC.md §5): a value given in two of
211
- // them, a file whose id is not its directory's, a domain whose files sit in two directories, and a server function
212
- // given what only an HTTP operation has
345
+ // them, a file whose id is not its directory's, a domain whose files sit in two directories, a server function given
346
+ // what only an HTTP operation has, and a name of an entity, a field or an action that the domain does not have
213
347
  function checkDomains(files) {
214
348
  const byDir = new Map();
215
349
  for (const f of files)
@@ -217,14 +351,32 @@ function checkDomains(files) {
217
351
  byDir.set(dirname(f), [...(byDir.get(dirname(f)) ?? []), f]);
218
352
  const out = [];
219
353
  const dirsOf = new Map(); // a domain's id -> the directories that hold it
220
- for (const [dir, list] of byDir) {
354
+ const domains = [...byDir].map(([dir, list]) => {
221
355
  const parts = inReadingOrder(list).map((file) => ({ file, text: readFileSync(file, 'utf8') }));
222
- const merged = mergeDomain(parts);
356
+ return { dir, parts, merged: mergeDomain(parts) };
357
+ });
358
+ // an entity of another domain, for the note of a name that this one does not have
359
+ const elsewhere = (self) => (entity) => {
360
+ for (const { dir, parts, merged } of domains) {
361
+ const id = merged.id ?? rel(dir);
362
+ const entities = merged.doc.entities;
363
+ if (id === self || entities === null || typeof entities !== 'object' || !Object.hasOwn(entities, entity))
364
+ continue;
365
+ const part = parts.find((p) => givesEntity(p.text, entity)) ?? parts[0];
366
+ return { domain: id, file: part.file, ...keyAt(part.text, ['entities', entity]) };
367
+ }
368
+ return null;
369
+ };
370
+ for (const { dir, parts, merged } of domains) {
371
+ const id = merged.id ?? rel(dir);
223
372
  for (const p of merged.problems) {
224
373
  const notes = p.first === undefined ? [] : [{ file: rel(p.first.file), line: p.first.line, column: p.first.column, message: 'given first here' }];
225
- out.push(result(p.rule, p.file, p, p.message, merged.id ?? rel(dir), p.element, notes));
374
+ out.push(result(p.rule, p.file, p, p.message, id, p.element, notes));
375
+ }
376
+ out.push(...checkServerFunctions(parts, merged.doc, id));
377
+ for (const p of checkDomainNames(parts, merged.doc, id, elsewhere(id))) {
378
+ out.push(result(p.rule, p.file, p, p.message, id, p.element, p.notes.map((n) => ({ ...n, file: rel(n.file) }))));
226
379
  }
227
- out.push(...checkServerFunctions(parts, merged.doc, merged.id ?? rel(dir)));
228
380
  if (merged.id !== null)
229
381
  dirsOf.set(merged.id, [...(dirsOf.get(merged.id) ?? []), dir]);
230
382
  }
@@ -246,6 +398,23 @@ function checkNav(dir) {
246
398
  out.push(result('graph-warning', file, { line: 1, column: 1 }, w, g.id, w));
247
399
  return out;
248
400
  }
401
+ // the level a finding is printed at, and counted at: an error known from the baseline is a warning, as it fails no
402
+ // run, but one that stops the run (it cannot be loaded) is an error however often it was seen
403
+ const printedLevel = (r) => (r.level === 'error' && r.baselineState === 'unchanged' && !BREAKING.has(r.rule) ? 'warning' : r.level);
404
+ // where a load error is (SPEC.md §10): the place the loader or the model gave it, at the keys it names or the line a
405
+ // parser gave, in the file it names; else the line a YAML parser gave; else the start of the graph's own file
406
+ function loadPlace(dir, file, err) {
407
+ const place = err.place;
408
+ const at = place === undefined ? file : join(dir, place.file);
409
+ if (place?.line !== undefined)
410
+ return { file: at, line: place.line, column: place.column ?? 1 };
411
+ const linePos = err.linePos?.[0];
412
+ if (linePos !== undefined)
413
+ return { file: at, line: linePos.line, column: linePos.col };
414
+ if (place?.path !== undefined && existsSync(at))
415
+ return { file: at, ...keyAt(readFileSync(at, 'utf8'), place.path) };
416
+ return { file: at, line: 1, column: 1 };
417
+ }
249
418
  const fingerprint = (r) => createHash('sha256').update(`${r.rule}|${r.graph}|${r.element}`).digest('hex').slice(0, 32);
250
419
  function baselinePrints(file) {
251
420
  const doc = JSON.parse(readFileSync(file, 'utf8'));
@@ -298,18 +467,29 @@ function sarif(results, exitCode) {
298
467
  ],
299
468
  };
300
469
  }
470
+ // every text the check reads is parsed once in it (`parsingOnce`), however many graphs read it
301
471
  export function checkMain(args) {
472
+ return parsingOnce(() => checkRun(args));
473
+ }
474
+ function checkRun(args) {
302
475
  const flag = (name) => {
303
476
  const i = args.indexOf(name);
304
477
  return i >= 0 ? args[i + 1] : undefined;
305
478
  };
306
- const withValue = ['--baseline', '--format', '--output'];
307
- const dir = args.find((a, i) => !a.startsWith('--') && !withValue.includes(args[i - 1] ?? ''));
308
- if (dir === undefined) {
479
+ const withValue = ['--baseline', '--format', '--output', '--app'];
480
+ const dirs = args.filter((a, i) => !a.startsWith('--') && !withValue.includes(args[i - 1] ?? ''));
481
+ if (dirs.length === 0) {
309
482
  console.error(`usage:\n${CHECK_USAGE}`);
310
483
  return 1;
311
484
  }
312
- const root = resolve(dir);
485
+ const notFolder = dirs.find((d) => !existsSync(d) || !statSync(d).isDirectory());
486
+ if (notFolder !== undefined) {
487
+ console.error(`${notFolder} is not a folder\nusage:\n${CHECK_USAGE}`);
488
+ return 1;
489
+ }
490
+ // every folder given, each graph and file once though one folder holds another
491
+ const roots = dirs.map((d) => resolve(d));
492
+ const dirsOfGraphs = [...new Set(roots.flatMap((r) => graphDirs(r)))];
313
493
  const strict = args.includes('--strict');
314
494
  const format = flag('--format') ?? 'text';
315
495
  const output = flag('--output');
@@ -318,9 +498,16 @@ export function checkMain(args) {
318
498
  console.error(`--format is text or sarif, not ${format}`);
319
499
  return 1;
320
500
  }
501
+ const appGiven = flag('--app');
502
+ if (appGiven !== undefined && (!existsSync(appGiven) || !statSync(appGiven).isDirectory())) {
503
+ console.error(`--app ${appGiven} is not a folder\nusage:\n${CHECK_USAGE}`);
504
+ return 1;
505
+ }
506
+ const app = resolve(appGiven ?? '.');
321
507
  const results = [];
508
+ const domains = new Map(); // the domains found, for every flow that names one
322
509
  let broken = false;
323
- for (const d of graphDirs(root)) {
510
+ for (const d of dirsOfGraphs) {
324
511
  const file = existsSync(join(d, 'flow.yaml')) ? join(d, 'flow.yaml') : join(d, 'nav.yaml');
325
512
  try {
326
513
  const newer = newerFormat(file);
@@ -329,30 +516,34 @@ export function checkMain(args) {
329
516
  results.push(result('format-newer', file, placeOf(file, 'schema:'), `written in ${newer}; this checker reads ${FORMAT}: pin a version that reads it`, rel(d), 'schema'));
330
517
  continue;
331
518
  }
332
- results.push(...(file.endsWith('flow.yaml') ? checkFlow(d) : checkNav(d)));
519
+ results.push(...(file.endsWith('flow.yaml') ? checkFlow(d, domains) : checkNav(d)));
333
520
  }
334
521
  catch (err) {
335
522
  if (!(err instanceof GraphError || err instanceof ModelError || err instanceof KitError || (err instanceof Error && err.name === 'YAMLParseError')))
336
523
  throw err;
337
524
  broken = true;
338
- const linePos = err.linePos?.[0];
339
- results.push(result('load', file, linePos === undefined ? { line: 1, column: 1 } : { line: linePos.line, column: linePos.col }, err.message.split('\n')[0], rel(d), 'load'));
525
+ const at = loadPlace(d, file, err);
526
+ results.push(result('load', at.file, at, err.message.split('\n')[0], rel(d), 'load'));
340
527
  }
341
528
  }
342
529
  // every graph file against its kind's schema: what an editor with the schemas marks, check reports
343
- const files = graphFiles(root);
530
+ const files = [...new Set(roots.flatMap((r) => graphFiles(r)))];
344
531
  for (const file of files) {
345
532
  for (const f of validateFile(file))
346
533
  results.push(result('schema', file, f, f.message, f.graph ?? rel(file), f.element));
347
534
  }
348
535
  results.push(...checkDomains(files));
536
+ // each flow's needs held to their evidence, and the product's gaps to its needs (SPEC.md §13)
537
+ const needs = checkNeeds(files, app);
538
+ for (const p of needs.problems)
539
+ results.push(result(p.rule, p.file, p, p.message, p.graph, p.element));
349
540
  results.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column || a.rule.localeCompare(b.rule) || a.message.localeCompare(b.message));
350
541
  if (baseline !== undefined) {
351
542
  const prints = baselinePrints(baseline);
352
543
  for (const r of results)
353
544
  r.baselineState = prints.has(fingerprint(r)) ? 'unchanged' : 'new';
354
545
  }
355
- const failing = results.filter((r) => r.level === 'error' && r.rule !== 'load' && r.rule !== 'format-newer' && (r.baselineState === undefined || r.baselineState === 'new'));
546
+ const failing = results.filter((r) => r.level === 'error' && !BREAKING.has(r.rule) && (r.baselineState === undefined || r.baselineState === 'new'));
356
547
  const exitCode = broken ? 1 : strict && failing.length > 0 ? 2 : 0;
357
548
  if (format === 'sarif') {
358
549
  const text = `${JSON.stringify(sarif(results, exitCode), null, 2)}\n`;
@@ -363,15 +554,21 @@ export function checkMain(args) {
363
554
  }
364
555
  if (format === 'text' || output !== undefined) {
365
556
  for (const r of results) {
366
- const level = r.level === 'error' && r.baselineState === 'unchanged' ? 'warning' : r.level;
367
- console.log(`${r.file}:${r.line}:${r.column}: ${level}: ${r.message} [${r.rule}]`);
557
+ console.log(`${r.file}:${r.line}:${r.column}: ${printedLevel(r)}: ${r.message} [${r.rule}]`);
368
558
  for (const n of r.notes)
369
559
  console.log(`${n.file}:${n.line}:${n.column}: note: ${n.message}`);
370
560
  }
371
- const graphs = graphDirs(root).length;
372
- const errors = results.filter((r) => r.level === 'error').length;
373
- const warnings = results.filter((r) => r.level === 'warning').length;
374
- console.error(`delurio check: ${count(graphs, 'graph')}, ${count(errors, 'error')}, ${count(warnings, 'warning')}; exit ${exitCode}`);
561
+ const graphs = dirsOfGraphs.length;
562
+ const errors = results.filter((r) => printedLevel(r) === 'error').length;
563
+ const warnings = results.filter((r) => printedLevel(r) === 'warning').length;
564
+ // the gaps, once a flow has needs: every need that is missing, listed or not, and those the base run did not have
565
+ const fresh = results.filter((r) => r.rule === 'need-gap' && r.baselineState === 'new').length;
566
+ const gaps = needs.files === 0 ? '' : `, ${count(needs.gaps, 'gap')} of ${count(needs.needs, 'need')}${fresh > 0 ? ` (${fresh} new)` : ''}`;
567
+ // the changes notes that writing flows say are missing (SPEC.md §4), once there is one
568
+ const notes = results.filter((r) => r.rule === 'changes-note-gap');
569
+ const newNotes = notes.filter((r) => r.baselineState === 'new').length;
570
+ const missingNotes = notes.length === 0 ? '' : `, ${count(notes.length, 'missing changes note')}${newNotes > 0 ? ` (${newNotes} new)` : ''}`;
571
+ console.error(`delurio check: ${count(graphs, 'graph')}, ${count(errors, 'error')}, ${count(warnings, 'warning')}${gaps}${missingNotes}; exit ${exitCode}`);
375
572
  }
376
573
  return exitCode;
377
574
  }
package/dist/diff-nav.js CHANGED
@@ -36,12 +36,20 @@ function entryWords(g, s) {
36
36
  return `${s.how} ${label} on ${fromWords(g, s)}`;
37
37
  }
38
38
  const entryKey = (s) => `entry ${s.id ?? `${fromTokens(s).join(', ')} → ${s.to} (${s.how})`}`;
39
- const pathWords = (v, page) => {
39
+ const pathWords = (g, v, page) => {
40
40
  const words = pathTo(v.reach, page).filter((e) => e.label !== '').map((e) => e.label);
41
+ // a way that starts at a page opened by its address (SPEC.md §6)
42
+ const typed = v.reach.get(page)?.byAddress ?? null;
43
+ if (typed !== null) {
44
+ if (typed === page)
45
+ return 'by its address';
46
+ const at = g.pages[typed] === undefined ? typed : quote(g.pages[typed].title);
47
+ return `by the address of ${at}${words.length === 0 ? '' : `, then ${words.join(' → ')}`}`;
48
+ }
41
49
  return words.length === 0 ? 'automatic' : words.join(' → ');
42
50
  };
43
51
  function pageFields(p) {
44
- return { route: p.route, title: p.titleKey ?? p.title, kind: p.kind, frame: p.frame, opensFor: p.opensFor ?? undefined, refusal: p.refusal ?? undefined, pageCodes: p.pageCodes ?? undefined, source: p.source ?? undefined, evidence: p.evidence ?? undefined };
52
+ return { route: p.route, title: p.titleKey ?? p.title, kind: p.kind, frame: p.frame, opensFor: p.opensFor ?? undefined, refusal: p.refusal ?? undefined, byAddress: p.byAddress ? true : undefined, pageCodes: p.pageCodes ?? undefined, source: p.source ?? undefined, evidence: p.evidence ?? undefined };
45
53
  }
46
54
  export function navStructure(b, a) {
47
55
  const out = [];
@@ -141,7 +149,7 @@ export function navStructure(b, a) {
141
149
  continue;
142
150
  }
143
151
  const name = pageName(ga, id);
144
- out.push(...fieldChanges('pages', key, pageFields(x), pageFields(y), ['route', 'title', 'kind', 'frame', 'opensFor', 'refusal', 'pageCodes', 'source', 'evidence'], (f, p, q) => {
152
+ out.push(...fieldChanges('pages', key, pageFields(x), pageFields(y), ['route', 'title', 'kind', 'frame', 'opensFor', 'refusal', 'byAddress', 'pageCodes', 'source', 'evidence'], (f, p, q) => {
145
153
  if (f === 'route')
146
154
  return `${name} moved to ${String(q)} (was ${String(p)}).`;
147
155
  if (f === 'title')
@@ -154,6 +162,8 @@ export function navStructure(b, a) {
154
162
  return q === undefined ? `${name} now opens for everyone.` : p === undefined ? `${name} now opens only for some people.` : `Who ${name} opens for changed.`;
155
163
  if (f === 'refusal')
156
164
  return q === undefined ? `${name} no longer says how it refuses.` : `${name} now refuses with: ${quote(String(q))}.`;
165
+ if (f === 'byAddress')
166
+ return q === true ? `${name} is now opened by its address.` : `${name} is no longer opened by its address.`;
157
167
  return null;
158
168
  }));
159
169
  }
@@ -299,7 +309,7 @@ export function navBehaviour(rb, ra, s) {
299
309
  const name = ga.pages[page] === undefined ? pageName(gb, page) : pageName(ga, page);
300
310
  if (!inB && inA) {
301
311
  const st = va.standing[page];
302
- add('page', page, null, { clicks: va.reach.get(page)?.clicks, standing: st }, `Can now reach ${name}${st === 'ok' ? '' : `, which ${STANDING_WORDS[st]}`} (${va.reach.get(page)?.clicks ?? 0} clicks: ${pathWords(va, page)}).`);
312
+ add('page', page, null, { clicks: va.reach.get(page)?.clicks, standing: st }, `Can now reach ${name}${st === 'ok' ? '' : `, which ${STANDING_WORDS[st]}`} (${va.reach.get(page)?.clicks ?? 0} clicks: ${pathWords(ga, va, page)}).`);
303
313
  }
304
314
  else if (inB && !inA) {
305
315
  add('page', page, { clicks: vb.reach.get(page)?.clicks, standing: vb.standing[page] }, null, `Can no longer reach ${name}${ga.pages[page] === undefined ? ' (the page was removed)' : ''}.`);
@@ -312,7 +322,7 @@ export function navBehaviour(rb, ra, s) {
312
322
  const cb = vb.reach.get(page)?.clicks ?? 0;
313
323
  const ca = va.reach.get(page)?.clicks ?? 0;
314
324
  if (cb !== ca)
315
- add('clicks', page, cb, ca, `${capital(name)}: ${cb} → ${ca} ${ca === 1 ? 'click' : 'clicks'} (${pathWords(va, page)}).`);
325
+ add('clicks', page, cb, ca, `${capital(name)}: ${cb} → ${ca} ${ca === 1 ? 'click' : 'clicks'} (${pathWords(ga, va, page)}).`);
316
326
  }
317
327
  }
318
328
  // the menu they see
@@ -0,0 +1,18 @@
1
+ import type { DomainPart } from './domain.ts';
2
+ export interface NamePlace {
3
+ file: string;
4
+ line: number;
5
+ column: number;
6
+ }
7
+ export interface NameProblem extends NamePlace {
8
+ rule: 'entity-unknown' | 'field-unknown' | 'policy-unknown';
9
+ message: string;
10
+ element: string;
11
+ notes: Array<NamePlace & {
12
+ message: string;
13
+ }>;
14
+ }
15
+ export type EntityElsewhere = (entity: string) => (NamePlace & {
16
+ domain: string;
17
+ }) | null;
18
+ export declare function checkDomainNames(parts: DomainPart[], doc: Record<string, unknown>, id: string, elsewhere?: EntityElsewhere): NameProblem[];
@@ -0,0 +1,124 @@
1
+ // The names a domain gives one another (SPEC.md §5), each held to what the domain has, all its files read as one: an
2
+ // action's `returns` and every `references` (on an entity's field, or in a body, a query, a result or a refusal's body)
3
+ // name an entity; an entity's `key` and `required` name its own fields; a policy's `do` names actions, and its `read`
4
+ // and `write` entities. A name that the domain does not have is an error, as a flow's `invoke` names are (decided on
5
+ // 16 Nov 2026, d-1116-10). Each finding is given in the file that gives the name, at its line, with a note where another
6
+ // domain beside it has the entity: a domain names only its own, and one domain may be split across files instead.
7
+ import { readYaml, keyAt } from './yaml.js';
8
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
+ // the keywords of JSON Schema 2020-12 whose value is a schema, a list of schemas, or schemas by name; a value of any
10
+ // other keyword (`examples`, `default`, `const`, `enum`) is data, never read for `references`
11
+ const ONE = ['items', 'contains', 'not', 'if', 'then', 'else', 'additionalProperties', 'propertyNames', 'unevaluatedItems', 'unevaluatedProperties', 'contentSchema'];
12
+ const LIST = ['allOf', 'anyOf', 'oneOf', 'prefixItems'];
13
+ const BY_NAME = ['properties', 'patternProperties', '$defs', 'dependentSchemas'];
14
+ // every `references` in a schema, with the path to the schema that gives it
15
+ function referencesIn(schema, path, out = []) {
16
+ if (!isObject(schema))
17
+ return out;
18
+ if (schema.references !== undefined)
19
+ out.push({ path, name: schema.references });
20
+ for (const k of ONE)
21
+ referencesIn(schema[k], [...path, k], out);
22
+ for (const k of LIST)
23
+ if (Array.isArray(schema[k]))
24
+ schema[k].forEach((s, i) => referencesIn(s, [...path, k, String(i)], out));
25
+ for (const k of BY_NAME)
26
+ if (isObject(schema[k]))
27
+ for (const [name, s] of Object.entries(schema[k]))
28
+ referencesIn(s, [...path, k, name], out);
29
+ return out;
30
+ }
31
+ // a schema's path inside the value it sits in, for a message: properties.address.properties.city -> address.city
32
+ const inside = (path) => path.map((s, i) => (path[i - 1] === 'properties' ? s : s === 'properties' ? '' : s)).filter((s) => s !== '').join('.');
33
+ // `doc` is the domain's files read as one (mergeDomain); `parts` the files, each read again here for where it gives a name
34
+ export function checkDomainNames(parts, doc, id, elsewhere = () => null) {
35
+ const entities = isObject(doc.entities) ? doc.entities : {};
36
+ const actions = isObject(doc.actions) ? doc.actions : {};
37
+ const isEntity = (name) => Object.hasOwn(entities, name);
38
+ const isAction = (name) => Object.hasOwn(actions, name);
39
+ const fieldsOf = (entity) => {
40
+ const e = entities[entity];
41
+ return isObject(e) && isObject(e.fields) ? e.fields : null;
42
+ };
43
+ const out = [];
44
+ for (const part of parts) {
45
+ let data;
46
+ try {
47
+ data = readYaml(part.text);
48
+ }
49
+ catch {
50
+ continue;
51
+ }
52
+ // a file that is not a map, or is another domain's (domain-place), is no part of this one
53
+ if (!isObject(data) || (typeof data.id === 'string' && data.id !== id))
54
+ continue;
55
+ const at = (rule, path, message, element, entity) => {
56
+ const other = entity === undefined ? null : elsewhere(entity);
57
+ const notes = other === null ? [] : [{ file: other.file, line: other.line, column: other.column, message: `${entity} is an entity of the domain ${other.domain}: a domain names only its own entities, and one domain may be split across the files of its directory (SPEC.md §5)` }];
58
+ out.push({ rule, file: part.file, ...keyAt(part.text, path), message, element, notes });
59
+ };
60
+ const references = (schema, path, where) => {
61
+ for (const r of referencesIn(schema, path)) {
62
+ if (typeof r.name !== 'string' || isEntity(r.name))
63
+ continue;
64
+ const rest = inside(r.path.slice(path.length));
65
+ at('entity-unknown', [...r.path, 'references'], `${where(rest)} references ${r.name}, which is not an entity of the domain ${id} (SPEC.md §5)`, `${r.path.join('/')}/references`, r.name);
66
+ }
67
+ };
68
+ for (const [entity, e] of Object.entries(isObject(data.entities) ? data.entities : {})) {
69
+ if (!isObject(e))
70
+ continue;
71
+ // an entity whose fields no file gives yet is not held to them
72
+ const fields = fieldsOf(entity);
73
+ for (const key of ['key', 'required']) {
74
+ if (fields === null || !Array.isArray(e[key]))
75
+ continue;
76
+ e[key].forEach((name, i) => {
77
+ if (typeof name !== 'string' || Object.hasOwn(fields, name))
78
+ return;
79
+ const said = key === 'key' ? `the key of the entity ${entity} names ${name}` : `the entity ${entity} requires ${name}`;
80
+ at('field-unknown', ['entities', entity, key, String(i)], `${said}, which is not one of its fields (SPEC.md §5)`, `entities/${entity}/${key}/${name}`);
81
+ });
82
+ }
83
+ for (const [field, schema] of Object.entries(isObject(e.fields) ? e.fields : {})) {
84
+ references(schema, ['entities', entity, 'fields', field], (rest) => `the field ${entity}.${field}${rest === '' ? '' : `, at ${rest},`}`);
85
+ }
86
+ }
87
+ for (const [action, a] of Object.entries(isObject(data.actions) ? data.actions : {})) {
88
+ if (!isObject(a))
89
+ continue;
90
+ const result = a.result;
91
+ if (isObject(result) && typeof result.returns === 'string' && !isEntity(result.returns)) {
92
+ at('entity-unknown', ['actions', action, 'result', 'returns'], `the action ${action} returns ${result.returns}, which is not an entity of the domain ${id} (SPEC.md §5)`, `actions/${action}/result/returns`, result.returns);
93
+ }
94
+ for (const section of ['query', 'body', 'result']) {
95
+ references(a[section], ['actions', action, section], (rest) => `the ${section} of the action ${action}${rest === '' ? '' : `, at ${rest},`}`);
96
+ }
97
+ for (const [code, r] of Object.entries(isObject(a.refusals) ? a.refusals : {})) {
98
+ if (isObject(r))
99
+ references(r.body, ['actions', action, 'refusals', code, 'body'], (rest) => `the body of the refusal ${code} of the action ${action}${rest === '' ? '' : `, at ${rest},`}`);
100
+ }
101
+ }
102
+ // the policies of this file, by their place in it; the element names the policy by its actor, as the list's order
103
+ // across files is no part of what it is
104
+ (Array.isArray(data.policies) ? data.policies : []).forEach((p, i) => {
105
+ if (!isObject(p))
106
+ return;
107
+ const actor = typeof p.actor === 'string' ? p.actor : String(i);
108
+ for (const key of ['do', 'read', 'write']) {
109
+ if (!Array.isArray(p[key]))
110
+ continue;
111
+ p[key].forEach((name, j) => {
112
+ if (typeof name !== 'string')
113
+ return;
114
+ const known = key === 'do' ? isAction(name) : isEntity(name);
115
+ if (known)
116
+ return;
117
+ const what = key === 'do' ? 'an action' : 'an entity';
118
+ at('policy-unknown', ['policies', String(i), key, String(j)], `the policy for ${actor} names ${name} in ${key}, which is not ${what} of the domain ${id} (SPEC.md §5)`, `policies/${actor}/${key}/${name}`, key === 'do' ? undefined : name);
119
+ });
120
+ }
121
+ });
122
+ }
123
+ return out;
124
+ }
package/dist/domain.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // number, a list) is given in one file only. A split lets a generated part and a hand-written part sit side by side.
5
5
  import { keyAt, readYaml } from './yaml.js';
6
6
  // the files whose name says another kind (SPEC.md §1); only the others are read to see whether they are a domain
7
- export const OTHER_KINDS = new Set(['flow.yaml', 'ui.yaml', 'nav.yaml', 'nav.extracted.yaml', 'binding.yaml', 'tutorial.yaml', 'kit.yaml', 'anchors.lock.yaml']);
7
+ export const OTHER_KINDS = new Set(['flow.yaml', 'ui.yaml', 'nav.yaml', 'nav.extracted.yaml', 'binding.yaml', 'tutorial.yaml', 'kit.yaml', 'needs.yaml', 'needs.gaps.yaml', 'anchors.lock.yaml']);
8
8
  const OWN = new Set(['schema', 'kind', 'id']);
9
9
  const JOINED = new Set(['policies', 'invariants']);
10
10
  // a file that may be part of a domain, by its name