@mark1russell7/canon-ontology 0.2.0 → 0.4.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/build/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { arrayOf, booleanOf, isRecord, numberOf, readArray, readText, recordOf, textOf, timeOf } from "@mark1russell7/optional/read";
2
- import { A as kindOfId, C as kindOf, D as ONTOLOGY_FOLDER, E as GRAMMAR_FILE, F as repositoryId, M as npmPackageId, N as npmPurl, O as RECORD_SCHEMA_FILE, P as pathOfId, S as isLive, T as relationOf, _ as readScope, a as SIZES, b as edgesOf, c as targetsOf, d as hasFullScope, f as resultClaimsOf, g as inScope, h as canonicalScope, i as PLACES_SHOWN, j as makeId, k as idPart, l as CLAIM_STATUSES, m as SCOPE_MODULUS_LIMIT, n as NECESSARY_GATES, o as compareTargets, p as scopeOf, r as ONTOLOGY_REPOSITORY, s as targetId, u as claimFails, v as sameScope, w as lineageOf, x as isKindIn, y as scopeText } from "./targets-DsUgzuOM.mjs";
2
+ import { A as GRAMMAR_FILE, C as scopeText, D as kindOf, E as isLive, F as makeId, I as npmPackageId, L as npmPurl, M as RECORD_SCHEMA_FILE, N as idPart, O as lineageOf, P as kindOfId, R as pathOfId, S as sameScope, T as isKindIn, _ as scopeOf, a as SIZES, b as inScope, c as targetsOf, d as leanKey, f as problemIdOf, g as resultClaimsOf, h as hasFullScope, i as PLACES_SHOWN, j as ONTOLOGY_FOLDER, k as relationOf, l as findProblem, m as claimFails, n as NECESSARY_GATES, o as compareTargets, p as CLAIM_STATUSES, r as ONTOLOGY_REPOSITORY, s as targetId, u as formalKeyOf, v as SCOPE_MODULUS_LIMIT, w as edgesOf, x as readScope, y as canonicalScope, z as repositoryId } from "./targets-BwC2nZGy.mjs";
3
+ import { a as applyBoard, c as decideClaim, d as planBoard, f as targetOfIssue, i as actionComment, l as isExpired, n as CLAIM_HOURS, o as claimCommandOf, r as TARGET_LABEL, s as claimEnd, t as BOARD_LIMIT, u as issueText } from "./board-DAKpkjvV.mjs";
3
4
  import { Ajv2020 } from "ajv/dist/2020.js";
4
5
  import formats from "ajv-formats";
5
6
  import { countOf, listOf } from "@mark1russell7/text/english";
@@ -7,12 +8,17 @@ import { compareCodeUnits } from "@mark1russell7/text/order";
7
8
  import { dirname, join, relative } from "node:path";
8
9
  import { HOMES, OWNERS, reposOf } from "@mark1russell7/conventions";
9
10
  import { findFiles, findUp, toPosix } from "@mark1russell7/files";
11
+ import { staleGenerated, writeGenerated } from "@mark1russell7/ontology/node";
12
+ import { spineRegistry, spineRelations } from "@mark1russell7/ontology";
13
+ import { errorMessage } from "@mark1russell7/text";
14
+ import { isDeepStrictEqual } from "node:util";
15
+ import { z } from "zod";
10
16
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
17
  import { createRequire } from "node:module";
12
- import { errorMessage } from "@mark1russell7/text";
13
18
  import { redactSecrets } from "@mark1russell7/text/redact";
14
19
  import { fetchTransport, send } from "polite-crawler/api";
15
20
  import { HostScheduler, realClock } from "polite-crawler/politeness";
21
+ import { utcText } from "@mark1russell7/algebra/clock";
16
22
  import { parse } from "yaml";
17
23
  // src/atlas.ts
18
24
  /** The URL of the data of the duplication atlas. */
@@ -217,229 +223,6 @@ function recordsFromAtlas(atlas, repositories, mapRecords) {
217
223
  skipped: [...skipped].sort()
218
224
  };
219
225
  }
220
- // src/board.ts
221
- /** The label of each issue of the board. */
222
- const TARGET_LABEL = "target";
223
- /** The time of a claim with no pull request, in hours. */
224
- const CLAIM_HOURS = 48;
225
- /** The most open issues of the board. */
226
- const BOARD_LIMIT = 20;
227
- /** The start of the hidden line of an issue body that has the id of its target. */
228
- const MARK = "<!-- canon-target: ";
229
- /** The end of the hidden line. */
230
- const MARK_END = " -->";
231
- /** This function gives the id of the target of an issue body, or undefined when the body has no hidden line. */
232
- function targetOfIssue(body) {
233
- const start = body.indexOf(MARK);
234
- if (start < 0) return void 0;
235
- const end = body.indexOf(MARK_END, start + 19);
236
- const id = end < 0 ? "" : body.slice(start + 19, end).trim();
237
- return id === "" || /\s/.test(id) ? void 0 : id;
238
- }
239
- /** This function gives the time of the end of a claim, as an ISO 8601 text to the minute. */
240
- function claimEnd(claimedAt) {
241
- return `${new Date(claimedAt + 1728e5).toISOString().slice(0, 16)}Z`;
242
- }
243
- /** This function tells if a claim is older than `CLAIM_HOURS`. A claim with no known start is live. */
244
- function isExpired(issue, now) {
245
- return issue.assignees.length > 0 && issue.claimedAt !== void 0 && now - issue.claimedAt >= 1728e5;
246
- }
247
- /** This function gives the title, the body and the labels of the issue of a target. */
248
- function issueText(target, repository = ONTOLOGY_REPOSITORY) {
249
- const { attrs } = target;
250
- const path = pathOfId(target.id);
251
- const body = [
252
- `${MARK}${target.id}${MARK_END}`,
253
- `**Target:** \`${target.id}\``,
254
- "",
255
- "| Gap | Home | Size | Area |",
256
- "| --- | --- | --- | --- |",
257
- `| \`${attrs.gap}\` | [${attrs.home}](https://github.com/${attrs.home}) | ${attrs.size} | ${attrs.area === void 0 ? "" : `\`${attrs.area}\``} |`,
258
- "",
259
- "## Acceptance",
260
- "",
261
- attrs.acceptance.text,
262
- "",
263
- ...attrs.acceptance.checks.map((check) => `- [ ] ${check}`),
264
- "",
265
- "## Why",
266
- "",
267
- attrs.why,
268
- "",
269
- "## Claim and close",
270
- "",
271
- `1. Write the comment \`/claim\` on this issue. A claim stops after ${String(48)} hours with no open pull request.`,
272
- `2. Do the work. [\`AGENTS.md\`](https://github.com/${repository}/blob/main/AGENTS.md) tells how.`,
273
- `3. In the pull request, write the line \`Target: ${target.id}\`.`,
274
- "",
275
- `The record of the target is [\`${path}\`](https://github.com/${repository}/blob/main/${path}). Write \`/unclaim\` to stop your claim.`,
276
- ""
277
- ].join("\n");
278
- return {
279
- title: attrs.title,
280
- body,
281
- labels: [TARGET_LABEL, `gap:${attrs.gap}`]
282
- };
283
- }
284
- /** This function tells if an issue has the text of a target: the same title, body and labels. */
285
- function sameText(issue, text) {
286
- const labels = [...issue.labels].sort();
287
- const wanted = [...text.labels].sort();
288
- return issue.title === text.title && issue.body === text.body && labels.length === wanted.length && labels.every((label, index) => label === wanted[index]);
289
- }
290
- /**
291
- * This function gives the steps that make the board agree with the target query.
292
- *
293
- * - The board keeps the open issue of each claimable target. It adds other claimable targets, up to the limit. An issue
294
- * does not close because new targets come before it.
295
- * - Each added target is the first claimable target of the gap with the fewest targets on the board. So one gap with
296
- * many targets does not fill the board.
297
- * - An issue whose target is not claimable closes: `completed` when the target is gone, else `not_planned`.
298
- * - A claim older than `CLAIM_HOURS` stops when no open pull request names its target.
299
- * - An issue with no hidden line is not an issue of the board. Of two issues of one target, the board uses the first.
300
- */
301
- function planBoard(input) {
302
- const limit = input.limit ?? 20;
303
- const known = new Set(input.targets.map((target) => target.id));
304
- const claimable = input.targets.filter((target) => target.attrs.claimable);
305
- const byTarget = /* @__PURE__ */ new Map();
306
- for (const issue of [...input.issues].sort((a, b) => a.number - b.number)) {
307
- const id = targetOfIssue(issue.body);
308
- if (id !== void 0 && !byTarget.has(id)) byTarget.set(id, issue);
309
- }
310
- const board = new Set(claimable.filter((target) => byTarget.get(target.id)?.state === "open").map((target) => target.id));
311
- const gaps = /* @__PURE__ */ new Map();
312
- for (const target of claimable) if (board.has(target.id)) gaps.set(target.attrs.gap, (gaps.get(target.attrs.gap) ?? 0) + 1);
313
- const waiting = claimable.filter((target) => !board.has(target.id));
314
- while (board.size < limit && waiting.length > 0) {
315
- let best = 0;
316
- for (let index = 1; index < waiting.length; index += 1) if ((gaps.get(waiting[index]?.attrs.gap ?? "") ?? 0) < (gaps.get(waiting[best]?.attrs.gap ?? "") ?? 0)) best = index;
317
- const [next] = waiting.splice(best, 1);
318
- if (next === void 0) break;
319
- board.add(next.id);
320
- gaps.set(next.attrs.gap, (gaps.get(next.attrs.gap) ?? 0) + 1);
321
- }
322
- const actions = [];
323
- for (const target of claimable.filter((candidate) => board.has(candidate.id))) {
324
- const text = issueText(target);
325
- const issue = byTarget.get(target.id);
326
- if (issue === void 0) {
327
- actions.push({
328
- kind: "create",
329
- target: target.id,
330
- text
331
- });
332
- continue;
333
- }
334
- if (issue.state === "closed" || !sameText(issue, text)) actions.push({
335
- kind: "update",
336
- number: issue.number,
337
- target: target.id,
338
- text,
339
- reopen: issue.state === "closed"
340
- });
341
- if (issue.state === "open" && isExpired(issue, input.now) && !input.pulls.has(target.id)) actions.push({
342
- kind: "release",
343
- number: issue.number,
344
- target: target.id,
345
- users: issue.assignees
346
- });
347
- }
348
- for (const [target, issue] of byTarget) if (issue.state === "open" && !board.has(target)) actions.push({
349
- kind: "close",
350
- number: issue.number,
351
- target,
352
- reason: known.has(target) ? "not_planned" : "completed"
353
- });
354
- return actions;
355
- }
356
- /** The comment of a step of the board, or undefined for a step with no comment. */
357
- function actionComment(action) {
358
- if (action.kind === "release") return `The claim of ${action.users.map((user) => `\`${user}\``).join(", ")} stopped: ${String(48)} hours passed with no open pull request. Another contributor can claim the target now.`;
359
- if (action.kind === "close") return action.reason === "completed" ? "The target query does not give this target now, so the gap is closed." : "The target query does not give this target as claimable now. The issue opens again when the target is claimable.";
360
- }
361
- /** This function applies the steps of the board through the API, in their order. It gives the number of each new issue. */
362
- async function applyBoard(api, actions) {
363
- const labels = new Set(actions.flatMap((action) => action.kind === "create" || action.kind === "update" ? action.text.labels : []));
364
- if (labels.size > 0) await api.ensureLabels([...labels].sort());
365
- const created = [];
366
- for (const action of actions) {
367
- if (action.kind === "create") {
368
- created.push(await api.create(action.text));
369
- continue;
370
- }
371
- if (action.kind === "update") {
372
- const { title, body, labels: issueLabels } = action.text;
373
- await api.update(action.number, {
374
- title,
375
- body,
376
- labels: issueLabels,
377
- ...action.reopen ? {
378
- state: "open",
379
- stateReason: "reopened"
380
- } : {}
381
- });
382
- continue;
383
- }
384
- if (action.kind === "release") await api.update(action.number, { assignees: [] });
385
- const comment = actionComment(action);
386
- if (comment !== void 0) await api.comment(action.number, comment);
387
- if (action.kind === "close") await api.update(action.number, {
388
- state: "closed",
389
- stateReason: action.reason
390
- });
391
- }
392
- return created;
393
- }
394
- /** This function gives the command of a comment: its first word is `/claim` or `/unclaim`. */
395
- function claimCommandOf(comment) {
396
- const first = comment.trim().split(/\s/, 1)[0];
397
- return first === "/claim" ? "claim" : first === "/unclaim" ? "unclaim" : void 0;
398
- }
399
- /**
400
- * This function decides a claim comment. A contributor claims one target at a time, and a claim stops after
401
- * `CLAIM_HOURS` with no pull request. A claim that stopped does not block a new claim, also before the board removes it.
402
- */
403
- function decideClaim(input) {
404
- const { command, user, issue, target, now } = input;
405
- const who = `\`${user}\``;
406
- if (issue.state !== "open") return {
407
- kind: "refuse",
408
- comment: "This issue is closed, so its target has no claim."
409
- };
410
- if (target === void 0 || !target.attrs.claimable) return {
411
- kind: "refuse",
412
- comment: "The target of this issue is not claimable now. `AGENTS.md` tells which targets are claimable."
413
- };
414
- const has = issue.assignees.includes(user);
415
- if (command === "unclaim") return has ? {
416
- kind: "set",
417
- assignees: issue.assignees.filter((login) => login !== user),
418
- comment: `${who} stopped the claim. Another contributor can claim the target now.`
419
- } : {
420
- kind: "refuse",
421
- comment: `${who} has no claim on this target.`
422
- };
423
- const until = issue.claimedAt === void 0 ? "the end of the claim" : claimEnd(issue.claimedAt);
424
- if (has) return {
425
- kind: "refuse",
426
- comment: `${who} has the claim already, until ${until}.`
427
- };
428
- if (issue.assignees.length > 0 && !isExpired(issue, now)) return {
429
- kind: "refuse",
430
- comment: `${issue.assignees.map((login) => `\`${login}\``).join(", ")} has the claim until ${until}. Claim another target, or claim this target after that time.`
431
- };
432
- const other = input.issues.find((candidate) => candidate.number !== issue.number && candidate.state === "open" && candidate.assignees.includes(user) && !isExpired(candidate, now));
433
- if (other !== void 0) return {
434
- kind: "refuse",
435
- comment: `${who} has a claim on #${String(other.number)} already. Claim one target at a time. Write \`/unclaim\` on #${String(other.number)} to stop that claim.`
436
- };
437
- return {
438
- kind: "set",
439
- assignees: [user],
440
- comment: `${who} claims this target until ${claimEnd(now)}. Open the pull request before that time, with the line \`Target: ${target.id}\`.`
441
- };
442
- }
443
226
  // src/check.ts
444
227
  /** This function makes a validator of JSON Schema 2020-12 with the formats `uri` and `date-time`. */
445
228
  function makeAjv() {
@@ -538,6 +321,19 @@ function checkEnvelope(envelope, what, path, kinds, grammar, problems) {
538
321
  message: `${what}: ${field} names ${id}, which is not a record.`
539
322
  });
540
323
  }
324
+ if (!timesInOrder(envelope)) problems.push({
325
+ path,
326
+ message: `${what}: valid_from ${String(envelope.valid_from)} is after valid_to ${String(envelope.valid_to)}.`
327
+ });
328
+ }
329
+ /**
330
+ * This function tells if the `valid_from` of an envelope is not after its `valid_to`. The comparison uses the instants,
331
+ * so two times with different offsets compare correctly. The record schema refuses a time that is not valid.
332
+ */
333
+ function timesInOrder(envelope) {
334
+ const from = Date.parse(envelope.valid_from ?? "");
335
+ const to = Date.parse(envelope.valid_to ?? "");
336
+ return Number.isNaN(from) || Number.isNaN(to) || from <= to;
541
337
  }
542
338
  /** This function gives the key of a relation: the values of the parts of the key of its kind. The default key is the two ends. */
543
339
  /**
@@ -587,6 +383,24 @@ function checkScopes(ontology, problems) {
587
383
  }
588
384
  }
589
385
  }
386
+ /**
387
+ * This function examines the formal names (roadmap C12). Two live problems cannot have one Lean key, because a tool
388
+ * finds a problem by its formal name. A short name, for example `conjecture`, names many statements.
389
+ */
390
+ function checkFormalNames(ontology, problems) {
391
+ const first = /* @__PURE__ */ new Map();
392
+ for (const { path, record } of ontology.records) {
393
+ if (record.kind !== "problem" || !isLive(record)) continue;
394
+ const key = formalKeyOf(record);
395
+ if (key === void 0) continue;
396
+ const earlier = first.get(key);
397
+ if (earlier === void 0) first.set(key, record.id);
398
+ else problems.push({
399
+ path,
400
+ message: `The formal name ${key} is also the formal name of ${earlier}. Give the full name, with its namespaces.`
401
+ });
402
+ }
403
+ }
590
404
  function keyOf(edge, key) {
591
405
  return JSON.stringify(key.map((part) => part === "from" ? edge.from : part === "to" ? edge.to : edge.qualifiers[part] ?? null));
592
406
  }
@@ -703,6 +517,7 @@ function checkOntology(ontology) {
703
517
  } else facts.set(fact, edge.from);
704
518
  }
705
519
  checkScopes(ontology, problems);
520
+ checkFormalNames(ontology, problems);
706
521
  return problems.sort((a, b) => a.path === b.path ? 0 : a.path < b.path ? -1 : 1);
707
522
  }
708
523
  // src/clones.ts
@@ -816,6 +631,317 @@ function cloneReport(groups, records, floor = 200) {
816
631
  }
817
632
  return lines.join("\n");
818
633
  }
634
+ // src/engine.ts
635
+ /** The folder of the files that the engine generates from the grammar, relative to the root of the repository. */
636
+ const ENGINE_FOLDER = "schema/engine";
637
+ /** The options of the generation: the first line of each SQL file names the command that makes the files. */
638
+ const ENGINE_GENERATE_OPTIONS = { header: `-- Generated by \`pnpm canon engine --write\` from ${GRAMMAR_FILE}. Do not edit by hand.` };
639
+ /**
640
+ * The keywords of JSON Schema that the add-on gives to the engine. A test holds each keyword: ajv and the engine give
641
+ * the same verdict on each value of the test.
642
+ */
643
+ const ENGINE_KEYWORDS = /* @__PURE__ */ new Set([
644
+ "$ref",
645
+ "additionalProperties",
646
+ "anyOf",
647
+ "const",
648
+ "description",
649
+ "enum",
650
+ "format",
651
+ "items",
652
+ "maximum",
653
+ "minItems",
654
+ "minLength",
655
+ "minimum",
656
+ "oneOf",
657
+ "pattern",
658
+ "properties",
659
+ "required",
660
+ "type",
661
+ "uniqueItems"
662
+ ]);
663
+ /**
664
+ * The values of the keyword `format` that the add-on gives to the engine. In JSON Schema 2020-12, a format is only an
665
+ * annotation. So each field with a format also has a pattern, and each reader gives the same verdict. The format `uri`
666
+ * is not in the list: zod reads it as `z.url()`, which removes the spaces at the two ends of the value.
667
+ */
668
+ const ENGINE_FORMATS = /* @__PURE__ */ new Set(["date-time"]);
669
+ /** The error of a grammar rule that the engine cannot keep. Each problem has the path of the rule in the grammar. */
670
+ var EngineGrammarError = class extends Error {
671
+ /** The problems: one text for each rule that the engine cannot keep. */
672
+ problems;
673
+ constructor(problems) {
674
+ super(`The ontology engine cannot keep ${String(problems.length)} rules of ${GRAMMAR_FILE}:\n${problems.join("\n")}`);
675
+ this.name = "EngineGrammarError";
676
+ this.problems = problems;
677
+ }
678
+ };
679
+ /** This function tells if a value is a JSON object, not an array and not null. */
680
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
681
+ /** This function adds a problem for each keyword of a schema that the engine does not keep, also in the parts of the schema. */
682
+ function checkKeywords(schema, path, problems) {
683
+ if (!isObject(schema)) {
684
+ problems.push(`${path}: the engine keeps only a schema that is an object, not ${JSON.stringify(schema)}.`);
685
+ return;
686
+ }
687
+ const next = Object.keys(schema).filter((keyword) => ![
688
+ "anyOf",
689
+ "description",
690
+ "oneOf"
691
+ ].includes(keyword));
692
+ if ((schema["oneOf"] !== void 0 || schema["anyOf"] !== void 0) && next.length > 0) problems.push(`${path}: a schema with oneOf or anyOf has only a description next to it, not ${next.join(", ")}.`);
693
+ if ((schema["type"] === "object" || schema["properties"] !== void 0) && schema["additionalProperties"] !== false) problems.push(`${path}: the engine keeps only an object with additionalProperties false.`);
694
+ for (const [keyword, value] of Object.entries(schema)) {
695
+ const at = `${path}/${keyword}`;
696
+ if (!ENGINE_KEYWORDS.has(keyword)) problems.push(`${at}: the engine does not keep the keyword ${keyword}.`);
697
+ else if (keyword === "format" && !ENGINE_FORMATS.has(String(value))) problems.push(`${at}: the engine does not keep the format ${String(value)}.`);
698
+ else if (keyword === "additionalProperties" && value !== false) problems.push(`${at}: the engine keeps only additionalProperties false.`);
699
+ else if (keyword === "properties" && isObject(value)) for (const [name, part] of Object.entries(value)) checkKeywords(part, `${at}/${name}`, problems);
700
+ else if (keyword === "items") checkKeywords(value, at, problems);
701
+ else if ((keyword === "oneOf" || keyword === "anyOf") && Array.isArray(value)) value.forEach((part, index) => {
702
+ checkKeywords(part, `${at}/${String(index)}`, problems);
703
+ });
704
+ }
705
+ }
706
+ /** This function gives the zod shape of an object schema of the grammar: one zod schema for each property. */
707
+ function shapeOf(schema, grammar, path, problems) {
708
+ const { if: _if, then: _then, ...rest } = schema;
709
+ checkKeywords(rest, path, problems);
710
+ if (schema["type"] !== "object" || schema["additionalProperties"] !== false) problems.push(`${path}: the engine keeps only a closed object: type object and additionalProperties false.`);
711
+ const required = new Set(schema["required"] ?? []);
712
+ const shape = {};
713
+ for (const [name, part] of Object.entries(schema["properties"] ?? {})) {
714
+ const zod = z.fromJSONSchema({
715
+ ...part,
716
+ $defs: grammar.$defs
717
+ });
718
+ shape[name] = required.has(name) ? zod : zod.optional();
719
+ }
720
+ return shape;
721
+ }
722
+ /**
723
+ * This function gives the requirements of a kind from the keywords `if` and `then` of its attributes. The engine keeps
724
+ * one form: when each property of `if` has its `const` value, each property of `then` is necessary.
725
+ */
726
+ function requirementsOf(schema, path, problems) {
727
+ const condition = schema["if"];
728
+ const result = schema["then"];
729
+ if (condition === void 0 && result === void 0) return [];
730
+ const form = `${path}: the engine keeps only the form if {properties: {name: {const}}, required} then {description, required}`;
731
+ if (!isObject(condition) || !isObject(result) || schema["else"] !== void 0) {
732
+ problems.push(`${form}.`);
733
+ return [];
734
+ }
735
+ const when = {};
736
+ const properties = condition["properties"];
737
+ const names = isObject(properties) ? Object.keys(properties) : [];
738
+ for (const name of names) {
739
+ const part = properties[name];
740
+ const value = isObject(part) && Object.keys(part).length === 1 ? part["const"] : void 0;
741
+ if (value === void 0 || typeof value === "object" && value !== null) problems.push(`${form}: ${name} has no const value.`);
742
+ else when[name] = value;
743
+ }
744
+ const conditionKeys = Object.keys(condition).sort().join(",");
745
+ const conditionRequired = [...condition["required"] ?? []].sort().join(",");
746
+ if (conditionKeys !== "properties,required" || conditionRequired !== [...names].sort().join(",")) problems.push(`${form}: the if part has other keywords.`);
747
+ const then = result["required"] ?? [];
748
+ const thenProperties = result["properties"];
749
+ const extra = Object.keys(result).filter((keyword) => ![
750
+ "description",
751
+ "properties",
752
+ "required"
753
+ ].includes(keyword));
754
+ const loose = isObject(thenProperties) ? Object.entries(thenProperties).filter(([name, part]) => part !== true || !then.includes(name)) : [];
755
+ if (typeof result["description"] !== "string" || then.length === 0 || extra.length > 0 || loose.length > 0) problems.push(`${form}: the then part has other keywords or no description.`);
756
+ return [{
757
+ description: String(result["description"]),
758
+ when,
759
+ then
760
+ }];
761
+ }
762
+ /** This function gives the kind of canon as a kind of the engine. A kind with no parent is a kind of the root, entity. */
763
+ function kindOf$1(kind, grammar, problems) {
764
+ const path = `${GRAMMAR_FILE}#/kinds/${kind.name}/attributes`;
765
+ const requirements = requirementsOf(kind.attributes, path, problems);
766
+ return {
767
+ name: kind.name,
768
+ parent: kind.parent ?? "entity",
769
+ mode: kind.mode,
770
+ description: kind.description,
771
+ attributes: shapeOf(kind.attributes, grammar, path, problems),
772
+ ...kind.facets.length > 0 ? { facets: kind.facets } : {},
773
+ defaultScope: "public",
774
+ ...requirements.length > 0 ? { requirements } : {}
775
+ };
776
+ }
777
+ /** This function gives the relation kind of canon as a relation kind of the engine. */
778
+ function relationOf$1(relation, grammar, problems) {
779
+ const path = `${GRAMMAR_FILE}#/relations/${relation.name}/qualifiers`;
780
+ return {
781
+ name: relation.name,
782
+ description: relation.description,
783
+ from: relation.from,
784
+ to: relation.to,
785
+ ...relation.parent === void 0 ? {} : { parent: relation.parent },
786
+ ...relation.qualifiers === void 0 ? {} : { qualifiers: shapeOf(relation.qualifiers, grammar, path, problems) },
787
+ ...relation.symmetric === void 0 ? {} : { symmetric: relation.symmetric },
788
+ ...relation.transitive === void 0 ? {} : { transitive: relation.transitive },
789
+ ...relation.abstract === void 0 ? {} : { abstract: relation.abstract },
790
+ ...relation.key === void 0 ? {} : { key: relation.key }
791
+ };
792
+ }
793
+ /**
794
+ * This function gives a relation kind of canon with the name of a relation kind of the engine as an extension. The
795
+ * extension adds each kind that the end of the engine does not have yet. The engine end can permit more kinds than canon.
796
+ */
797
+ function extensionOf(relation, spine, grammar, problems) {
798
+ if (relation.qualifiers !== void 0 || relation.key !== void 0 || relation.parent !== void 0) problems.push(`${GRAMMAR_FILE}#/relations/${relation.name}: a relation of the engine gets only more kinds at its ends.`);
799
+ const lineage = (name) => {
800
+ const kind = grammar.kinds.find((candidate) => candidate.name === name);
801
+ return kind === void 0 || kind.parent === null ? [name, "entity"] : [name, ...lineage(kind.parent)];
802
+ };
803
+ const missing = (kinds, allowed) => kinds.filter((kind) => !lineage(kind).some((ancestor) => allowed.includes(ancestor)));
804
+ const from = missing(relation.from, spine.from);
805
+ const to = missing(relation.to, spine.to);
806
+ return {
807
+ relation: relation.name,
808
+ ...from.length > 0 ? { from } : {},
809
+ ...to.length > 0 ? { to } : {}
810
+ };
811
+ }
812
+ /**
813
+ * This function gives the kinds and the relation kinds of the grammar as an add-on of the engine.
814
+ *
815
+ * @throws EngineGrammarError when the grammar has a rule that the engine cannot keep
816
+ */
817
+ function engineAddOn(grammar) {
818
+ const problems = [];
819
+ const facets = grammar.facets.map((facet) => ({
820
+ name: facet.name,
821
+ description: facet.description,
822
+ attributes: shapeOf(facet.attributes, grammar, `${GRAMMAR_FILE}#/facets/${facet.name}/attributes`, problems)
823
+ }));
824
+ for (const [name, schema] of Object.entries(grammar.$defs)) checkKeywords(schema, `${GRAMMAR_FILE}#/$defs/${name}`, problems);
825
+ const kinds = grammar.kinds.map((kind) => kindOf$1(kind, grammar, problems));
826
+ const relations = [];
827
+ const extensions = [];
828
+ for (const relation of grammar.relations) {
829
+ const spine = spineRelations.find((candidate) => candidate.name === relation.name);
830
+ if (spine === void 0) relations.push(relationOf$1(relation, grammar, problems));
831
+ else extensions.push(extensionOf(relation, spine, grammar, problems));
832
+ }
833
+ if (problems.length > 0) throw new EngineGrammarError(problems);
834
+ return withoutInherited({
835
+ kinds,
836
+ relations,
837
+ ...facets.length > 0 ? { facets } : {},
838
+ ...extensions.length > 0 ? { extensions } : {}
839
+ });
840
+ }
841
+ /** The schema of an attribute that a kind of canon does not have: it refuses each value. */
842
+ const NO_VALUE = z.never().describe("A kind of canon has no value of this attribute of its parents.").optional();
843
+ /**
844
+ * This function narrows each kind to the attributes that canon gives it. In the engine, a kind also gets each attribute
845
+ * of its parents and their facets. Thus the root of the spine gives each kind of canon the attributes `name` and
846
+ * `notes`. The schema of canon has only its own attributes, so the kind refuses each other attribute.
847
+ *
848
+ * @throws EngineGrammarError when a kind gets requirements from its parents in the engine
849
+ */
850
+ function withoutInherited(input) {
851
+ const first = spineRegistry(input);
852
+ const problems = [];
853
+ const kinds = input.kinds.map((kind) => {
854
+ if (first.effectiveRequirements(kind.name).length !== (kind.requirements ?? []).length) problems.push(`${GRAMMAR_FILE}#/kinds/${kind.name}: the engine adds the requirements of the parents, and canon does not.`);
855
+ const inherited = Object.keys(first.effectiveShape(kind.name)).filter((name) => !Object.hasOwn(kind.attributes, name));
856
+ if (inherited.length === 0) return kind;
857
+ return {
858
+ ...kind,
859
+ attributes: {
860
+ ...kind.attributes,
861
+ ...Object.fromEntries(inherited.map((name) => [name, NO_VALUE]))
862
+ }
863
+ };
864
+ });
865
+ if (problems.length > 0) throw new EngineGrammarError(problems);
866
+ return {
867
+ ...input,
868
+ kinds
869
+ };
870
+ }
871
+ /**
872
+ * This function gives the registry of the engine with the spine and the kinds of canon.
873
+ *
874
+ * @throws EngineGrammarError when the grammar has a rule that the engine cannot keep
875
+ */
876
+ function engineRegistry(grammar) {
877
+ return spineRegistry(engineAddOn(grammar));
878
+ }
879
+ /** This function gives the names of the fields of two objects that do not have the same value. */
880
+ function changedFields(before, after) {
881
+ const left = new Map(Object.entries(before));
882
+ const right = new Map(Object.entries(after));
883
+ return [.../* @__PURE__ */ new Set([...left.keys(), ...right.keys()])].filter((name) => !isDeepStrictEqual(left.get(name), right.get(name))).sort();
884
+ }
885
+ /**
886
+ * This function loads each record and each relation into the engine. A record or a relation that the engine refuses is a
887
+ * problem. A value that the engine changes is also a problem: the load keeps each value. The engine adds only the scope
888
+ * `public`, the default scope of each kind of canon, to an envelope with no scope.
889
+ */
890
+ function loadIntoEngine(registry, records) {
891
+ const kinds = new Map(records.map(({ record }) => [record.id, record.kind]));
892
+ const entities = [];
893
+ const edges = [];
894
+ const problems = [];
895
+ const compare = (path, part, before, after) => {
896
+ const changed = changedFields(before, after);
897
+ if (changed.length > 0) problems.push(`${path}: the engine changes the ${part} ${changed.join(", ")}.`);
898
+ };
899
+ const refuse = (path, error) => {
900
+ problems.push(`${path}: ${errorMessage(error).replaceAll("\n", " ")}`);
901
+ };
902
+ for (const { path, record } of records) {
903
+ const envelope = record.envelope ?? {};
904
+ try {
905
+ const entity = registry.validateEntity({
906
+ id: record.id,
907
+ kind: record.kind,
908
+ attrs: { ...record.attrs },
909
+ envelope
910
+ });
911
+ compare(path, "attributes", record.attrs, entity.attrs);
912
+ compare(path, "envelope fields", {
913
+ scope: "public",
914
+ ...envelope
915
+ }, entity.envelope);
916
+ entities.push(entity);
917
+ } catch (error) {
918
+ refuse(path, error);
919
+ }
920
+ for (const edge of record.edges ?? []) {
921
+ const at = `${path} ${edge.type} ${edge.to}`;
922
+ const qualifiers = edge.qualifiers ?? {};
923
+ try {
924
+ const parsed = registry.validateEdge({
925
+ from: record.id,
926
+ type: edge.type,
927
+ to: edge.to,
928
+ qualifiers: { ...qualifiers },
929
+ envelope: edge.envelope ?? {}
930
+ }, (id) => kinds.get(id));
931
+ compare(at, "qualifiers", qualifiers, parsed.qualifiers);
932
+ compare(at, "envelope fields", edge.envelope ?? {}, parsed.envelope);
933
+ edges.push(parsed);
934
+ } catch (error) {
935
+ refuse(at, error);
936
+ }
937
+ }
938
+ }
939
+ return {
940
+ entities,
941
+ edges,
942
+ problems
943
+ };
944
+ }
819
945
  // src/homes.ts
820
946
  /** The id of the record of kind source for the map of homes. */
821
947
  const MAP_SOURCE_ID = "source.conventions-map";
@@ -827,16 +953,6 @@ const IMPORT_SOURCE_IDS = [MAP_SOURCE_ID, GITHUB_SOURCE_ID];
827
953
  const ENVELOPE = { source_ids: [MAP_SOURCE_ID] };
828
954
  /** The envelope of a repository that only the lists of GitHub name. */
829
955
  const GITHUB_ENVELOPE = { source_ids: [GITHUB_SOURCE_ID] };
830
- /**
831
- * This function gives the public form of a text of the map. It removes the ids of roadmap items, because they mean
832
- * nothing outside their repositories. The map itself keeps the ids.
833
- *
834
- * This function is a shortcut. It ends with the item C28 of `docs/ROADMAP.md`: when the notes of the map have no ids,
835
- * the import stops this removal.
836
- */
837
- function publicText(text) {
838
- return text.replace(/\s?Planned as item [A-Z]+[0-9]+\./g, "").replace(/\bthe program [A-Z]+[0-9]+ of\b/g, "the roadmap of").replace(/ \((?:[A-Z]{1,3}-?[0-9]{1,4}|[0-9]{1,2}-[0-9]{1,2})\)/g, "").trim();
839
- }
840
956
  /** This function gives the repository `owner/name` of a repository URL of npm, or undefined when it is not on GitHub. */
841
957
  function githubRepositoryOf(url) {
842
958
  const lower = url.toLowerCase();
@@ -956,9 +1072,9 @@ function recordsFromHomes(homes, facts) {
956
1072
  }]);
957
1073
  const attrs = {
958
1074
  title: home.title,
959
- covers: publicText(home.covers)
1075
+ covers: home.covers
960
1076
  };
961
- const note = home.note === void 0 ? "" : publicText(home.note);
1077
+ const note = home.note ?? "";
962
1078
  if (note !== "") attrs["note"] = note;
963
1079
  if (home.words.length > 0) attrs["words"] = home.words;
964
1080
  if (home.signatures !== void 0 && home.signatures.length > 0) attrs["signatures"] = home.signatures;
@@ -1394,16 +1510,42 @@ function globMatches(parts, name) {
1394
1510
  }
1395
1511
  return true;
1396
1512
  }
1397
- /** This function selects the jobs of each workflow with `pick`, and gives their files and their checks. */
1513
+ /** This function gives the path of the workflow of the same repository that the job calls (`uses: ./path`), or undefined. */
1514
+ function localCallOf(job) {
1515
+ return job.uses?.startsWith("./") === true ? job.uses.slice(2) : void 0;
1516
+ }
1517
+ /**
1518
+ * This function selects the jobs of each workflow with `pick`, and gives their files and their checks. A job that calls a
1519
+ * workflow of the same repository with a selected job is a selected job of its own workflow too. So a check that needs
1520
+ * the call (`CI OK` of `pull-request.yml`, for example) holds the gate.
1521
+ */
1398
1522
  function pickJobs(workflows, pick) {
1523
+ const jobs = workflows.flatMap((workflow) => workflow.jobs.filter(pick));
1524
+ const selected = new Set(jobs);
1525
+ const called = /* @__PURE__ */ new Set();
1526
+ let grew = true;
1527
+ while (grew) {
1528
+ grew = false;
1529
+ for (const workflow of workflows) {
1530
+ if (!called.has(workflow.path) && workflow.jobs.some((job) => selected.has(job))) {
1531
+ called.add(workflow.path);
1532
+ grew = true;
1533
+ }
1534
+ for (const job of workflow.jobs) {
1535
+ const call = localCallOf(job);
1536
+ if (!selected.has(job) && call !== void 0 && called.has(call)) {
1537
+ selected.add(job);
1538
+ grew = true;
1539
+ }
1540
+ }
1541
+ }
1542
+ }
1399
1543
  const files = [];
1400
1544
  const checks = /* @__PURE__ */ new Set();
1401
- const jobs = [];
1402
1545
  for (const workflow of workflows) {
1403
- const seeds = workflow.jobs.filter(pick);
1546
+ const seeds = workflow.jobs.filter((job) => selected.has(job));
1404
1547
  if (seeds.length === 0) continue;
1405
1548
  files.push(workflow.path);
1406
- jobs.push(...seeds);
1407
1549
  for (const check of checksOf(workflow, seeds)) checks.add(check);
1408
1550
  }
1409
1551
  return {
@@ -1521,9 +1663,11 @@ function gatesOf(tree, answers, rules) {
1521
1663
  }], rigsJobs.checks, rules)
1522
1664
  };
1523
1665
  }
1524
- /** This function gives the time of a read in the form of the records: UTC, to the second. */
1666
+ /** This function gives the time of a read in the form of the records: UTC, to the second (RFC 3339). */
1525
1667
  function timeText(ms) {
1526
- return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
1668
+ const text = utcText(ms);
1669
+ if (text === void 0) throw new RangeError(`The time ${String(ms)} of the read is not an instant in the years 1 to 9999.`);
1670
+ return text;
1527
1671
  }
1528
1672
  /** This function gives a no read for each gate. */
1529
1673
  function noReadOfEach(reason) {
@@ -1687,6 +1831,8 @@ Commands:
1687
1831
  results Show each claim that needs a result record, and its state: checked, partial or not checked.
1688
1832
  results --json Give the claims as JSON.
1689
1833
  results --check Exit code 1 when a claim is not checked, or a status claim is partial.
1834
+ engine Load each record into the ontology engine, and check the files of schema/engine/.
1835
+ engine --write Write the files that the engine makes from the grammar to schema/engine/.
1690
1836
  import Read the map of homes and the live facts, and write the records of the map.
1691
1837
  board Show the changes that make the target board agree with the target query.
1692
1838
  board --apply Make the changes: open, change and close the issues of the board.
@@ -1723,6 +1869,22 @@ function check(printer, ontology) {
1723
1869
  printer.status("ok", `${String(ontology.records.length)} records agree with the grammar.`);
1724
1870
  return 0;
1725
1871
  }
1872
+ /**
1873
+ * This function does the command `engine` (roadmap C18). It loads each record into the ontology engine, and it compares the
1874
+ * files of the engine with a new generation. It gives the exit code: 0 when the engine keeps each value and the files agree.
1875
+ */
1876
+ async function engine(printer, root, ontology, flags) {
1877
+ const registry = engineRegistry(ontology.grammar);
1878
+ const folder = join(root, ENGINE_FOLDER);
1879
+ if (flags.has("--write")) for (const name of await writeGenerated(registry, folder, ENGINE_GENERATE_OPTIONS)) printer.line(`write ${ENGINE_FOLDER}/${name}`);
1880
+ const load = loadIntoEngine(registry, ontology.records);
1881
+ for (const problem of load.problems) printer.status("fail", problem);
1882
+ const stale = await staleGenerated(registry, folder, ENGINE_GENERATE_OPTIONS);
1883
+ for (const name of stale) printer.status("fail", `${ENGINE_FOLDER}/${name} does not agree with the grammar. Start \`pnpm canon engine --write\`, and commit the files.`);
1884
+ if (load.problems.length > 0 || stale.length > 0) return 1;
1885
+ printer.status("ok", `The engine keeps each value of ${String(load.entities.length)} records and ${String(load.edges.length)} relations.`);
1886
+ return 0;
1887
+ }
1726
1888
  /** This function runs the command `results`. It gives the exit code. */
1727
1889
  function results(printer, ontology, flags) {
1728
1890
  const claims = resultClaimsOf(ontology);
@@ -1904,11 +2066,12 @@ async function claim(printer, ontology, args, options) {
1904
2066
  return 0;
1905
2067
  }
1906
2068
  const id = targetOfIssue(issue.body);
2069
+ const target = targetsOf(ontology).find((candidate) => candidate.id === id);
1907
2070
  const decision = decideClaim({
1908
2071
  command,
1909
2072
  user,
1910
2073
  issue,
1911
- target: targetsOf(ontology).find((candidate) => candidate.id === id),
2074
+ target,
1912
2075
  issues,
1913
2076
  now: (options.now ?? Date.now)()
1914
2077
  });
@@ -1939,7 +2102,7 @@ async function runCli(args, printer, cwd, options = {}) {
1939
2102
  }
1940
2103
  const root = rootArg ?? findRoot(cwd);
1941
2104
  if (root === void 0) {
1942
- printer.status("fail", `No ${GRAMMAR_FILE} in ${cwd} or a parent folder. Give --root <folder>.`);
2105
+ printer.status("fail", `No ${GRAMMAR_FILE} in ${cwd} or a parent folder. In an old clone of canon, start git pull or clone again. Else, give --root <folder>.`);
1943
2106
  return 2;
1944
2107
  }
1945
2108
  try {
@@ -1947,6 +2110,7 @@ async function runCli(args, printer, cwd, options = {}) {
1947
2110
  if (command === "check") return check(printer, ontology);
1948
2111
  if (command === "targets") return targets(printer, root, ontology, flags);
1949
2112
  if (command === "results") return results(printer, ontology, flags);
2113
+ if (command === "engine") return await engine(printer, root, ontology, flags);
1950
2114
  if (command === "import") return await importHomes(printer, root, ontology, options);
1951
2115
  if (command === "board") return await board(printer, ontology, flagList, options);
1952
2116
  if (command === "claim") return await claim(printer, ontology, flagList, options);
@@ -2126,6 +2290,6 @@ function githubIssueApi(client, repository, signal) {
2126
2290
  }
2127
2291
  };
2128
2292
  }
2129
- export { ATLAS_LIMIT, ATLAS_SCHEMA, ATLAS_SOURCE_ID, ATLAS_URL, BENCH_PACKAGE, BOARD_LIMIT, CLAIM_HOURS, CLAIM_STATUSES, CLONE_FLOOR, GATE_NAMES, GITHUB_SOURCE_ID, GRAMMAR_FILE, HOSTS_AT_ONCE, IMPORT_SOURCE_IDS, IssueApiError, MAP_SOURCE_ID, MUTATION_LANE, NECESSARY_GATES, ONTOLOGY_FOLDER, ONTOLOGY_REPOSITORY, OntologyReadError, PLACES_SHOWN, PROPERTY_PACKAGES, RECORD_SCHEMA_FILE, REPOSITORY_PAGES, RIGS_FILE, RULES_PAGE, SCOPE_MODULUS_LIMIT, SIZES, TARGET_LABEL, USAGE, USER_AGENT, actionComment, applyBoard, applyPlan, canonicalScope, checkMatches, checkOntology, claimCommandOf, claimEnd, claimFails, claimTimeOf, cloneGroups, cloneReport, compareTargets, conventionsVersion, decideClaim, edgesOf, fileUrl, filesToRead, findRoot, gateRepositoriesOf, gatesOf, githubIssueApi, githubRepositoryOf, hasFullScope, idPart, inScope, isEmptyPlan, isExpired, isKindIn, isLive, isPackagePath, isWorkflowPath, issueOfItem, issueText, kindOf, kindOfId, lineageOf, makeId, necessaryChecksOf, npmFactOf, npmLatestUrl, npmPackageId, npmPurl, pathOfId, planBoard, planWrite, politeFetch, publicText, readAtlas, readHomeFacts, readOntology, readScope, readTestGates, recordText, recordsFromAtlas, recordsFromHomes, relationOf, repositoriesOfPages, repositoryId, repositoryPageUrls, resultClaimsOf, rulesUrl, runCli, sameScope, scopeOf, scopeText, targetId, targetOfIssue, targetsOf, treeOf, treeUrl, withTestGates };
2293
+ export { ATLAS_LIMIT, ATLAS_SCHEMA, ATLAS_SOURCE_ID, ATLAS_URL, BENCH_PACKAGE, BOARD_LIMIT, CLAIM_HOURS, CLAIM_STATUSES, CLONE_FLOOR, ENGINE_FOLDER, ENGINE_FORMATS, ENGINE_GENERATE_OPTIONS, ENGINE_KEYWORDS, EngineGrammarError, GATE_NAMES, GITHUB_SOURCE_ID, GRAMMAR_FILE, HOSTS_AT_ONCE, IMPORT_SOURCE_IDS, IssueApiError, MAP_SOURCE_ID, MUTATION_LANE, NECESSARY_GATES, ONTOLOGY_FOLDER, ONTOLOGY_REPOSITORY, OntologyReadError, PLACES_SHOWN, PROPERTY_PACKAGES, RECORD_SCHEMA_FILE, REPOSITORY_PAGES, RIGS_FILE, RULES_PAGE, SCOPE_MODULUS_LIMIT, SIZES, TARGET_LABEL, USAGE, USER_AGENT, actionComment, applyBoard, applyPlan, canonicalScope, checkMatches, checkOntology, claimCommandOf, claimEnd, claimFails, claimTimeOf, cloneGroups, cloneReport, compareTargets, conventionsVersion, decideClaim, edgesOf, engineAddOn, engineRegistry, fileUrl, filesToRead, findProblem, findRoot, formalKeyOf, gateRepositoriesOf, gatesOf, githubIssueApi, githubRepositoryOf, hasFullScope, idPart, inScope, isEmptyPlan, isExpired, isKindIn, isLive, isPackagePath, isWorkflowPath, issueOfItem, issueText, kindOf, kindOfId, leanKey, lineageOf, loadIntoEngine, makeId, necessaryChecksOf, npmFactOf, npmLatestUrl, npmPackageId, npmPurl, pathOfId, planBoard, planWrite, politeFetch, problemIdOf, readAtlas, readHomeFacts, readOntology, readScope, readTestGates, recordText, recordsFromAtlas, recordsFromHomes, relationOf, repositoriesOfPages, repositoryId, repositoryPageUrls, resultClaimsOf, rulesUrl, runCli, sameScope, scopeOf, scopeText, targetId, targetOfIssue, targetsOf, timesInOrder, treeOf, treeUrl, withTestGates };
2130
2294
 
2131
2295
  //# sourceMappingURL=index.mjs.map