@mark1russell7/canon-ontology 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["compareText","kindOf","relationOf"],"sources":["../src/atlas.ts","../src/check.ts","../src/clones.ts","../src/engine.ts","../src/homes.ts","../src/polite.ts","../src/facts.ts","../src/load.ts","../src/test-gates.ts","../src/write.ts","../src/cli.ts","../src/github.ts"],"sourcesContent":["// The read of the duplication atlas of codeatlas into records of kind candidate.\nimport type { HomeAnswer } from \"@mark1russell7/conventions\";\nimport { arrayOf, booleanOf, numberOf, readText, textOf } from \"@mark1russell7/optional/read\";\nimport type { PublicRepository } from \"./homes.ts\";\nimport { makeId, repositoryId } from \"./ids.ts\";\nimport type { EntityRecord } from \"./types.ts\";\n\n/** The URL of the data of the duplication atlas. */\nexport const ATLAS_URL = \"https://metrograph-labs.github.io/codeatlas/data/atlas.json\";\n\n/** The id of the record of kind source for the duplication atlas. */\nexport const ATLAS_SOURCE_ID = \"source.codeatlas\";\n\n/** The schema of the atlas that this reader knows. The reader refuses an atlas with a different schema. */\nexport const ATLAS_SCHEMA = \"codeatlas/1\";\n\n/** The largest text of an atlas that the reader accepts, in characters. */\nexport const ATLAS_LIMIT: number = 32 * 1024 * 1024;\n\n/** A function of a repository that the atlas finds with the names of an area. */\nexport interface AtlasCopy {\n readonly repo: string;\n readonly file: string;\n readonly line: number;\n readonly name: string;\n}\n\n/** The functions that the atlas finds for one area of the map of homes. */\nexport interface AtlasRow {\n readonly area: string;\n readonly copies: readonly AtlasCopy[];\n}\n\n/** A repository that the atlas read, with its owner and the commit that it read. */\nexport interface AtlasRepository {\n readonly repo: string;\n readonly owner: string;\n readonly commit: string;\n}\n\n/** A class of cloned code: functions with the same shape in two or more places. */\nexport interface AtlasClass {\n /** The count of syntax nodes of one copy. */\n readonly nodes: number;\n /** The areas of the map of homes that the atlas finds for the class. */\n readonly areas: readonly string[];\n /** The copies. A function of a test file is not a copy. A function with no name has the name `<anonymous>`. */\n readonly members: readonly AtlasCopy[];\n}\n\n/** The parts of the atlas that canon uses. */\nexport interface Atlas {\n readonly repositories: readonly AtlasRepository[];\n readonly rows: readonly AtlasRow[];\n readonly classes: readonly AtlasClass[];\n}\n\n/** The result of a read of the atlas: the atlas, or the reason that the import cannot use it. */\nexport type AtlasRead = { readonly atlas: Atlas } | { readonly error: string };\n\n/** The result of the atlas import: the records of kind candidate and the source, and a text for each copy that it left out. */\nexport interface AtlasImport {\n readonly records: readonly EntityRecord[];\n readonly skipped: readonly string[];\n}\n\nconst COMMIT = /^[0-9a-f]{40}$/;\n\n/**\n * This function reads one function. It drops a function of a test file. It also drops a function with no name, unless\n * `anonymous` is true.\n */\nfunction copyOf(value: unknown, anonymous = false): AtlasCopy | undefined {\n const repo = textOf(value, \"repo\");\n const file = textOf(value, \"file\");\n const line = numberOf(value, \"line\");\n const name = textOf(value, \"name\");\n if (repo === undefined || file === undefined || line === undefined || name === undefined) return undefined;\n if (booleanOf(value, \"test\") !== false || !Number.isInteger(line) || line < 1 || name === \"\") return undefined;\n if (name.startsWith(\"<\") && (!anonymous || name !== \"<anonymous>\")) return undefined;\n return { repo, file, line, name };\n}\n\n/** This function reads one class of cloned code. It drops a class with a bad count of nodes. */\nfunction classOf(value: unknown): AtlasClass | undefined {\n const nodes = numberOf(value, \"nodes\");\n if (nodes === undefined || !Number.isInteger(nodes) || nodes < 1) return undefined;\n return { nodes, areas: arrayOf(value, \"homes\", readText) ?? [], members: arrayOf(value, \"members\", (member) => copyOf(member, true)) ?? [] };\n}\n\n/**\n * This function reads the answer of the fetch of the atlas. It gives an error for a failed fetch, a text of more than\n * `limit` characters and a text that is not JSON. A schema that is not `ATLAS_SCHEMA` also gives an error. It drops each\n * row with a bad field. An atlas with no list of classes has no classes.\n */\nexport function readAtlas(answer: HomeAnswer | undefined, limit: number = ATLAS_LIMIT): AtlasRead {\n if (answer === undefined) return { error: \"The fetch gave no answer for the atlas.\" };\n if (\"error\" in answer) return { error: `The fetch of the atlas gave the error ${answer.error}.` };\n if (answer.text.length > limit) return { error: `The atlas has more than ${String(limit)} characters.` };\n let data: unknown;\n try {\n data = JSON.parse(answer.text);\n } catch {\n return { error: \"The atlas is not JSON.\" };\n }\n const schema = textOf(data, \"schema\");\n if (schema !== ATLAS_SCHEMA) return { error: `The atlas has the schema ${schema ?? \"(none)\"}, not ${ATLAS_SCHEMA}.` };\n const repositories = arrayOf(data, \"repos\", (row): AtlasRepository | undefined => {\n const repo = textOf(row, \"repo\");\n const owner = textOf(row, \"owner\");\n const commit = textOf(row, \"commit\");\n return repo === undefined || owner === undefined || commit === undefined || !COMMIT.test(commit) ? undefined : { repo, owner, commit };\n });\n const rows = arrayOf(data, \"homed\", (row): AtlasRow | undefined => {\n const area = textOf(row, \"area\");\n return area === undefined ? undefined : { area, copies: arrayOf(row, \"copies\", copyOf) ?? [] };\n });\n if (repositories === undefined || rows === undefined) return { error: \"The atlas has no list of repositories or no list of homed rows.\" };\n return { atlas: { repositories, rows, classes: arrayOf(data, \"classes\", classOf) ?? [] } };\n}\n\n/** This function gives the repositories of each area that hold its own code: the home and each repository of a package of the area. */\nexport function ownRepositories(records: readonly EntityRecord[]): ReadonlyMap<string, ReadonlySet<string>> {\n const own = new Map<string, Set<string>>();\n const add = (area: string, repository: string): void => {\n const set = own.get(area) ?? new Set<string>();\n set.add(repository);\n own.set(area, set);\n };\n for (const record of records) {\n const edges = record.edges ?? [];\n if (record.kind === \"repository\") for (const edge of edges) if (edge.type === \"home-of\") add(edge.to, record.id);\n const partOf = edges.find((edge) => edge.type === \"part-of\")?.to;\n if (record.kind === \"package\" && partOf !== undefined) for (const edge of edges) if (edge.type === \"covers\") add(edge.to, partOf);\n }\n return own;\n}\n\n/** The repository of a name of the atlas and the commit that the atlas read, or the reason that there is none. */\nexport type AtlasFound = { readonly repository: PublicRepository; readonly commit: string } | { readonly why: string };\n\n/**\n * This function gives a function that finds the repository of a name of the atlas. It finds the repository under the\n * owner that the atlas names, or under the one owner that has a repository of that name. A fork and an archived\n * repository are not found.\n */\nexport function repositoryFinder(atlas: Atlas, repositories: readonly PublicRepository[]): (repo: string) => AtlasFound {\n const live = repositories.filter((repository) => repository.fork !== true && repository.archived !== true);\n const byFullName = new Map(live.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository]));\n const byName = new Map<string, PublicRepository[]>();\n for (const repository of live) byName.set(repository.name.toLowerCase(), [...(byName.get(repository.name.toLowerCase()) ?? []), repository]);\n const read = new Map(atlas.repositories.map((row) => [row.repo.toLowerCase(), row]));\n return (repo) => {\n const scan = read.get(repo.toLowerCase());\n const named = byName.get(repo.toLowerCase()) ?? [];\n const found = (scan === undefined ? undefined : byFullName.get(`${scan.owner}/${repo}`.toLowerCase())) ?? (named.length === 1 ? named[0] : undefined);\n if (scan !== undefined && found !== undefined) return { repository: found, commit: scan.commit };\n const why = scan === undefined ? \"the atlas has no commit for it\" : named.length > 1 ? \"two owners have a repository of that name\" : \"GitHub lists no public repository of that name that is not a fork and not archived\";\n return { why };\n };\n}\n\n/**\n * This function makes a record of kind candidate for each pair of a repository and an area that the atlas finds. It\n * reads nothing itself.\n *\n * - The import finds each repository of the atlas under its owner, or under the one owner that has a repository of that\n * name. It leaves out a name of two owners, a fork, an archived repository and a repository that is not public.\n * - It leaves out an area that the map of homes does not have, and the repositories that hold the own code of the area.\n * - Each candidate has the commit that the atlas read, and each place once, in the order of the file and the line.\n */\nexport function recordsFromAtlas(atlas: Atlas, repositories: readonly PublicRepository[], mapRecords: readonly EntityRecord[]): AtlasImport {\n const skipped = new Set<string>();\n const find = repositoryFinder(atlas, repositories);\n const areas = new Set(mapRecords.filter((record) => record.kind === \"area\").map((record) => record.id));\n const own = ownRepositories(mapRecords);\n const pairs = new Map<string, { id: string; repository: string; area: string; commit: string; places: Map<string, AtlasCopy> }>();\n for (const row of atlas.rows) {\n const area = makeId(\"area\", row.area);\n if (!areas.has(area)) {\n skipped.add(`The atlas names the area ${row.area}, which the map of homes does not have.`);\n continue;\n }\n for (const copy of row.copies) {\n const found = find(copy.repo);\n if (\"why\" in found) {\n skipped.add(`The atlas names the repository ${copy.repo}, but ${found.why}.`);\n continue;\n }\n const repository = repositoryId(found.repository.owner, found.repository.name);\n if (own.get(area)?.has(repository) === true) continue;\n const key = `${repository} ${area}`;\n const id = makeId(\"candidate\", found.repository.owner, found.repository.name, row.area);\n const pair = pairs.get(key) ?? { id, repository, area, commit: found.commit, places: new Map<string, AtlasCopy>() };\n pair.places.set(`${copy.file}:${String(copy.line)}:${copy.name}`, copy);\n pairs.set(key, pair);\n }\n }\n const records: EntityRecord[] = [\n {\n id: ATLAS_SOURCE_ID,\n kind: \"source\",\n attrs: { title: \"The duplication atlas of codeatlas\", url: \"https://metrograph-labs.github.io/codeatlas/\", version: ATLAS_SCHEMA, license: \"MIT\" },\n },\n ];\n for (const pair of pairs.values()) {\n const places = [...pair.places.values()]\n .sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))\n .map(({ file, line, name }) => ({ file, line, name }));\n records.push({\n id: pair.id,\n kind: \"candidate\",\n attrs: { commit: pair.commit, places },\n envelope: { source_ids: [ATLAS_SOURCE_ID] },\n edges: [\n { type: \"about\", to: pair.area },\n { type: \"about\", to: pair.repository },\n ],\n });\n }\n records.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n return { records, skipped: [...skipped].sort() };\n}\n","// The check of the ontology: the grammar, the shape of each record file, and the integrity of the graph.\nimport { instantNanos } from \"@mark1russell7/algebra/clock\";\nimport { Ajv2020, type ErrorObject, type ValidateFunction } from \"ajv/dist/2020.js\";\nimport formats from \"ajv-formats\";\nimport { edgesOf, isKindIn, isLive, kindOf, lineageOf, relationOf } from \"./grammar.ts\";\nimport { GRAMMAR_FILE, kindOfId, pathOfId } from \"./ids.ts\";\nimport { formalKeyOf } from \"./problems.ts\";\nimport { canonicalScope, readScope, type Scope } from \"./scope.ts\";\nimport type { Edge, Envelope, Grammar, JsonSchema, Ontology, Problem } from \"./types.ts\";\n\n/** This function makes a validator of JSON Schema 2020-12 with the formats `uri` and `date-time`. */\nfunction makeAjv(): Ajv2020 {\n const ajv = new Ajv2020({ allErrors: true, strict: true, strictTypes: false, logger: false });\n formats[\"default\"](ajv);\n return ajv;\n}\n\n/** This function gives the text of each error of a validation, with the name `name` for the value. */\nfunction errorTexts(name: string, errors: readonly ErrorObject[] | null | undefined): string[] {\n return (errors ?? []).map((error) => {\n const extra = error.keyword === \"additionalProperties\" ? ` (${String(error.params[\"additionalProperty\"])})` : \"\";\n const allowed = error.keyword === \"enum\" ? `: ${JSON.stringify(error.params[\"allowedValues\"])}` : \"\";\n return `${name}${error.instancePath} ${error.message ?? error.keyword}${extra}${allowed}`;\n });\n}\n\n/** The validators of the grammar: one for the attributes of each kind and one for the qualifiers of each relation kind. */\nexport interface Validators {\n readonly record: ValidateFunction;\n readonly kinds: ReadonlyMap<string, ValidateFunction>;\n readonly qualifiers: ReadonlyMap<string, ValidateFunction>;\n}\n\n/** This function compiles a schema of the grammar with the shared `$defs`. It gives a problem when the schema is not valid. */\nfunction compile(ajv: Ajv2020, grammar: Grammar, schema: JsonSchema, what: string, problems: Problem[]): ValidateFunction | undefined {\n try {\n return ajv.compile({ $defs: grammar.$defs, ...schema });\n } catch (error) {\n problems.push({ path: GRAMMAR_FILE, message: `${what}: ${error instanceof Error ? error.message : String(error)}` });\n return undefined;\n }\n}\n\n/** This function checks the grammar itself, and compiles its validators. */\nexport function checkGrammar(ontology: Ontology, problems: Problem[]): Validators {\n const { grammar } = ontology;\n const ajv = makeAjv();\n const name = new RegExp(grammar.namePattern);\n const kinds = new Map<string, ValidateFunction>();\n const qualifiers = new Map<string, ValidateFunction>();\n const fail = (message: string): void => {\n problems.push({ path: GRAMMAR_FILE, message });\n };\n const seen = new Set<string>();\n for (const kind of grammar.kinds) {\n if (seen.has(kind.name)) fail(`The kind ${kind.name} comes more than one time.`);\n seen.add(kind.name);\n if (!name.test(kind.name)) fail(`The kind name ${kind.name} does not agree with the name pattern.`);\n if (kind.parent !== null && kindOf(grammar, kind.parent) === undefined) fail(`The parent ${kind.parent} of the kind ${kind.name} is not a kind.`);\n if (kind.parent !== null && lineageOf(grammar, kind.name).length <= lineageOf(grammar, kind.parent).length) fail(`The parents of the kind ${kind.name} make a loop.`);\n const validate = compile(ajv, grammar, kind.attributes, `the attributes of the kind ${kind.name}`, problems);\n if (validate !== undefined) kinds.set(kind.name, validate);\n }\n for (const relation of grammar.relations) {\n if (seen.has(relation.name)) fail(`The name ${relation.name} is a kind and a relation kind, or two relation kinds.`);\n seen.add(relation.name);\n if (!name.test(relation.name)) fail(`The relation name ${relation.name} does not agree with the name pattern.`);\n for (const end of [...relation.from, ...relation.to]) {\n if (kindOf(grammar, end) === undefined) fail(`The relation ${relation.name} names ${end}, which is not a kind.`);\n }\n if (relation.parent !== undefined && relationOf(grammar, relation.parent) === undefined) fail(`The parent ${relation.parent} of the relation ${relation.name} is not a relation kind.`);\n const fields = Object.keys((relation.qualifiers?.[\"properties\"] as Record<string, unknown> | undefined) ?? {});\n for (const part of relation.key ?? []) {\n if (part !== \"from\" && part !== \"to\" && !fields.includes(part)) fail(`The key of the relation ${relation.name} names ${part}, which is not an end or a qualifier.`);\n }\n if (relation.qualifiers !== undefined) {\n const validate = compile(ajv, grammar, relation.qualifiers, `the qualifiers of the relation ${relation.name}`, problems);\n if (validate !== undefined) qualifiers.set(relation.name, validate);\n }\n }\n return { record: ajv.compile(ontology.recordSchema), kinds, qualifiers };\n}\n\n/** This function checks that each id of an envelope names a record, and that each source id names a record of kind source. */\nfunction checkEnvelope(envelope: Envelope | undefined, what: string, path: string, kinds: ReadonlyMap<string, string>, grammar: Grammar, problems: Problem[]): void {\n if (envelope === undefined) return;\n for (const source of envelope.source_ids ?? []) {\n const kind = kinds.get(source);\n if (kind === undefined) problems.push({ path, message: `${what}: the source ${source} is not a record.` });\n else if (!isKindIn(grammar, kind, [\"source\"])) problems.push({ path, message: `${what}: the source ${source} is a ${kind}, not a source.` });\n }\n for (const field of [\"superseded_by\", \"retired_from\"] as const) {\n const id = envelope[field];\n if (id !== undefined && !kinds.has(id)) problems.push({ path, message: `${what}: ${field} names ${id}, which is not a record.` });\n }\n if (!timesInOrder(envelope)) problems.push({ path, message: `${what}: valid_from ${String(envelope.valid_from)} is after valid_to ${String(envelope.valid_to)}.` });\n}\n\n/**\n * This function tells if the `valid_from` of an envelope is not after its `valid_to`. The comparison uses the instants\n * in nanoseconds, so two times with different offsets or in one millisecond compare correctly. The record schema refuses\n * a time that is not valid.\n */\nexport function timesInOrder(envelope: Envelope): boolean {\n const from = instantNanos(envelope.valid_from ?? \"\");\n const to = instantNanos(envelope.valid_to ?? \"\");\n return from === undefined || to === undefined || from <= to;\n}\n\n/** 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. */\n/**\n * This function examines the scopes (roadmap C16). Each scope is valid and not empty. A live result about a problem has\n * a scope, and the problem has a scope of the same variable. So the rule of the results can compare the two scopes.\n */\nfunction checkScopes(ontology: Ontology, problems: Problem[]): void {\n const scopes = new Map<string, Scope>();\n const records = new Map(ontology.records.map((entry) => [entry.record.id, entry]));\n for (const { path, record } of ontology.records) {\n const value = record.attrs[\"scope\"];\n if (value === undefined) continue;\n const scope = readScope(value);\n if (typeof scope === \"string\") problems.push({ path, message: scope });\n else if (canonicalScope(scope) === undefined) problems.push({ path, message: \"The scope has no value: no value from from to to is in its classes.\" });\n else scopes.set(record.id, scope);\n }\n const named = new Set<string>();\n for (const { path, record } of ontology.records) {\n if (record.kind !== \"result\" || !isLive(record)) continue;\n for (const edge of record.edges ?? []) {\n const problem = records.get(edge.to);\n if (edge.type !== \"about\" || !isLive(edge) || problem?.record.kind !== \"problem\") continue;\n if (record.attrs[\"scope\"] === undefined) problems.push({ path, message: `The result is about ${edge.to}, so it has a scope.` });\n if (problem.record.attrs[\"scope\"] === undefined && !named.has(edge.to)) {\n named.add(edge.to);\n problems.push({ path: problem.path, message: `The result ${record.id} is about the problem, so the problem has a scope.` });\n }\n const own = scopes.get(record.id);\n const theirs = scopes.get(edge.to);\n if (own !== undefined && theirs !== undefined && own.variable !== theirs.variable) {\n problems.push({ path, message: `The scope of the result has the variable ${own.variable}, and the scope of ${edge.to} has ${theirs.variable}.` });\n }\n }\n }\n}\n\n/**\n * This function examines the formal names (roadmap C12). Two live problems cannot have one Lean key, because a tool\n * finds a problem by its formal name. A short name, for example `conjecture`, names many statements.\n */\nfunction checkFormalNames(ontology: Ontology, problems: Problem[]): void {\n const first = new Map<string, string>();\n for (const { path, record } of ontology.records) {\n if (record.kind !== \"problem\" || !isLive(record)) continue;\n const key = formalKeyOf(record);\n if (key === undefined) continue;\n const earlier = first.get(key);\n if (earlier === undefined) first.set(key, record.id);\n else problems.push({ path, message: `The formal name ${key} is also the formal name of ${earlier}. Give the full name, with its namespaces.` });\n }\n}\n\nfunction keyOf(edge: Edge, key: readonly string[]): string {\n return JSON.stringify(key.map((part) => (part === \"from\" ? edge.from : part === \"to\" ? edge.to : (edge.qualifiers[part] ?? null))));\n}\n\n/**\n * This function checks the ontology, and gives each problem that it finds, in the order of the paths. No problem means\n * that the data is valid:\n *\n * - The grammar is valid: unique names, known parents and ends, keys of known parts and schemas that compile.\n * - Each record file agrees with `schema/record.schema.json`, and its attributes agree with the schema of its kind.\n * - The id of each record starts with its kind, its file is at the path of its id, and no two records have one id.\n * - Each relation has a relation kind that is not abstract, ends of the correct kinds, and correct qualifiers.\n * - No two live relations of a kind have the same key. For example, an area has at most one home.\n * - Each id of an envelope names a record, and each source is a record of kind source.\n */\nexport function checkOntology(ontology: Ontology): readonly Problem[] {\n const problems: Problem[] = [];\n const { grammar } = ontology;\n const validators = checkGrammar(ontology, problems);\n const idPattern = new RegExp(grammar.idPattern);\n const kinds = new Map<string, string>();\n const paths = new Map<string, string>();\n for (const { path, record } of ontology.records) {\n if (!validators.record(record)) {\n for (const message of errorTexts(\"record\", validators.record.errors)) problems.push({ path, message });\n continue;\n }\n const earlier = paths.get(record.id);\n if (earlier !== undefined) problems.push({ path, message: `The id ${record.id} is also the id of ${earlier}.` });\n paths.set(record.id, path);\n kinds.set(record.id, record.kind);\n }\n for (const { path, record } of ontology.records) {\n if (paths.get(record.id) !== path) continue;\n if (!idPattern.test(record.id)) problems.push({ path, message: `The id ${record.id} does not agree with the id pattern.` });\n if (kindOfId(record.id) !== record.kind) problems.push({ path, message: `The id ${record.id} does not start with its kind ${record.kind} and a dot.` });\n else if (pathOfId(record.id) !== path) problems.push({ path, message: `The file of ${record.id} is not at ${pathOfId(record.id)}.` });\n const validate = validators.kinds.get(record.kind);\n if (kindOf(grammar, record.kind) === undefined) problems.push({ path, message: `The kind ${record.kind} is not a kind of the grammar.` });\n else if (validate !== undefined && !validate(record.attrs)) {\n for (const message of errorTexts(\"attrs\", validate.errors)) problems.push({ path, message });\n }\n checkEnvelope(record.envelope, \"envelope\", path, kinds, grammar, problems);\n for (const [index, edge] of (record.edges ?? []).entries()) {\n const what = `edges/${String(index)} (${edge.type} ${edge.to})`;\n const relation = relationOf(grammar, edge.type);\n if (relation === undefined) {\n problems.push({ path, message: `${what}: ${edge.type} is not a relation kind of the grammar.` });\n continue;\n }\n if (relation.abstract === true) problems.push({ path, message: `${what}: the relation kind ${edge.type} is abstract.` });\n if (!isKindIn(grammar, record.kind, relation.from)) problems.push({ path, message: `${what}: a ${record.kind} cannot start a relation ${edge.type}.` });\n const to = kinds.get(edge.to);\n if (to === undefined) problems.push({ path, message: `${what}: ${edge.to} is not a record.` });\n else if (!isKindIn(grammar, to, relation.to)) problems.push({ path, message: `${what}: a relation ${edge.type} cannot end at a ${to}.` });\n const validate = validators.qualifiers.get(edge.type);\n if (validate === undefined && relation.qualifiers === undefined && Object.keys(edge.qualifiers ?? {}).length > 0) {\n problems.push({ path, message: `${what}: the relation kind ${edge.type} has no qualifiers.` });\n } else if (validate !== undefined && !validate(edge.qualifiers ?? {})) {\n for (const message of errorTexts(`${what} qualifiers`, validate.errors)) problems.push({ path, message });\n }\n checkEnvelope(edge.envelope, `${what} envelope`, path, kinds, grammar, problems);\n }\n }\n const facts = new Map<string, string>();\n for (const edge of edgesOf(ontology).filter(isLive)) {\n const relation = relationOf(grammar, edge.type);\n if (relation === undefined) continue;\n const fact = `${edge.type} ${keyOf(edge, relation.key ?? [\"from\", \"to\"])}`;\n const first = facts.get(fact);\n const path = paths.get(edge.from) ?? pathOfId(edge.from);\n if (first !== undefined) {\n const parts = (relation.key ?? [\"from\", \"to\"]).join(\" and \");\n problems.push({ path, message: `The relation ${edge.type} to ${edge.to} has the same ${parts} as a relation ${edge.type} of ${first}. The two cannot both be true.` });\n }\n else facts.set(fact, edge.from);\n }\n checkScopes(ontology, problems);\n checkFormalNames(ontology, problems);\n return problems.sort((a, b) => (a.path === b.path ? 0 : a.path < b.path ? -1 : 1));\n}\n","// The report of the cloned code with no home: the classes of the duplication atlas that no area of the map covers.\nimport { textOf } from \"@mark1russell7/optional/read\";\nimport { countOf, listOf } from \"@mark1russell7/text/english\";\nimport { compareCodeUnits as compareText } from \"@mark1russell7/text/order\";\nimport { type Atlas, ownRepositories, repositoryFinder } from \"./atlas.ts\";\nimport type { PublicRepository } from \"./homes.ts\";\nimport { repositoryId } from \"./ids.ts\";\nimport type { EntityRecord } from \"./types.ts\";\n\n/** The fewest copied syntax nodes of a class in the report. A smaller class is too small for a home. */\nexport const CLONE_FLOOR = 200;\n\n/** A copy of a class of cloned code, in a repository of the records. */\nexport interface CloneMember {\n /** The id of the record of the repository. */\n readonly repository: string;\n readonly file: string;\n readonly line: number;\n /** The name of the function, or `<anonymous>`. */\n readonly name: string;\n}\n\n/** A class of cloned code that no area of the map of homes covers. */\nexport interface CloneClass {\n /** The syntax nodes of the copies after the first: the nodes of one copy, times the count of copies less one. */\n readonly copied: number;\n /** The copies, in the order of the repository, the file and the line. */\n readonly members: readonly CloneMember[];\n}\n\n/** The classes of cloned code with no home that have their copies in the same repositories. */\nexport interface CloneGroup {\n /** The ids of the records of the repositories, in order. */\n readonly repositories: readonly string[];\n /** The sum of the copied syntax nodes of the classes. */\n readonly copied: number;\n /** The classes, the largest first. */\n readonly classes: readonly CloneClass[];\n}\n\n/** This function gives the public repositories of the records: each record of kind repository that exists. */\nfunction repositoriesOf(records: readonly EntityRecord[]): readonly PublicRepository[] {\n const repositories: PublicRepository[] = [];\n for (const record of records) {\n if (record.kind !== \"repository\" || record.attrs[\"exists\"] !== true) continue;\n const owner = textOf(record.attrs, \"owner\");\n const name = textOf(record.attrs, \"name\");\n const url = textOf(record.attrs, \"url\");\n if (owner !== undefined && name !== undefined && url !== undefined) repositories.push({ owner, name, url });\n }\n return repositories;\n}\n\n/**\n * This function gives the classes of cloned code that no area covers, in groups by their repositories. It keeps a\n * class with copies in two or more public repositories of the records and `floor` or more copied syntax nodes.\n *\n * - The atlas names each repository. This function finds it in the records as the import does. A copy in a\n * repository that it cannot find is not a copy of the report.\n * - The largest group comes first. Two groups of the same size are in the order of their repositories.\n */\nexport function cloneGroups(atlas: Atlas, records: readonly EntityRecord[], floor: number = CLONE_FLOOR): readonly CloneGroup[] {\n const find = repositoryFinder(atlas, repositoriesOf(records));\n const groups = new Map<string, { repositories: readonly string[]; classes: CloneClass[] }>();\n for (const found of atlas.classes) {\n if (found.areas.length > 0) continue;\n const members = new Map<string, CloneMember>();\n for (const copy of found.members) {\n const place = find(copy.repo);\n if (\"why\" in place) continue;\n const member = { repository: repositoryId(place.repository.owner, place.repository.name), file: copy.file, line: copy.line, name: copy.name };\n members.set(`${member.repository} ${member.file}:${String(member.line)} ${member.name}`, member);\n }\n const repositories = [...new Set([...members.values()].map((member) => member.repository))].sort(compareText);\n const copied = found.nodes * (members.size - 1);\n if (repositories.length < 2 || copied < floor) continue;\n const ordered = [...members.values()].sort((a, b) => compareText(a.repository, b.repository) || compareText(a.file, b.file) || a.line - b.line);\n const key = repositories.join(\" \");\n const group = groups.get(key) ?? { repositories, classes: [] };\n group.classes.push({ copied, members: ordered });\n groups.set(key, group);\n }\n const placeOf = (clone: CloneClass): string => clone.members.map((member) => `${member.repository} ${member.file}:${String(member.line)}`).join(\" \");\n return [...groups.values()]\n .map(({ repositories, classes }) => ({\n repositories,\n copied: classes.reduce((sum, clone) => sum + clone.copied, 0),\n classes: classes.sort((a, b) => b.copied - a.copied || compareText(placeOf(a), placeOf(b))),\n }))\n .sort((a, b) => b.copied - a.copied || compareText(a.repositories.join(\" \"), b.repositories.join(\" \")));\n}\n\n/** This function gives the name of a repository for a person: `owner/name`. */\nfunction repositoryName(id: string, byId: ReadonlyMap<string, EntityRecord>): string {\n const attrs = byId.get(id)?.attrs;\n const owner = attrs === undefined ? undefined : textOf(attrs, \"owner\");\n const name = attrs === undefined ? undefined : textOf(attrs, \"name\");\n return owner === undefined || name === undefined ? id : `${owner}/${name}`;\n}\n\n/** This function gives the text of the functions of one file: each name with its line. */\nfunction functionsText(members: readonly CloneMember[]): string {\n const parts = [...new Map(members.map((member) => [`${String(member.line)} ${member.name}`, member])).values()]\n .sort((a, b) => a.line - b.line || compareText(a.name, b.name))\n .map((member) => (member.name === \"<anonymous>\" ? `a function with no name at line ${String(member.line)}` : `\\`${member.name}\\` at line ${String(member.line)}`));\n return listOf(parts);\n}\n\n/**\n * This function gives the report of the groups as Markdown, for the maintainer of the map of homes. The report names\n * each repository, the areas whose code it holds, and each file and function of the copies. It names no hash, so a\n * new read of the atlas gives the same keys. Each title of an area is in quotes, because a title can have commas.\n */\nexport function cloneReport(groups: readonly CloneGroup[], records: readonly EntityRecord[], floor: number = CLONE_FLOOR): string {\n const byId = new Map(records.map((record) => [record.id, record]));\n const areasOf = new Map<string, string[]>();\n for (const [area, repositories] of ownRepositories(records)) {\n const title = textOf(byId.get(area)?.attrs ?? {}, \"title\") ?? area;\n for (const repository of repositories) areasOf.set(repository, [...(areasOf.get(repository) ?? []), title]);\n }\n const classes = groups.reduce((sum, group) => sum + group.classes.length, 0);\n const lines = [\"# The cloned code with no home\", \"\"];\n if (classes === 0) {\n lines.push(`The duplication atlas finds no class of cloned code with no home, with ${String(floor)} or more copied syntax nodes.`);\n return lines.join(\"\\n\");\n }\n lines.push(\n `The duplication atlas finds ${countOf(classes, \"class\", \"classes\")} of cloned code that no area of the map of homes covers, in ${countOf(groups.length, \"group\")}.`,\n `Each class has copies in two or more public repositories, and ${String(floor)} or more copied syntax nodes.`,\n \"For each group, the maintainer chooses a home, or writes why the copies stay.\",\n );\n for (const group of groups) {\n lines.push(\"\", `## ${listOf(group.repositories.map((id) => `\\`${repositoryName(id, byId)}\\``))}`, \"\");\n lines.push(`${countOf(group.classes.length, \"class\", \"classes\")}, ${group.copied.toLocaleString(\"en-US\")} copied syntax nodes.`, \"\");\n for (const repository of group.repositories) {\n const areas = (areasOf.get(repository) ?? []).sort(compareText).map((title) => `\"${title}\"`);\n const holds = areas.length === 0 ? \"It holds the code of no area.\" : `It holds the code of the ${areas.length === 1 ? \"area\" : \"areas\"} ${listOf(areas)}.`;\n lines.push(`- \\`${repositoryName(repository, byId)}\\`. ${holds}`);\n const files = new Map<string, CloneMember[]>();\n for (const clone of group.classes) for (const member of clone.members) if (member.repository === repository) files.set(member.file, [...(files.get(member.file) ?? []), member]);\n for (const [file, members] of [...files.entries()].sort(([a], [b]) => compareText(a, b))) lines.push(` - \\`${file}\\`: ${functionsText(members)}.`);\n }\n }\n return lines.join(\"\\n\");\n}\n","// The kinds of canon as an add-on of the ontology engine (roadmap C18). The grammar file stays the one source of the\n// kinds. This module reads the grammar into the engine, and it refuses each rule that the engine cannot keep.\nimport {\n type AttrShape,\n type Edge as EngineEdge,\n type Entity,\n type FacetDef as EngineFacet,\n type GenerateOptions,\n type KindDef as EngineKind,\n type Registry,\n type RegistryInput,\n type RelationExtension,\n type RelationKindDef as EngineRelation,\n type Requirement,\n type RequirementValue,\n type Scope as EngineScope,\n spineRegistry,\n spineRelations,\n} from \"@mark1russell7/ontology\";\nimport { errorMessage } from \"@mark1russell7/text\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport { GRAMMAR_FILE } from \"./ids.ts\";\nimport type { Grammar, JsonSchema, KindDef, LoadedRecord, RelationKindDef } from \"./types.ts\";\n\n/**\n * The audience of canon: each record is public (`schema/record.schema.json`). It is the default scope of each kind, and\n * the engine refuses a record or an edge with a more private scope.\n */\nconst CANON_AUDIENCE: EngineScope = \"public\";\n\n/** The folder of the files that the engine generates from the grammar, relative to the root of the repository. */\nexport const ENGINE_FOLDER = \"schema/engine\";\n\n/** The options of the generation: the first line of each SQL file names the command that makes the files. */\nexport const ENGINE_GENERATE_OPTIONS: GenerateOptions = {\n header: `-- Generated by \\`pnpm canon engine --write\\` from ${GRAMMAR_FILE}. Do not edit by hand.`,\n};\n\n/**\n * The keywords of JSON Schema that the add-on gives to the engine. A test holds each keyword: ajv and the engine give\n * the same verdict on each value of the test.\n */\nexport const ENGINE_KEYWORDS: ReadonlySet<string> = new Set([\n \"$ref\",\n \"additionalProperties\",\n \"anyOf\",\n \"const\",\n \"description\",\n \"enum\",\n \"format\",\n \"items\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minimum\",\n \"oneOf\",\n \"pattern\",\n \"properties\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n]);\n\n/**\n * The values of the keyword `format` that the add-on gives to the engine. In JSON Schema 2020-12, a format is only an\n * annotation. So each field with a format also has a pattern, and each reader gives the same verdict. The format `uri`\n * is not in the list: zod reads it as `z.url()`, which removes the spaces at the two ends of the value.\n */\nexport const ENGINE_FORMATS: ReadonlySet<string> = new Set([\"date-time\"]);\n\n/** The error of a grammar rule that the engine cannot keep. Each problem has the path of the rule in the grammar. */\nexport class EngineGrammarError extends Error {\n /** The problems: one text for each rule that the engine cannot keep. */\n readonly problems: readonly string[];\n\n constructor(problems: readonly string[]) {\n super(`The ontology engine cannot keep ${String(problems.length)} rules of ${GRAMMAR_FILE}:\\n${problems.join(\"\\n\")}`);\n this.name = \"EngineGrammarError\";\n this.problems = problems;\n }\n}\n\n/** This function tells if a value is a JSON object, not an array and not null. */\nconst isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** This function adds a problem for each keyword of a schema that the engine does not keep, also in the parts of the schema. */\nfunction checkKeywords(schema: unknown, path: string, problems: string[]): void {\n if (!isObject(schema)) {\n problems.push(`${path}: the engine keeps only a schema that is an object, not ${JSON.stringify(schema)}.`);\n return;\n }\n // zod reads an object next to oneOf or anyOf as an intersection of open objects, so it loses the rules of the object\n const next = Object.keys(schema).filter((keyword) => ![\"anyOf\", \"description\", \"oneOf\"].includes(keyword));\n if ((schema[\"oneOf\"] !== undefined || schema[\"anyOf\"] !== undefined) && next.length > 0) {\n problems.push(`${path}: a schema with oneOf or anyOf has only a description next to it, not ${next.join(\", \")}.`);\n }\n // zod removes the unknown keys of an open object, so the engine changes the value where ajv keeps it\n if ((schema[\"type\"] === \"object\" || schema[\"properties\"] !== undefined) && schema[\"additionalProperties\"] !== false) {\n problems.push(`${path}: the engine keeps only an object with additionalProperties false.`);\n }\n for (const [keyword, value] of Object.entries(schema)) {\n const at = `${path}/${keyword}`;\n if (!ENGINE_KEYWORDS.has(keyword)) problems.push(`${at}: the engine does not keep the keyword ${keyword}.`);\n else if (keyword === \"format\" && !ENGINE_FORMATS.has(String(value))) problems.push(`${at}: the engine does not keep the format ${String(value)}.`);\n else if (keyword === \"additionalProperties\" && value !== false) problems.push(`${at}: the engine keeps only additionalProperties false.`);\n else if (keyword === \"properties\" && isObject(value)) {\n for (const [name, part] of Object.entries(value)) checkKeywords(part, `${at}/${name}`, problems);\n } else if (keyword === \"items\") checkKeywords(value, at, problems);\n else if ((keyword === \"oneOf\" || keyword === \"anyOf\") && Array.isArray(value)) {\n value.forEach((part: unknown, index) => {\n checkKeywords(part, `${at}/${String(index)}`, problems);\n });\n }\n }\n}\n\n/** This function gives the zod shape of an object schema of the grammar: one zod schema for each property. */\nfunction shapeOf(schema: JsonSchema, grammar: Grammar, path: string, problems: string[]): AttrShape {\n const { if: _if, then: _then, ...rest } = schema;\n checkKeywords(rest, path, problems);\n if (schema[\"type\"] !== \"object\" || schema[\"additionalProperties\"] !== false) {\n problems.push(`${path}: the engine keeps only a closed object: type object and additionalProperties false.`);\n }\n const required = new Set((schema[\"required\"] as readonly string[] | undefined) ?? []);\n const shape: Record<string, z.ZodType> = {};\n for (const [name, part] of Object.entries((schema[\"properties\"] as Record<string, JsonSchema> | undefined) ?? {})) {\n const zod = z.fromJSONSchema({ ...part, $defs: grammar.$defs } as Parameters<typeof z.fromJSONSchema>[0]);\n shape[name] = required.has(name) ? zod : zod.optional();\n }\n return shape;\n}\n\n/**\n * This function gives the requirements of a kind from the keywords `if` and `then` of its attributes. The engine keeps\n * one form: when each property of `if` has its `const` value, each property of `then` is necessary.\n */\nfunction requirementsOf(schema: JsonSchema, path: string, problems: string[]): readonly Requirement[] {\n const condition = schema[\"if\"];\n const result = schema[\"then\"];\n if (condition === undefined && result === undefined) return [];\n const form = `${path}: the engine keeps only the form if {properties: {name: {const}}, required} then {description, required}`;\n if (!isObject(condition) || !isObject(result) || schema[\"else\"] !== undefined) {\n problems.push(`${form}.`);\n return [];\n }\n const when: Record<string, RequirementValue> = {};\n const properties = condition[\"properties\"];\n const names = isObject(properties) ? Object.keys(properties) : [];\n for (const name of names) {\n const part = (properties as Readonly<Record<string, unknown>>)[name];\n const value = isObject(part) && Object.keys(part).length === 1 ? part[\"const\"] : undefined;\n if (value === undefined || (typeof value === \"object\" && value !== null)) problems.push(`${form}: ${name} has no const value.`);\n else when[name] = value as RequirementValue;\n }\n const conditionKeys = Object.keys(condition).sort().join(\",\");\n const conditionRequired = [...((condition[\"required\"] as readonly string[] | undefined) ?? [])].sort().join(\",\");\n if (conditionKeys !== \"properties,required\" || conditionRequired !== [...names].sort().join(\",\")) problems.push(`${form}: the if part has other keywords.`);\n const then = (result[\"required\"] as readonly string[] | undefined) ?? [];\n const thenProperties = result[\"properties\"];\n const extra = Object.keys(result).filter((keyword) => ![\"description\", \"properties\", \"required\"].includes(keyword));\n const loose = isObject(thenProperties) ? Object.entries(thenProperties).filter(([name, part]) => part !== true || !then.includes(name)) : [];\n if (typeof result[\"description\"] !== \"string\" || then.length === 0 || extra.length > 0 || loose.length > 0) {\n problems.push(`${form}: the then part has other keywords or no description.`);\n }\n return [{ description: String(result[\"description\"]), when, then }];\n}\n\n/** 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. */\nfunction kindOf(kind: KindDef, grammar: Grammar, problems: string[]): EngineKind {\n const path = `${GRAMMAR_FILE}#/kinds/${kind.name}/attributes`;\n const requirements = requirementsOf(kind.attributes, path, problems);\n return {\n name: kind.name,\n parent: kind.parent ?? \"entity\",\n mode: kind.mode,\n description: kind.description,\n attributes: shapeOf(kind.attributes, grammar, path, problems),\n ...(kind.facets.length > 0 ? { facets: kind.facets } : {}),\n defaultScope: CANON_AUDIENCE,\n ...(requirements.length > 0 ? { requirements } : {}),\n };\n}\n\n/** This function gives the relation kind of canon as a relation kind of the engine. */\nfunction relationOf(relation: RelationKindDef, grammar: Grammar, problems: string[]): EngineRelation {\n const path = `${GRAMMAR_FILE}#/relations/${relation.name}/qualifiers`;\n return {\n name: relation.name,\n description: relation.description,\n from: relation.from,\n to: relation.to,\n ...(relation.parent === undefined ? {} : { parent: relation.parent }),\n ...(relation.qualifiers === undefined ? {} : { qualifiers: shapeOf(relation.qualifiers, grammar, path, problems) }),\n ...(relation.symmetric === undefined ? {} : { symmetric: relation.symmetric }),\n ...(relation.transitive === undefined ? {} : { transitive: relation.transitive }),\n ...(relation.abstract === undefined ? {} : { abstract: relation.abstract }),\n ...(relation.key === undefined ? {} : { key: relation.key }),\n };\n}\n\n/**\n * This function gives a relation kind of canon with the name of a relation kind of the engine as an extension. The\n * extension adds one pair of ends: each `from` kind of canon with each `to` kind of canon. The pair of the spine relates\n * no kind of canon, so the engine permits the same edges as canon.\n */\nfunction extensionOf(relation: RelationKindDef, problems: string[]): RelationExtension {\n if (relation.qualifiers !== undefined || relation.key !== undefined || relation.parent !== undefined) {\n problems.push(`${GRAMMAR_FILE}#/relations/${relation.name}: a relation of the engine gets only more kinds at its ends.`);\n }\n return { relation: relation.name, from: [...relation.from], to: [...relation.to] };\n}\n\n/**\n * This function gives the kinds and the relation kinds of the grammar as an add-on of the engine.\n *\n * @throws EngineGrammarError when the grammar has a rule that the engine cannot keep\n */\nexport function engineAddOn(grammar: Grammar): RegistryInput {\n const problems: string[] = [];\n const facets: EngineFacet[] = grammar.facets.map((facet) => ({\n name: facet.name,\n description: facet.description,\n attributes: shapeOf(facet.attributes, grammar, `${GRAMMAR_FILE}#/facets/${facet.name}/attributes`, problems),\n }));\n for (const [name, schema] of Object.entries(grammar.$defs)) checkKeywords(schema, `${GRAMMAR_FILE}#/$defs/${name}`, problems);\n const kinds = grammar.kinds.map((kind) => kindOf(kind, grammar, problems));\n const relations: EngineRelation[] = [];\n const extensions: RelationExtension[] = [];\n for (const relation of grammar.relations) {\n const spine = spineRelations.find((candidate) => candidate.name === relation.name);\n if (spine === undefined) relations.push(relationOf(relation, grammar, problems));\n else extensions.push(extensionOf(relation, problems));\n }\n if (problems.length > 0) throw new EngineGrammarError(problems);\n const input = {\n kinds,\n relations,\n ...(facets.length > 0 ? { facets } : {}),\n ...(extensions.length > 0 ? { extensions } : {}),\n audience: CANON_AUDIENCE,\n };\n return withoutInherited(input);\n}\n\n/** The schema of an attribute that a kind of canon does not have: it refuses each value. */\nconst NO_VALUE = z.never().describe(\"A kind of canon has no value of this attribute of its parents.\").optional();\n\n/**\n * This function narrows each kind to the attributes that canon gives it. In the engine, a kind also gets each attribute\n * of its parents and their facets. Thus the root of the spine gives each kind of canon the attributes `name` and\n * `notes`. The schema of canon has only its own attributes, so the kind refuses each other attribute.\n *\n * @throws EngineGrammarError when a kind gets requirements from its parents in the engine\n */\nfunction withoutInherited(input: RegistryInput & { readonly kinds: readonly EngineKind[] }): RegistryInput {\n const first = spineRegistry(input);\n const problems: string[] = [];\n const kinds = input.kinds.map((kind) => {\n if (first.effectiveRequirements(kind.name).length !== (kind.requirements ?? []).length) {\n problems.push(`${GRAMMAR_FILE}#/kinds/${kind.name}: the engine adds the requirements of the parents, and canon does not.`);\n }\n const inherited = Object.keys(first.effectiveShape(kind.name)).filter((name) => !Object.hasOwn(kind.attributes, name));\n if (inherited.length === 0) return kind;\n return { ...kind, attributes: { ...kind.attributes, ...Object.fromEntries(inherited.map((name) => [name, NO_VALUE])) } };\n });\n if (problems.length > 0) throw new EngineGrammarError(problems);\n return { ...input, kinds };\n}\n\n/**\n * This function gives the registry of the engine with the spine and the kinds of canon.\n *\n * @throws EngineGrammarError when the grammar has a rule that the engine cannot keep\n */\nexport function engineRegistry(grammar: Grammar): Registry {\n return spineRegistry(engineAddOn(grammar));\n}\n\n/** The records of canon in the engine: each entity and each relation, or the problems of the load. */\nexport interface EngineLoad {\n readonly entities: readonly Entity[];\n readonly edges: readonly EngineEdge[];\n /** The problems: one text for each record or relation that the engine refuses or changes. */\n readonly problems: readonly string[];\n}\n\n/** This function gives the names of the fields of two objects that do not have the same value. */\nfunction changedFields(before: object, after: object): readonly string[] {\n const left = new Map(Object.entries(before));\n const right = new Map(Object.entries(after));\n return [...new Set([...left.keys(), ...right.keys()])].filter((name) => !isDeepStrictEqual(left.get(name), right.get(name))).sort();\n}\n\n/**\n * This function loads each record and each relation into the engine. A record or a relation that the engine refuses is a\n * problem. A value that the engine changes is also a problem: the load keeps each value. The engine adds only the scope\n * `public`, the default scope of each kind of canon, to an envelope with no scope.\n */\nexport function loadIntoEngine(registry: Registry, records: readonly LoadedRecord[]): EngineLoad {\n const kinds = new Map(records.map(({ record }) => [record.id, record.kind]));\n const entities: Entity[] = [];\n const edges: EngineEdge[] = [];\n const problems: string[] = [];\n const compare = (path: string, part: string, before: object, after: object): void => {\n const changed = changedFields(before, after);\n if (changed.length > 0) problems.push(`${path}: the engine changes the ${part} ${changed.join(\", \")}.`);\n };\n const refuse = (path: string, error: unknown): void => {\n problems.push(`${path}: ${errorMessage(error).replaceAll(\"\\n\", \" \")}`);\n };\n for (const { path, record } of records) {\n const envelope = record.envelope ?? {};\n try {\n const entity = registry.validateEntity({ id: record.id, kind: record.kind, attrs: { ...record.attrs }, envelope });\n compare(path, \"attributes\", record.attrs, entity.attrs);\n compare(path, \"envelope fields\", { scope: \"public\", ...envelope }, entity.envelope);\n entities.push(entity);\n } catch (error) {\n refuse(path, error);\n }\n for (const edge of record.edges ?? []) {\n const at = `${path} ${edge.type} ${edge.to}`;\n const qualifiers = edge.qualifiers ?? {};\n try {\n const parsed = registry.validateEdge(\n { from: record.id, type: edge.type, to: edge.to, qualifiers: { ...qualifiers }, envelope: edge.envelope ?? {} },\n (id) => kinds.get(id),\n );\n compare(at, \"qualifiers\", qualifiers, parsed.qualifiers);\n compare(at, \"envelope fields\", edge.envelope ?? {}, parsed.envelope);\n edges.push(parsed);\n } catch (error) {\n refuse(at, error);\n }\n }\n }\n return { entities, edges, problems };\n}\n","// The import of the map of homes of @mark1russell7/conventions into records of the ontology.\nimport { type Home, reposOf } from \"@mark1russell7/conventions\";\nimport type { AtlasRead } from \"./atlas.ts\";\nimport { makeId, npmPackageId, npmPurl, repositoryId } from \"./ids.ts\";\nimport type { EdgeRecord, EntityRecord } from \"./types.ts\";\n\n/** The id of the record of kind source for the map of homes. */\nexport const MAP_SOURCE_ID = \"source.conventions-map\";\n\n/** The id of the record of kind source for the lists of the public repositories of each owner on GitHub. */\nexport const GITHUB_SOURCE_ID = \"source.github-repositories\";\n\n/** The ids of the sources of the import. The import writes each record of these sources, and removes the old ones. */\nexport const IMPORT_SOURCE_IDS: readonly string[] = [MAP_SOURCE_ID, GITHUB_SOURCE_ID];\n\n/** A public repository of an owner, as GitHub gives it. */\nexport interface PublicRepository {\n readonly owner: string;\n readonly name: string;\n readonly url: string;\n /** This text is the purpose of the repository, as its owner wrote it on GitHub. */\n readonly description?: string | undefined;\n /** This value is true for a fork of the repository of another account. */\n readonly fork?: boolean | undefined;\n /** This value is true for a repository that its owner archived. */\n readonly archived?: boolean | undefined;\n /** The default branch of the repository. The read of the test gates examines it. */\n readonly defaultBranch?: string | undefined;\n}\n\n/** The facts of npm for one package name. */\nexport interface NpmFact {\n /** True when npm has a version of the package. */\n readonly published: boolean;\n /** The repository of the latest version, as `owner/name`, when its `package.json` names a repository on GitHub. */\n readonly repository?: string;\n}\n\n/** The live facts that the import adds to the map: the public repositories and the facts of npm. */\nexport interface HomeFacts {\n /** Each public repository of each owner. A repository that is not here is private, or it does not exist. */\n readonly repositories: readonly PublicRepository[];\n /** The facts of npm for each package name of the map. */\n readonly npm: ReadonlyMap<string, NpmFact>;\n /** The version of `@mark1russell7/conventions` that has the map. */\n readonly version: string;\n /** The read of the duplication atlas. With no read, the import gives no candidate. */\n readonly atlas?: AtlasRead | undefined;\n}\n\n/** The result of an import: the records, in the order of their ids, and a text for each home or repository that it left out. */\nexport interface HomeImport {\n readonly records: readonly EntityRecord[];\n readonly skipped: readonly string[];\n}\n\n/** The envelope of each record that the import makes from the map. */\nconst ENVELOPE = { source_ids: [MAP_SOURCE_ID] } as const;\n\n/** The envelope of a repository that only the lists of GitHub name. */\nconst GITHUB_ENVELOPE = { source_ids: [GITHUB_SOURCE_ID] } as const;\n\n/** This function gives the repository `owner/name` of a repository URL of npm, or undefined when it is not on GitHub. */\nexport function githubRepositoryOf(url: string): string | undefined {\n const lower = url.toLowerCase();\n const host = \"github.com\";\n const at = lower.indexOf(host);\n const separator = lower.charAt(at + host.length);\n if (at < 0 || (separator !== \"/\" && separator !== \":\")) return undefined;\n const [owner = \"\", rest = \"\"] = lower.slice(at + host.length + 1).split(\"/\");\n const name = (rest.split(\"#\")[0] ?? \"\").replace(/\\.git$/, \"\");\n if (owner === \"\" || name === \"\" || /\\s/.test(owner + name)) return undefined;\n return `${owner}/${name}`;\n}\n\n/** The records of an import while it runs, by id. A second record with the same id adds its edges to the first. */\nclass RecordSet {\n private readonly byId = new Map<string, EntityRecord>();\n\n add(record: EntityRecord): void {\n const earlier = this.byId.get(record.id);\n if (earlier === undefined) {\n this.byId.set(record.id, record);\n return;\n }\n const edges = [...(earlier.edges ?? [])];\n for (const edge of record.edges ?? []) {\n if (!edges.some((other) => other.type === edge.type && other.to === edge.to)) edges.push(edge);\n }\n this.byId.set(record.id, { ...earlier, edges });\n }\n\n /** This function gives each record in the order of the ids, with its edges in the order of their type and end. */\n sorted(): readonly EntityRecord[] {\n const order = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n return [...this.byId.values()]\n .map((record) => {\n const edges = [...(record.edges ?? [])].sort((a, b) => order(`${a.type} ${a.to}`, `${b.type} ${b.to}`));\n const base: EntityRecord = { id: record.id, kind: record.kind, attrs: record.attrs, ...(record.envelope === undefined ? {} : { envelope: record.envelope }) };\n return edges.length === 0 ? base : { ...base, edges };\n })\n .sort((a, b) => order(a.id, b.id));\n }\n}\n\n/**\n * This function makes the records of the ontology from the map of homes and the live facts. It reads nothing itself.\n *\n * - Each home gives a record of kind area, and its repository gives a record of kind repository with the relation home-of.\n * - The import finds each repository under each owner, so a move between the owners does not wait on the map.\n * - A repository that is not public is left out. A home whose repository is not public is left out, except a planned home:\n * its repository is a record with `exists: false`.\n * - Each package of the map gives a record of kind package. Its repository comes from npm when npm names one.\n * - Each repository of `alsoIn` gives the relation holds-copy to the area: the code of the area moves between it and the home.\n * - Each public repository that is not a fork and not archived gives a record of kind repository, also when the map does\n * not name it. Its source is then the lists of GitHub. A repository record has the description of GitHub.\n */\nexport function recordsFromHomes(homes: readonly Home[], facts: HomeFacts): HomeImport {\n const records = new RecordSet();\n const skipped: string[] = [];\n const known = new Map(facts.repositories.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository]));\n const find = (home: Home, ref: string): PublicRepository | undefined => {\n for (const candidate of reposOf({ ...home, repo: ref, alsoIn: [] })) {\n const repository = known.get(candidate.toLowerCase());\n if (repository !== undefined) return repository;\n }\n return undefined;\n };\n const addRepository = (repository: PublicRepository, exists: boolean, edges: readonly EdgeRecord[], envelope: EntityRecord[\"envelope\"] = ENVELOPE): string => {\n const id = repositoryId(repository.owner, repository.name);\n const attrs: Record<string, unknown> = { owner: repository.owner, name: repository.name, url: repository.url, exists };\n const description = repository.description?.trim() ?? \"\";\n if (description !== \"\") attrs[\"description\"] = description;\n records.add({ id, kind: \"repository\", attrs, envelope, edges });\n return id;\n };\n records.add({\n id: MAP_SOURCE_ID,\n kind: \"source\",\n attrs: { title: \"The map of homes of @mark1russell7/conventions\", url: \"https://www.npmjs.com/package/@mark1russell7/conventions\", version: facts.version, license: \"MIT\" },\n });\n for (const home of homes) {\n const areaId = makeId(\"area\", home.area);\n const found = find(home, home.repo);\n const [owner = \"\", name = \"\"] = home.repo.split(\"/\");\n if (found === undefined && home.state !== \"planned\") {\n skipped.push(`The area ${home.area}: its repository is not public.`);\n continue;\n }\n const homeRepository = found ?? { owner, name, url: `https://github.com/${home.repo}` };\n const homeId = addRepository(homeRepository, found !== undefined, [{ type: \"home-of\", to: areaId, qualifiers: { state: home.state } }]);\n const attrs: Record<string, unknown> = { title: home.title, covers: home.covers };\n const note = home.note ?? \"\";\n if (note !== \"\") attrs[\"note\"] = note;\n if (home.words.length > 0) attrs[\"words\"] = home.words;\n if (home.signatures !== undefined && home.signatures.length > 0) attrs[\"signatures\"] = home.signatures;\n if (home.modules !== undefined && home.modules.length > 0) attrs[\"modules\"] = home.modules;\n records.add({ id: areaId, kind: \"area\", attrs, envelope: ENVELOPE });\n const pending = new Set(home.pending ?? []);\n for (const packageName of [...new Set([...home.packages, ...pending])]) {\n const fact = facts.npm.get(packageName);\n const published = fact?.published ?? !pending.has(packageName);\n const state = published ? \"published\" : home.packages.includes(packageName) ? \"unpublished\" : \"planned\";\n const npmRepository = fact?.repository === undefined ? undefined : find(home, fact.repository);\n const partOf = npmRepository === undefined ? homeId : addRepository(npmRepository, true, []);\n const packageAttrs: Record<string, unknown> = { name: packageName, registry: \"npm\", purl: npmPurl(packageName), state };\n if (published) packageAttrs[\"url\"] = `https://www.npmjs.com/package/${packageName}`;\n records.add({\n id: npmPackageId(packageName),\n kind: \"package\",\n attrs: packageAttrs,\n envelope: ENVELOPE,\n edges: [\n { type: \"part-of\", to: partOf },\n { type: \"covers\", to: areaId },\n ],\n });\n }\n for (const ref of home.alsoIn ?? []) {\n const repository = find(home, ref);\n if (repository === undefined) {\n skipped.push(`The area ${home.area}: a repository of alsoIn is not public.`);\n continue;\n }\n const id = repositoryId(repository.owner, repository.name);\n if (id !== homeId) addRepository(repository, true, [{ type: \"holds-copy\", to: areaId }]);\n }\n }\n records.add({\n id: GITHUB_SOURCE_ID,\n kind: \"source\",\n attrs: { title: \"The lists of the public repositories of each owner on GitHub\", url: \"https://docs.github.com/en/rest/repos/repos#list-repositories-for-a-user\" },\n });\n for (const repository of facts.repositories) {\n if (repository.fork !== true && repository.archived !== true) addRepository(repository, true, [], GITHUB_ENVELOPE);\n }\n return { records: records.sorted(), skipped };\n}\n","// The polite read of the URLs of the import: each request at the pace of its host, through polite-crawler/api.\nimport type { HomeAnswer } from \"@mark1russell7/conventions\";\nimport { errorMessage } from \"@mark1russell7/text\";\nimport { redactSecrets } from \"@mark1russell7/text/redact\";\nimport { fetchTransport, send, type Transport } from \"polite-crawler/api\";\nimport { HostScheduler, realClock } from \"polite-crawler/politeness\";\n\n/** The answers for a list of URLs: the text of each URL, or the reason why there is no text. */\nexport type UrlAnswers = ReadonlyMap<string, HomeAnswer>;\n\n/** A function that reads each URL and gives the answer for each URL. A fake of a test can give the answers at once. */\nexport type UrlFetch = (urls: readonly string[]) => UrlAnswers | Promise<UrlAnswers>;\n\n/** The name of the client in each request. The repository is the contact. */\nexport const USER_AGENT = \"canon-import/1 (+https://github.com/metrograph-labs/canon)\";\n\n/** The most requests in progress at one time. Each host has one request in progress at most. */\nexport const HOSTS_AT_ONCE = 4;\n\n/** The name of each API in a message. Another host has its own name in the message. */\nconst SOURCES: Readonly<Record<string, string>> = { \"api.github.com\": \"the GitHub API\", \"registry.npmjs.org\": \"the npm registry\" };\n\n/** The options of `politeFetch`. */\nexport interface PoliteFetchOptions {\n /** This value is a GitHub token. Only the requests to `api.github.com` send it, for the rate limit of a token. */\n readonly githubToken?: string | undefined;\n /** This function sends each request. The default is `fetchTransport` of `polite-crawler/api` with `USER_AGENT`. A test gives a fake. */\n readonly transport?: Transport | undefined;\n}\n\n/**\n * This function gives a fetch that reads each URL through `send` of `polite-crawler/api`. Each host has one request in\n * progress at most, and the policy of the crawler sets the rest between two requests of a host.\n *\n * - An answer 2xx gives its text. Another status gives the error `HTTP <status>`, as `githubFetch` of conventions does.\n * The fetch follows no redirect.\n * - A request with no answer, or a stopped host, gives the text of the error. The text has no token.\n */\nexport function politeFetch(options: PoliteFetchOptions = {}): (urls: readonly string[]) => Promise<UrlAnswers> {\n const transport = options.transport ?? fetchTransport({ userAgent: USER_AGENT });\n const pace = { scheduler: new HostScheduler(realClock, HOSTS_AT_ONCE), now: realClock.now };\n const token = options.githubToken === undefined || options.githubToken === \"\" ? undefined : options.githubToken;\n const answerOf = async (url: string): Promise<HomeAnswer> => {\n const host = new URL(url).host;\n const secrets = host === \"api.github.com\" && token !== undefined ? [token] : [];\n const headers: Record<string, string> = secrets.length > 0 ? { accept: \"application/vnd.github+json\", authorization: `Bearer ${String(token)}` } : {};\n try {\n const { reply } = await send(pace, transport, {\n source: SOURCES[host] ?? host,\n host,\n what: url,\n exchange: { method: \"GET\", url, headers, body: null },\n secrets,\n redact: redactSecrets,\n });\n return reply.status >= 200 && reply.status < 300 ? { text: reply.body } : { error: `HTTP ${String(reply.status)}` };\n } catch (error) {\n return { error: redactSecrets(errorMessage(error), secrets) };\n }\n };\n return async (urls) => new Map(await Promise.all(urls.map(async (url) => [url, await answerOf(url)] as const)));\n}\n","// The read of the live facts of the import: the public repositories of each owner, the facts of npm and the duplication atlas.\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { type Home, type HomeAnswer, OWNERS } from \"@mark1russell7/conventions\";\nimport { ATLAS_URL, readAtlas } from \"./atlas.ts\";\nimport { githubRepositoryOf, type HomeFacts, type NpmFact, type PublicRepository } from \"./homes.ts\";\nimport { politeFetch, type UrlAnswers, type UrlFetch } from \"./polite.ts\";\n\n/** The most pages of 100 repositories that the read asks for each owner. A full last page is an error. */\nexport const REPOSITORY_PAGES = 5;\n\n/** This function gives the URLs of the pages of the public repositories of each owner. */\nexport function repositoryPageUrls(): readonly string[] {\n return OWNERS.flatMap((owner) =>\n Array.from({ length: REPOSITORY_PAGES }, (_, page) => `https://api.github.com/users/${owner.login}/repos?type=owner&per_page=100&page=${String(page + 1)}`),\n );\n}\n\n/** This function gives the URL of the latest version of an npm package in the registry. */\nexport function npmLatestUrl(name: string): string {\n return `https://registry.npmjs.org/${name.replaceAll(\"/\", \"%2f\")}/latest`;\n}\n\n/** This function reads the public repositories of the answers of the pages. It throws when a page has no answer, or the last page is full. */\nexport function repositoriesOfPages(answers: UrlAnswers): readonly PublicRepository[] {\n const repositories: PublicRepository[] = [];\n for (const owner of OWNERS) {\n for (let page = 1; page <= REPOSITORY_PAGES; page += 1) {\n const url = `https://api.github.com/users/${owner.login}/repos?type=owner&per_page=100&page=${String(page)}`;\n const answer = answers.get(url);\n if (answer === undefined || \"error\" in answer) throw new Error(`GitHub gave no list of the repositories of ${owner.login}: ${answer?.error ?? \"no answer\"}`);\n const list = JSON.parse(answer.text) as readonly { name: string; owner: { login: string }; html_url: string; private: boolean; fork?: boolean; archived?: boolean; description?: string | null; default_branch?: string }[];\n if (page === REPOSITORY_PAGES && list.length === 100) throw new Error(`${owner.login} has more than ${String(REPOSITORY_PAGES * 100)} repositories: increase REPOSITORY_PAGES.`);\n for (const item of list) {\n if (!item.private) {\n repositories.push({ owner: item.owner.login, name: item.name, url: item.html_url, description: item.description ?? undefined, fork: item.fork === true, archived: item.archived === true, defaultBranch: item.default_branch });\n }\n }\n if (list.length < 100) break;\n }\n }\n return repositories;\n}\n\n/** This function reads the fact of npm for one package from the answer for its latest version. It throws on an error that is not 404. */\nexport function npmFactOf(name: string, answer: HomeAnswer | undefined): NpmFact {\n if (answer === undefined) throw new Error(`npm gave no answer for ${name}.`);\n if (\"error\" in answer) {\n if (answer.error === \"HTTP 404\") return { published: false };\n throw new Error(`npm gave an error for ${name}: ${answer.error}`);\n }\n const manifest = JSON.parse(answer.text) as { repository?: string | { url?: string } };\n const url = typeof manifest.repository === \"string\" ? manifest.repository : manifest.repository?.url;\n const repository = url === undefined ? undefined : githubRepositoryOf(url);\n return repository === undefined ? { published: true } : { published: true, repository };\n}\n\n/** This function gives the version of the installed `@mark1russell7/conventions`, which has the map. */\nexport function conventionsVersion(): string {\n const file = createRequire(import.meta.url).resolve(\"@mark1russell7/conventions/package.json\");\n return (JSON.parse(readFileSync(file, \"utf8\")) as { version: string }).version;\n}\n\n/**\n * This function reads the live facts of the homes from GitHub, npm and the duplication atlas. The facts are the public\n * repositories of each owner, the latest version of each package of the map, and the atlas. The default fetch is\n * `politeFetch` with no token. Each request goes at the pace of its host.\n */\nexport async function readHomeFacts(homes: readonly Home[], fetch: UrlFetch = politeFetch()): Promise<HomeFacts> {\n const names = [...new Set(homes.flatMap((home) => [...home.packages, ...(home.pending ?? [])]))].sort();\n const answers = await fetch([...repositoryPageUrls(), ...names.map(npmLatestUrl), ATLAS_URL]);\n const npm = new Map(names.map((name) => [name, npmFactOf(name, answers.get(npmLatestUrl(name)))]));\n return { repositories: repositoriesOfPages(answers), npm, version: conventionsVersion(), atlas: readAtlas(answers.get(ATLAS_URL)) };\n}\n","// The read of the grammar and of each record file from the folders of a repository.\nimport { readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { findFiles, toPosix } from \"@mark1russell7/files\";\nimport { GRAMMAR_FILE, ONTOLOGY_FOLDER, RECORD_SCHEMA_FILE } from \"./ids.ts\";\nimport type { EntityRecord, Grammar, JsonSchema, LoadedRecord, Ontology } from \"./types.ts\";\n\n/** This error tells that a file of the ontology is not valid JSON. The check gives each other problem as a `Problem`. */\nexport class OntologyReadError extends Error {\n /** The path of the file, relative to the root. */\n readonly path: string;\n\n constructor(path: string, message: string) {\n super(`${path}: ${message}`);\n this.name = \"OntologyReadError\";\n this.path = path;\n }\n}\n\n/** This function reads a JSON file. It throws an `OntologyReadError` with the relative path when the text is not JSON. */\nfunction readJson(root: string, path: string): unknown {\n const text = readFileSync(join(root, path), \"utf8\");\n try {\n return JSON.parse(text) as unknown;\n } catch (error) {\n throw new OntologyReadError(path, error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * This function reads the grammar, the schema of a record file and each record file of the repository at `root`. The\n * record files are each `.json` file under the folder `ontology`, in sorted order. The function does not check them:\n * `checkOntology` does that.\n */\nexport function readOntology(root: string): Ontology {\n const grammar = readJson(root, GRAMMAR_FILE) as Grammar;\n const recordSchema = readJson(root, RECORD_SCHEMA_FILE) as JsonSchema;\n const files = findFiles({ root, include: [`${ONTOLOGY_FOLDER}/**/*.json`] });\n const records: LoadedRecord[] = files.map((file) => {\n const path = toPosix(relative(root, file));\n return { path, record: readJson(root, path) as EntityRecord };\n });\n return { grammar, recordSchema, records };\n}\n","// The read of the test gates of each home repository from public data of GitHub: the tree of the default branch, the\n// workflow files and the package files of that tree, and the rules of the branch.\nimport { utcText } from \"@mark1russell7/algebra/clock\";\nimport type { HomeAnswer } from \"@mark1russell7/conventions\";\nimport { arrayOf, booleanOf, isRecord, readText, recordOf, textOf } from \"@mark1russell7/optional/read\";\nimport { parse } from \"yaml\";\nimport type { PublicRepository } from \"./homes.ts\";\nimport { repositoryId } from \"./ids.ts\";\nimport { politeFetch, type UrlFetch } from \"./polite.ts\";\nimport type { EntityRecord, GateFact, GateName, LoadedRecord, TestGates } from \"./types.ts\";\n\n/** The test gates of the read, in the order of the records. */\nexport const GATE_NAMES: readonly GateName[] = [\"mutation\", \"property\", \"speed\", \"rigs\"];\n\n/** The lane file of the mutation tests, when the caller of the workflow gives no input `lane`. */\nexport const MUTATION_LANE = \"mutation.json\";\n\n/** The file of the rig records of a repository. */\nexport const RIGS_FILE = \"docs/rigs.json\";\n\n/** The packages of property tests. A package file that names one of them in its dependencies has property tests. */\nexport const PROPERTY_PACKAGES: readonly string[] = [\"fast-check\", \"@mark1russell7/rigor-testkit\"];\n\n/** The package of the speed gates. */\nexport const BENCH_PACKAGE = \"@mark1russell7/rigor-bench\";\n\n/** The most rules of a branch that the read asks for. A full page is a no read. */\nexport const RULES_PAGE = 100;\n\n/** A home repository and the branch that the read examines. */\nexport interface GateRepository {\n readonly owner: string;\n readonly name: string;\n readonly branch: string;\n}\n\n/** This function gives the path of a branch in a URL: each part of the name, encoded. */\nfunction branchPath(branch: string): string {\n return branch.split(\"/\").map(encodeURIComponent).join(\"/\");\n}\n\n/** This function gives the URL of the full tree of the branch of a repository: one request for each repository. */\nexport function treeUrl(repository: GateRepository): string {\n return `https://api.github.com/repos/${repository.owner}/${repository.name}/git/trees/${branchPath(repository.branch)}?recursive=1`;\n}\n\n/** This function gives the URL of the rules of the branch of a repository. GitHub gives them with no token. */\nexport function rulesUrl(repository: GateRepository): string {\n return `https://api.github.com/repos/${repository.owner}/${repository.name}/rules/branches/${branchPath(repository.branch)}?per_page=${String(RULES_PAGE)}`;\n}\n\n/**\n * This function gives the URL of the branch of a repository. Its answer has the classic protection of the branch, with\n * its necessary checks. GitHub gives it with no token.\n */\nexport function branchUrl(repository: GateRepository): string {\n return `https://api.github.com/repos/${repository.owner}/${repository.name}/branches/${branchPath(repository.branch)}`;\n}\n\n/** This function gives the URL of the text of one file of the branch. The host of raw files is not the API. */\nexport function fileUrl(repository: GateRepository, path: string): string {\n return `https://raw.githubusercontent.com/${repository.owner}/${repository.name}/${branchPath(repository.branch)}/${path.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n}\n\n/** The files of a tree: the id of the content of each file, by its path. */\nexport interface Tree {\n readonly files: ReadonlyMap<string, string>;\n}\n\n/** A read that cannot tell the facts, and its reason. */\nexport interface NoRead {\n readonly no_read: string;\n}\n\n/** This function gives the text of the answer, or the reason why there is no text. */\nfunction textOrReason(answer: HomeAnswer | undefined, what: string): { readonly text: string } | NoRead {\n if (answer === undefined) return { no_read: `GitHub gave no answer for ${what}.` };\n if (\"error\" in answer) return { no_read: `GitHub gave ${answer.error} for ${what}.` };\n return { text: answer.text };\n}\n\n/** This function reads JSON. It gives undefined when the text is not JSON. */\nfunction jsonOf(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/**\n * This function reads the answer for a tree. A tree that GitHub truncated is a no read, because a missing file of such a\n * tree does not show that the file is absent. A 404 and each other error are a no read too.\n */\nexport function treeOf(answer: HomeAnswer | undefined): Tree | NoRead {\n const read = textOrReason(answer, \"the tree of the branch\");\n if (\"no_read\" in read) return read;\n const body = jsonOf(read.text);\n if (booleanOf(body, \"truncated\") === true) return { no_read: \"GitHub gave a truncated tree, so the read cannot see each file.\" };\n const items = arrayOf(body, \"tree\", (item) => (isRecord(item) ? item : undefined));\n if (items === undefined) return { no_read: \"The answer for the tree has no list of files.\" };\n const files = new Map<string, string>();\n for (const item of items) {\n const path = textOf(item, \"path\");\n const sha = textOf(item, \"sha\");\n if (textOf(item, \"type\") === \"blob\" && path !== undefined && sha !== undefined) files.set(path, sha);\n }\n return { files };\n}\n\n/** This function reads the names of the necessary checks from the answer for the rules of a branch. */\nexport function necessaryChecksOf(answer: HomeAnswer | undefined): { readonly checks: readonly string[] } | NoRead {\n const read = textOrReason(answer, \"the rules of the branch\");\n if (\"no_read\" in read) return read;\n const rules = jsonOf(read.text);\n if (!Array.isArray(rules)) return { no_read: \"The answer for the rules of the branch is not a list.\" };\n if (rules.length >= RULES_PAGE) return { no_read: `The branch has ${String(RULES_PAGE)} rules or more, and the read asks for one page.` };\n const checks = new Set<string>();\n for (const rule of rules) {\n if (textOf(rule, \"type\") !== \"required_status_checks\") continue;\n const parameters = recordOf(rule, \"parameters\");\n for (const check of arrayOf(parameters, \"required_status_checks\", (item) => textOf(item, \"context\")) ?? []) checks.add(check);\n }\n return { checks: [...checks].sort() };\n}\n\n/**\n * This function reads the names of the necessary checks of the classic protection from the answer for a branch. A\n * branch with no classic protection, or with checks that are not enforced, gives no check.\n */\nexport function classicChecksOf(answer: HomeAnswer | undefined): { readonly checks: readonly string[] } | NoRead {\n const read = textOrReason(answer, \"the branch\");\n if (\"no_read\" in read) return read;\n const branch = jsonOf(read.text);\n if (!isRecord(branch)) return { no_read: \"The answer for the branch is not a JSON object.\" };\n const protection = recordOf(branch, \"protection\");\n const required = recordOf(protection, \"required_status_checks\");\n if (booleanOf(protection, \"enabled\") !== true || required === undefined || textOf(required, \"enforcement_level\") === \"off\") return { checks: [] };\n const contexts = arrayOf(required, \"contexts\", readText) ?? [];\n const checks = arrayOf(required, \"checks\", (item) => textOf(item, \"context\")) ?? [];\n return { checks: [...new Set([...contexts, ...checks])].sort() };\n}\n\n/**\n * This function gives the necessary checks of a branch: the checks of its rulesets and of its classic protection. A\n * no read of one of the two is a no read, because the missing part can make a check necessary.\n */\nexport function branchChecksOf(rules: { readonly checks: readonly string[] } | NoRead, classic: { readonly checks: readonly string[] } | NoRead): { readonly checks: readonly string[] } | NoRead {\n if (\"no_read\" in rules) return rules;\n if (\"no_read\" in classic) return classic;\n return { checks: [...new Set([...rules.checks, ...classic.checks])].sort() };\n}\n\n/** This function tells if a path is a workflow of GitHub Actions. GitHub reads only the files at the top of the folder. */\nexport function isWorkflowPath(path: string): boolean {\n return /^\\.github\\/workflows\\/[^/]+\\.ya?ml$/.test(path);\n}\n\n/** This function tells if a path is a package file of the repository: not in `node_modules` and not in a fixture folder. */\nexport function isPackagePath(path: string): boolean {\n const parts = path.split(\"/\");\n return parts.at(-1) === \"package.json\" && !parts.some((part) => part === \"node_modules\" || /^(__)?fixtures?(__)?$/.test(part));\n}\n\n/** This function gives the paths of the files that the read needs from a tree: each workflow and each package file. */\nexport function filesToRead(tree: Tree): readonly string[] {\n return [...tree.files.keys()].filter((path) => isWorkflowPath(path) || isPackagePath(path)).sort();\n}\n\n/** A step of a job of a workflow. */\ninterface Step {\n readonly uses?: string | undefined;\n readonly run?: string | undefined;\n /** The inputs of the action that the step uses. */\n readonly with?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** A job of a workflow. */\ninterface Job {\n readonly id: string;\n /** The name of the check of the job: the name of the job, or its id. */\n readonly name: string;\n /** The reusable workflow that the job calls. */\n readonly uses?: string | undefined;\n /** The inputs of the reusable workflow. */\n readonly with?: Readonly<Record<string, unknown>> | undefined;\n readonly needs: readonly string[];\n readonly steps: readonly Step[];\n}\n\n/** A workflow file and its jobs. */\ninterface Workflow {\n readonly path: string;\n readonly jobs: readonly Job[];\n}\n\n/** This function reads the jobs of a workflow file. It gives a no read when the text is not a workflow. */\nfunction workflowOf(path: string, text: string): Workflow | NoRead {\n let document: unknown;\n try {\n document = parse(text) as unknown;\n } catch {\n return { no_read: `The workflow ${path} is not valid YAML.` };\n }\n const jobs = recordOf(document, \"jobs\");\n if (jobs === undefined) return { no_read: `The workflow ${path} has no jobs.` };\n return {\n path,\n jobs: Object.entries(jobs).map(([id, job]): Job => {\n const needs = isRecord(job) ? job[\"needs\"] : undefined;\n return {\n id,\n name: textOf(job, \"name\") ?? id,\n uses: textOf(job, \"uses\"),\n with: recordOf(job, \"with\"),\n needs: typeof needs === \"string\" ? [needs] : (arrayOf(job, \"needs\", readText) ?? []),\n steps: arrayOf(job, \"steps\", (step) => (isRecord(step) ? { uses: textOf(step, \"uses\"), run: textOf(step, \"run\"), with: recordOf(step, \"with\") } : undefined)) ?? [],\n };\n }),\n };\n}\n\n/** This function tells if a job uses the reusable workflow `file` of the template, or the copy of the template itself. */\nfunction callsTemplate(job: Job, file: string): boolean {\n const uses = job.uses ?? \"\";\n return (uses.startsWith(\"mark1russell7/template/\") || uses.startsWith(\"./\")) && new RegExp(`(^|/)\\\\.github/workflows/${file.replaceAll(\".\", \"\\\\.\")}(@|$)`).test(uses);\n}\n\n/** The paths of the action `gate-summary`: in the template, and in the copy of the template itself. */\nconst GATE_SUMMARY = [\"mark1russell7/template/.github/actions/gate-summary\", \"./.github/actions/gate-summary\"];\n\n/** This function tells if a step uses the action `gate-summary` of the template, at a commit or with no ref. */\nfunction usesGateSummary(step: Step): boolean {\n const uses = step.uses ?? \"\";\n const at = uses.indexOf(\"@\");\n return GATE_SUMMARY.includes(at === -1 ? uses : uses.slice(0, at));\n}\n\n/**\n * This function gives the kind of gate that the job marks: the input `gate` of its step `gate-summary` of the\n * template. A job with no marker, or with a word that is not a gate, gives undefined.\n */\nfunction markedGate(job: { readonly steps: readonly Step[] }): GateName | undefined {\n for (const step of job.steps) {\n const gate = usesGateSummary(step) ? step.with?.[\"gate\"] : undefined;\n const kind = GATE_NAMES.find((name) => name === gate);\n if (kind !== undefined) return kind;\n }\n return undefined;\n}\n\n/** A command that starts the tests of a package. */\nconst TEST_COMMAND = /\\b(vitest|(pnpm|npm|yarn)(\\s+-r|\\s+--recursive)?\\s+(run\\s+)?test)\\b/;\n\n/** A command or a step that starts a bench of `@mark1russell7/rigor-bench`. */\nconst BENCH_COMMAND = /\\b(rigor-gate-line|rigor-stamp|bench(mark)?)\\b/i;\n\n/** This function gives the checks of the jobs `seeds` and of each job that needs them, also through other jobs. */\nfunction checksOf(workflow: Workflow, seeds: readonly Job[]): readonly string[] {\n const ids = new Set(seeds.map((job) => job.id));\n let grew = ids.size > 0;\n while (grew) {\n grew = false;\n for (const job of workflow.jobs) {\n if (!ids.has(job.id) && job.needs.some((need) => ids.has(need))) {\n ids.add(job.id);\n grew = true;\n }\n }\n }\n return workflow.jobs.filter((job) => ids.has(job.id)).map((job) => (job.uses === undefined ? job.name : `${job.name} / *`));\n}\n\n/**\n * This function tells if the check `pattern` of a gate gives the check `name`. A `*` and each expression `${{ }}` match\n * any text. A job of a matrix with no name gives its values after its name, in parentheses.\n */\nexport function checkMatches(pattern: string, name: string): boolean {\n if (pattern.length > MAX_CHECK_TEXT || name.length > MAX_CHECK_TEXT) return false;\n const parts = literalParts(pattern);\n if (globMatches(parts, name)) return true;\n if (!name.endsWith(\")\")) return false;\n // A job of a matrix: the name, a space and its values in parentheses.\n for (let at = name.indexOf(\" (\"); at !== -1; at = name.indexOf(\" (\", at + 1)) if (globMatches(parts, name.slice(0, at))) return true;\n return false;\n}\n\n/** The longest check name or pattern that `checkMatches` reads. A longer text matches nothing. */\nconst MAX_CHECK_TEXT = 512;\n\n/**\n * This function gives the literal parts of a check pattern. A `*` and each expression `${{ }}` separate the parts. An\n * expression with no end is literal text. The function uses no regular expression, so its time is linear.\n */\nfunction literalParts(pattern: string): string[] {\n const parts: string[] = [];\n let part = \"\";\n for (let at = 0; at < pattern.length; ) {\n if (pattern[at] === \"*\") {\n parts.push(part);\n part = \"\";\n at++;\n continue;\n }\n const end = pattern.startsWith(\"${{\", at) ? pattern.indexOf(\"}}\", at + 3) : -1;\n if (end !== -1) {\n parts.push(part);\n part = \"\";\n at = end + 2;\n continue;\n }\n part += pattern[at] ?? \"\";\n at++;\n }\n parts.push(part);\n return parts;\n}\n\n/**\n * This function tells if `name` is the literal parts `parts` with any text between each two. The first part starts the\n * name, and the last part ends it. Each middle part takes its first place after the part before it.\n */\nfunction globMatches(parts: readonly string[], name: string): boolean {\n const first = parts[0] ?? \"\";\n if (parts.length === 1) return name === first;\n const last = parts.at(-1) ?? \"\";\n if (!name.startsWith(first) || name.length < first.length + last.length || !name.endsWith(last)) return false;\n const end = name.length - last.length;\n let at = first.length;\n for (const part of parts.slice(1, -1)) {\n const found = name.indexOf(part, at);\n if (found === -1 || found + part.length > end) return false;\n at = found + part.length;\n }\n return true;\n}\n\n/** The jobs of the workflows that `pick` selects, with the files of their workflows and their checks. */\ninterface Picked {\n readonly files: readonly string[];\n readonly checks: readonly string[];\n readonly jobs: readonly Job[];\n}\n\n/** This function gives the path of the workflow of the same repository that the job calls (`uses: ./path`), or undefined. */\nfunction localCallOf(job: Job): string | undefined {\n return job.uses?.startsWith(\"./\") === true ? job.uses.slice(2) : undefined;\n}\n\n/**\n * This function selects the jobs of each workflow with `pick`, and gives their files and their checks. A job that calls a\n * workflow of the same repository with a selected job is a selected job of its own workflow too. So a check that needs\n * the call (`CI OK` of `pull-request.yml`, for example) holds the gate.\n */\nfunction pickJobs(workflows: readonly Workflow[], pick: (job: Job) => boolean): Picked {\n const jobs = workflows.flatMap((workflow) => workflow.jobs.filter(pick));\n const selected = new Set<Job>(jobs);\n const called = new Set<string>();\n let grew = true;\n while (grew) {\n grew = false;\n for (const workflow of workflows) {\n if (!called.has(workflow.path) && workflow.jobs.some((job) => selected.has(job))) {\n called.add(workflow.path);\n grew = true;\n }\n for (const job of workflow.jobs) {\n const call = localCallOf(job);\n if (!selected.has(job) && call !== undefined && called.has(call)) {\n selected.add(job);\n grew = true;\n }\n }\n }\n }\n const files: string[] = [];\n const checks = new Set<string>();\n for (const workflow of workflows) {\n const seeds = workflow.jobs.filter((job) => selected.has(job));\n if (seeds.length === 0) continue;\n files.push(workflow.path);\n for (const check of checksOf(workflow, seeds)) checks.add(check);\n }\n return { files, checks: [...checks].sort(), jobs };\n}\n\n/** The dependencies of a package file. */\ninterface PackageFile {\n readonly path: string;\n readonly dependencies: ReadonlySet<string>;\n}\n\n/** This function reads the names of the dependencies of each kind from the text of a package file. */\nfunction packageOf(path: string, text: string): PackageFile | NoRead {\n const manifest = jsonOf(text);\n if (!isRecord(manifest)) return { no_read: `The package file ${path} is not a JSON object.` };\n const names = [\"dependencies\", \"devDependencies\", \"optionalDependencies\", \"peerDependencies\"].flatMap((field) => Object.keys(recordOf(manifest, field) ?? {}));\n return { path, dependencies: new Set(names) };\n}\n\n/** The facts of a gate from a list of parts. Each part has a text for `missing`, and the files that show it. */\nfunction factOf(parts: readonly { readonly missing: string; readonly files: readonly string[] }[], checks: readonly string[], rules: { readonly checks: readonly string[] } | NoRead): GateFact {\n const files = [...new Set(parts.flatMap((part) => part.files))].sort();\n const missing = parts.filter((part) => part.files.length === 0).map((part) => part.missing);\n if (missing.length > 0) return { exists: false, ...(files.length > 0 ? { files } : {}), missing };\n if (\"no_read\" in rules) return { exists: true, files, checks, no_read: rules.no_read };\n return { exists: true, necessary: checks.some((check) => rules.checks.some((name) => checkMatches(check, name))), files, checks };\n}\n\n/**\n * This function gives the fact of each test gate from a tree, the answers for its files and the rules of the branch. It\n * reads nothing itself.\n *\n * - mutation: a lane file (`mutation.json`, or the input `lane` of the caller) and a job that calls `reusable-mutation.yml`.\n * - property: a package file that names `fast-check` or `@mark1russell7/rigor-testkit`. Its checks are the checks of\n * each job that calls `reusable-ci.yml` or starts the tests, and of each job that needs such a job.\n * - speed: a package file that names `@mark1russell7/rigor-bench`, and a job that starts a bench. A summary job with\n * `gate: speed` (the marker of `gate-summary`) gives the bench jobs. With no marker in the repository, the read uses\n * a word rule. Then a bench job uses the action `stamp-gate`, a bin of the bench or a command with the word `bench`.\n * The bins are `rigor-gate-line` and `rigor-stamp`.\n * - rigs: the file `docs/rigs.json` and a job that calls `reusable-rigs.yml`.\n *\n * A file with no answer, or a file that the read cannot parse, gives a no read for each gate that needs it.\n */\nexport function gatesOf(tree: Tree, answers: ReadonlyMap<string, HomeAnswer | undefined>, rules: { readonly checks: readonly string[] } | NoRead): Readonly<Record<GateName, GateFact>> {\n const workflows: Workflow[] = [];\n const packages: PackageFile[] = [];\n let workflowFault: string | undefined;\n let packageFault: string | undefined;\n for (const path of filesToRead(tree)) {\n const read = textOrReason(answers.get(path), `the file ${path}`);\n const parsed = \"no_read\" in read ? read : isWorkflowPath(path) ? workflowOf(path, read.text) : packageOf(path, read.text);\n if (\"no_read\" in parsed) {\n if (isWorkflowPath(path)) workflowFault ??= parsed.no_read;\n else packageFault ??= parsed.no_read;\n } else if (\"jobs\" in parsed) workflows.push(parsed);\n else packages.push(parsed);\n }\n const naming = (names: readonly string[]): readonly string[] => packages.filter((file) => names.some((name) => file.dependencies.has(name))).map((file) => file.path);\n const has = (path: string): readonly string[] => (tree.files.has(path) ? [path] : []);\n\n const mutationJobs = pickJobs(workflows, (job) => callsTemplate(job, \"reusable-mutation.yml\"));\n const lanes = mutationJobs.jobs.map((job) => (typeof job.with?.[\"lane\"] === \"string\" ? job.with[\"lane\"] : MUTATION_LANE));\n const lane = lanes.find((path) => tree.files.has(path)) ?? lanes[0] ?? MUTATION_LANE;\n const mutation: GateFact =\n workflowFault !== undefined\n ? { no_read: workflowFault }\n : factOf(\n [\n { missing: `the lane file \\`${lane}\\``, files: has(lane) },\n { missing: \"a job that calls `reusable-mutation.yml` of `mark1russell7/template`\", files: mutationJobs.files },\n ],\n mutationJobs.checks,\n rules,\n );\n\n const propertyFiles = naming(PROPERTY_PACKAGES);\n const testJobs = pickJobs(workflows, (job) => callsTemplate(job, \"reusable-ci.yml\") || job.steps.some((step) => TEST_COMMAND.test(step.run ?? \"\")));\n const propertyPart = { missing: \"a package file that names `fast-check` or `@mark1russell7/rigor-testkit` in its dependencies\", files: propertyFiles };\n const property: GateFact =\n packageFault !== undefined\n ? { no_read: packageFault }\n : propertyFiles.length > 0 && workflowFault !== undefined\n ? { exists: true, files: propertyFiles, no_read: workflowFault }\n : factOf([propertyPart], testJobs.checks, rules);\n\n // The marker is exact, so a repository with a marked summary job does not use the word rule (C41).\n const marked = workflows.some((workflow) => workflow.jobs.some((job) => markedGate(job) === \"speed\"));\n const benchJobs = pickJobs(workflows, (job) =>\n marked ? markedGate(job) === \"speed\" : job.steps.some((step) => (step.uses ?? \"\").includes(\"/.github/actions/stamp-gate\") || BENCH_COMMAND.test(step.run ?? \"\")),\n );\n const speed: GateFact =\n (packageFault ?? workflowFault) !== undefined\n ? { no_read: packageFault ?? workflowFault ?? \"\" }\n : factOf(\n [\n { missing: `a package file that names \\`${BENCH_PACKAGE}\\` in its dependencies`, files: naming([BENCH_PACKAGE]) },\n { missing: \"a job that starts a bench: a summary job with `gate: speed`, the action `stamp-gate`, the bin `rigor-gate-line` or `rigor-stamp`, or a command `bench`\", files: benchJobs.files },\n ],\n benchJobs.checks,\n rules,\n );\n\n const rigsJobs = pickJobs(workflows, (job) => callsTemplate(job, \"reusable-rigs.yml\"));\n const rigs: GateFact =\n workflowFault !== undefined\n ? { no_read: workflowFault }\n : factOf(\n [\n { missing: `the file \\`${RIGS_FILE}\\``, files: has(RIGS_FILE) },\n { missing: \"a job that calls `reusable-rigs.yml` of `mark1russell7/template`\", files: rigsJobs.files },\n ],\n rigsJobs.checks,\n rules,\n );\n\n return { mutation, property, speed, rigs };\n}\n\n/** This function gives the time of a read in the form of the records: UTC, to the second (RFC 3339). */\nfunction timeText(ms: number): string {\n const text = utcText(ms);\n if (text === undefined) throw new RangeError(`The time ${String(ms)} of the read is not an instant in the years 1 to 9999.`);\n return text;\n}\n\n/** This function gives a no read for each gate. */\nfunction noReadOfEach(reason: string): Readonly<Record<GateName, GateFact>> {\n return { mutation: { no_read: reason }, property: { no_read: reason }, speed: { no_read: reason }, rigs: { no_read: reason } };\n}\n\n/**\n * This function reads the test gates of each repository. The default fetch is `politeFetch` with no token, so each\n * request goes at the pace of its host. The read makes two rounds of requests:\n *\n * 1. the tree, the rules and the classic protection of the branch of each repository, from the API of GitHub,\n * 2. each workflow file and each package file of each tree, from the host of raw files. Two files with the same content\n * id give one request.\n *\n * A repository whose tree has no read gives a no read for each gate. The read does not throw for one repository.\n */\nexport async function readTestGates(repositories: readonly GateRepository[], fetch: UrlFetch = politeFetch(), now: () => number = Date.now): Promise<ReadonlyMap<string, TestGates>> {\n const first = await fetch(repositories.flatMap((repository) => [treeUrl(repository), rulesUrl(repository), branchUrl(repository)]));\n const trees = repositories.map((repository) => ({\n repository,\n tree: treeOf(first.get(treeUrl(repository))),\n rules: branchChecksOf(necessaryChecksOf(first.get(rulesUrl(repository))), classicChecksOf(first.get(branchUrl(repository)))),\n }));\n const urlOfContent = new Map<string, string>();\n for (const { repository, tree } of trees) {\n if (\"no_read\" in tree) continue;\n for (const path of filesToRead(tree)) {\n const sha = tree.files.get(path) ?? \"\";\n if (!urlOfContent.has(sha)) urlOfContent.set(sha, fileUrl(repository, path));\n }\n }\n const second = await fetch([...new Set(urlOfContent.values())]);\n const readAt = timeText(now());\n const result = new Map<string, TestGates>();\n for (const { repository, tree, rules } of trees) {\n const answers = new Map<string, HomeAnswer | undefined>();\n if (!(\"no_read\" in tree)) for (const path of filesToRead(tree)) answers.set(path, second.get(urlOfContent.get(tree.files.get(path) ?? \"\") ?? \"\"));\n const gates = \"no_read\" in tree ? noReadOfEach(tree.no_read) : gatesOf(tree, answers, rules);\n result.set(repositoryId(repository.owner, repository.name), { read_at: readAt, branch: repository.branch, ...(\"no_read\" in rules ? {} : { necessary_checks: rules.checks }), gates });\n }\n return result;\n}\n\n/**\n * This function gives the home repositories that the read examines. Each is a record of kind repository that exists\n * and is the home of an area. The lists of GitHub give its default branch. A repository with no known default branch\n * is not in the list.\n */\nexport function gateRepositoriesOf(records: readonly EntityRecord[], repositories: readonly PublicRepository[]): readonly GateRepository[] {\n const branches = new Map(repositories.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository.defaultBranch]));\n const list: GateRepository[] = [];\n for (const record of records) {\n if (record.kind !== \"repository\" || record.attrs[\"exists\"] !== true || !(record.edges ?? []).some((edge) => edge.type === \"home-of\")) continue;\n const owner = String(record.attrs[\"owner\"]);\n const name = String(record.attrs[\"name\"]);\n const branch = branches.get(`${owner}/${name}`.toLowerCase());\n if (branch !== undefined && branch !== \"\") list.push({ owner, name, branch });\n }\n return list;\n}\n\n/** This function gives the text of the facts of a read with no time, to compare two reads. */\nfunction factText(gates: unknown): string {\n if (!isRecord(gates)) return \"\";\n const { read_at: _time, ...facts } = gates;\n return JSON.stringify(facts);\n}\n\n/**\n * This function adds the test gates of each repository to its record as the attribute `test_gates`. When the earlier\n * record of a repository has the same facts, the new record keeps the earlier time. Thus a read with no change writes\n * no file.\n */\nexport function withTestGates(records: readonly EntityRecord[], gates: ReadonlyMap<string, TestGates>, earlier: readonly LoadedRecord[] = []): readonly EntityRecord[] {\n const old = new Map(earlier.map(({ record }) => [record.id, record.attrs[\"test_gates\"]]));\n return records.map((record) => {\n const read = gates.get(record.id);\n if (read === undefined || record.kind !== \"repository\") return record;\n const before = old.get(record.id);\n const time = isRecord(before) && factText(before) === factText(read) ? textOf(before, \"read_at\") : undefined;\n return { ...record, attrs: { ...record.attrs, test_gates: time === undefined ? read : { ...read, read_at: time } } };\n });\n}\n","// The write of records to their files, and the drift between the files and the records that a program makes.\nimport { mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { pathOfId } from \"./ids.ts\";\nimport type { EntityRecord, LoadedRecord } from \"./types.ts\";\n\n/** This function gives the text of the file of a record: JSON with two spaces and a last line end. */\nexport function recordText(record: EntityRecord): string {\n return `${JSON.stringify(record, null, 2)}\\n`;\n}\n\n/** The changes of the files that make the files agree with a set of records. */\nexport interface WritePlan {\n /** The text of each file to write, by its path relative to the root. */\n readonly write: ReadonlyMap<string, string>;\n /** The files to remove: each file that a program made before, with no record in the new set. */\n readonly remove: readonly string[];\n /** The files that the plan does not write, because a person wrote their record. The program does not own them. */\n readonly keep: readonly string[];\n}\n\n/**\n * This function plans the changes that make the files agree with the records `records`. The program that made the\n * records owns each existing record for which `owns` is true. A file of such a record with no new record is removed.\n * The plan writes only the files whose text changes. It does not write over a record that the program does not own.\n */\nexport function planWrite(root: string, records: readonly EntityRecord[], existing: readonly LoadedRecord[], owns: (record: EntityRecord) => boolean): WritePlan {\n const write = new Map<string, string>();\n const others = new Set(existing.filter(({ record }) => !owns(record)).map(({ path }) => path));\n const keep: string[] = [];\n for (const record of records) {\n const path = pathOfId(record.id);\n if (others.has(path)) {\n keep.push(path);\n continue;\n }\n const text = recordText(record);\n let old: string | undefined;\n try {\n old = readFileSync(join(root, path), \"utf8\");\n } catch {\n old = undefined;\n }\n if (old?.replace(/\\r\\n/g, \"\\n\") !== text) write.set(path, text);\n }\n const kept = new Set(records.map((record) => pathOfId(record.id)));\n const remove = existing.filter(({ path, record }) => owns(record) && !kept.has(path)).map(({ path }) => path);\n return { write, remove, keep };\n}\n\n/** This function tells if a plan changes no file. */\nexport function isEmptyPlan(plan: WritePlan): boolean {\n return plan.write.size === 0 && plan.remove.length === 0;\n}\n\n/** This function applies a plan: it writes each file, with its folder, and removes each file of `remove`. */\nexport function applyPlan(root: string, plan: WritePlan): void {\n for (const [path, text] of plan.write) {\n mkdirSync(dirname(join(root, path)), { recursive: true });\n writeFileSync(join(root, path), text);\n }\n for (const path of plan.remove) rmSync(join(root, path));\n}\n","// The command line of the ontology: check the data, give the targets, and import the map of homes.\nimport { dirname, join } from \"node:path\";\nimport { HOMES } from \"@mark1russell7/conventions\";\nimport { findUp } from \"@mark1russell7/files\";\nimport { staleGenerated, writeGenerated } from \"@mark1russell7/ontology/node\";\nimport type { Printer } from \"@mark1russell7/text/print\";\nimport { ATLAS_SOURCE_ID, ATLAS_URL, readAtlas, recordsFromAtlas } from \"./atlas.ts\";\nimport { applyBoard, type BoardAction, BOARD_LIMIT, claimCommandOf, decideClaim, isExpired, type IssueApi, planBoard, targetOfIssue } from \"./board.ts\";\nimport { checkOntology } from \"./check.ts\";\nimport { CLONE_FLOOR, cloneGroups, cloneReport } from \"./clones.ts\";\nimport { ENGINE_FOLDER, ENGINE_GENERATE_OPTIONS, engineRegistry, loadIntoEngine } from \"./engine.ts\";\nimport { readHomeFacts } from \"./facts.ts\";\nimport { politeFetch, type UrlFetch } from \"./polite.ts\";\nimport { IMPORT_SOURCE_IDS, recordsFromHomes } from \"./homes.ts\";\nimport { GRAMMAR_FILE } from \"./ids.ts\";\nimport { readOntology } from \"./load.ts\";\nimport { claimFails, resultClaimsOf } from \"./results.ts\";\nimport { targetsOf } from \"./targets.ts\";\nimport { gateRepositoriesOf, readTestGates, withTestGates } from \"./test-gates.ts\";\nimport type { EntityRecord, Ontology } from \"./types.ts\";\nimport { applyPlan, isEmptyPlan, planWrite, type WritePlan } from \"./write.ts\";\n\n/** The help text of the command line. */\nexport const USAGE: string = `Usage: canon <command> [--root <folder>]\n\nCommands:\n check Check the grammar and each record. Exit code 1 when there is a problem.\n targets Show the targets of the target query, the claimable targets first.\n targets --json Give the targets as JSON.\n targets --write Write the targets to ontology/target/.\n targets --check Exit code 1 when the files of ontology/target/ do not agree with the query.\n results Show each claim that needs a result record, and its state: checked, partial or not checked.\n results --json Give the claims as JSON.\n results --check Exit code 1 when a claim is not checked, or a status claim is partial.\n engine Load each record into the ontology engine, and check the files of schema/engine/.\n engine --write Write the files that the engine makes from the grammar to schema/engine/.\n import Read the map of homes and the live facts, and write the records of the map.\n board Show the changes that make the target board agree with the target query.\n board --apply Make the changes: open, change and close the issues of the board.\n claim --issue <number> --user <login> --comment <text>\n Decide a comment /claim or /unclaim on an issue of the board, and write the answer.\n clones [--floor <n>]\n Read the duplication atlas, and show the cloned code that no home covers, as Markdown.\n The report keeps a class with n or more copied syntax nodes (default ${String(CLONE_FLOOR)}).\n\nThe commands board and claim read the token of GitHub from GITHUB_TOKEN. The commands import and clones\nsend it to the API of GitHub when it is set. They make each request at the pace of its host.\n\nThe root is the folder of ${GRAMMAR_FILE}: the current folder or a parent of it.`;\n\n/** This function finds the root of the repository: the folder whose `schema` folder has the grammar. */\nexport function findRoot(from: string): string | undefined {\n const grammar = findUp(GRAMMAR_FILE, from);\n return grammar === null ? undefined : dirname(dirname(grammar));\n}\n\n/** This function tells if a record is one of the sources `sources`, or comes from one of them. */\nfunction fromSources(record: EntityRecord, sources: readonly string[]): boolean {\n return sources.includes(record.id) || (record.envelope?.source_ids ?? []).some((id) => sources.includes(id));\n}\n\n/** This function writes the changes of a plan as lines. */\nfunction showPlan(printer: Printer, plan: WritePlan): void {\n for (const path of plan.write.keys()) printer.line(`write ${path}`);\n for (const path of plan.remove) printer.line(`remove ${path}`);\n for (const path of plan.keep) printer.warn(`A person wrote ${path}, so the program keeps it.`);\n}\n\n/** This function writes the problems of the check. It gives the exit code: 0 with no problem, else 1. */\nfunction check(printer: Printer, ontology: Ontology): number {\n const problems = checkOntology(ontology);\n for (const problem of problems) printer.status(\"fail\", `${problem.path}: ${problem.message}`);\n if (problems.length > 0) return 1;\n printer.status(\"ok\", `${String(ontology.records.length)} records agree with the grammar.`);\n return 0;\n}\n\n/**\n * This function does the command `engine` (roadmap C18). It loads each record into the ontology engine, and it compares the\n * files of the engine with a new generation. It gives the exit code: 0 when the engine keeps each value and the files agree.\n */\nasync function engine(printer: Printer, root: string, ontology: Ontology, flags: ReadonlySet<string>): Promise<number> {\n const registry = engineRegistry(ontology.grammar);\n const folder = join(root, ENGINE_FOLDER);\n if (flags.has(\"--write\")) {\n for (const name of await writeGenerated(registry, folder, ENGINE_GENERATE_OPTIONS)) printer.line(`write ${ENGINE_FOLDER}/${name}`);\n }\n const load = loadIntoEngine(registry, ontology.records);\n for (const problem of load.problems) printer.status(\"fail\", problem);\n const stale = await staleGenerated(registry, folder, ENGINE_GENERATE_OPTIONS);\n for (const name of stale) {\n printer.status(\"fail\", `${ENGINE_FOLDER}/${name} does not agree with the grammar. Start \\`pnpm canon engine --write\\`, and commit the files.`);\n }\n if (load.problems.length > 0 || stale.length > 0) return 1;\n printer.status(\"ok\", `The engine keeps each value of ${String(load.entities.length)} records and ${String(load.edges.length)} relations.`);\n return 0;\n}\n\n/** This function runs the command `results`. It gives the exit code. */\nfunction results(printer: Printer, ontology: Ontology, flags: ReadonlySet<string>): number {\n const claims = resultClaimsOf(ontology);\n if (flags.has(\"--json\")) {\n printer.json(claims);\n return 0;\n }\n const open = claims.filter(claimFails);\n if (claims.length > 0) {\n printer.table(\n claims.map((claim) => [claim.state, claim.kind === \"status\" ? (claim.status ?? \"\") : `solved by ${claim.function ?? \"\"}`, claim.problem, claim.results.join(\", \")]),\n { head: [\"state\", \"claim\", \"problem\", \"results\"] },\n );\n }\n const total = `${String(claims.length - open.length)} of ${String(claims.length)} claims have a result record of the necessary scope.`;\n if (flags.has(\"--check\") && open.length > 0) {\n printer.status(\"fail\", `${total} Add a result for each claim that is not checked. A status claim needs a result with the scope of its problem.`);\n return 1;\n }\n printer.status(open.length === 0 ? \"ok\" : \"info\", total);\n return 0;\n}\n\n/** This function runs the command `targets`. It gives the exit code. */\nfunction targets(printer: Printer, root: string, ontology: Ontology, flags: ReadonlySet<string>): number {\n const list = targetsOf(ontology);\n if (flags.has(\"--json\")) {\n printer.json(list);\n return 0;\n }\n if (flags.has(\"--write\") || flags.has(\"--check\")) {\n const plan = planWrite(root, list, ontology.records, (record) => record.kind === \"target\");\n if (flags.has(\"--write\")) {\n applyPlan(root, plan);\n showPlan(printer, plan);\n printer.status(\"ok\", `${String(list.length)} targets.`);\n return 0;\n }\n if (isEmptyPlan(plan)) {\n printer.status(\"ok\", `The ${String(list.length)} files of ontology/target/ agree with the target query.`);\n return 0;\n }\n showPlan(printer, plan);\n printer.status(\"fail\", \"The files of ontology/target/ do not agree with the target query. Start `pnpm canon targets --write`, and commit the files.\");\n return 1;\n }\n printer.table(\n list.map((target) => [target.attrs.claimable ? \"yes\" : \"no\", target.attrs.size, target.attrs.home, target.attrs.title]),\n { head: [\"claimable\", \"size\", \"repository\", \"title\"] },\n );\n printer.line(`${String(list.filter((target) => target.attrs.claimable).length)} of ${String(list.length)} targets are claimable.`);\n return 0;\n}\n\n/**\n * This function runs the command `import`. It gives the exit code. When the read of the duplication atlas fails, the\n * import does not own the records of the atlas, so the old candidates stay.\n */\nasync function importHomes(printer: Printer, root: string, ontology: Ontology, options: CliOptions): Promise<number> {\n const fetch = options.fetch ?? politeFetch();\n const facts = await readHomeFacts(HOMES, fetch);\n const result = recordsFromHomes(HOMES, facts);\n const gates = await readTestGates(gateRepositoriesOf(result.records, facts.repositories), fetch, options.now);\n const homes = withTestGates(result.records, gates, ontology.records);\n const atlas = facts.atlas !== undefined && \"atlas\" in facts.atlas ? recordsFromAtlas(facts.atlas.atlas, facts.repositories, result.records) : undefined;\n const sources = atlas === undefined ? IMPORT_SOURCE_IDS : [...IMPORT_SOURCE_IDS, ATLAS_SOURCE_ID];\n const records = [...homes, ...(atlas?.records ?? [])];\n const plan = planWrite(root, records, ontology.records, (record) => fromSources(record, sources));\n applyPlan(root, plan);\n showPlan(printer, plan);\n for (const text of [...result.skipped, ...(atlas?.skipped ?? [])]) printer.warn(text);\n for (const [id, read] of gates) {\n const reasons = [...new Set(Object.values(read.gates).flatMap((gate) => (gate.no_read === undefined ? [] : [gate.no_read])))];\n if (reasons.length > 0) printer.warn(`The test gates of ${id} have no full read. ${reasons.join(\" \")}`);\n }\n if (facts.atlas !== undefined && \"error\" in facts.atlas) printer.warn(`The import keeps the old candidates. ${facts.atlas.error}`);\n printer.status(\"ok\", `${String(records.length)} records of the map of homes, of the lists of GitHub and of the duplication atlas.`);\n return 0;\n}\n\n/** The services of the commands that read or change GitHub. A test gives fakes. */\nexport interface CliOptions {\n /** This function gives the API of the issues of the board. It throws when there is no token. */\n readonly issues?: (() => IssueApi) | undefined;\n /** This function gives the current time, in milliseconds since 1970. The default is `Date.now`. */\n readonly now?: (() => number) | undefined;\n /** This function reads the URLs of the commands `import` and `clones`. The default is `politeFetch` with no token. */\n readonly fetch?: UrlFetch | undefined;\n}\n\n/** This function gives the value after the option `name`, or undefined. */\nfunction valueOf(args: readonly string[], name: string): string | undefined {\n const index = args.indexOf(name);\n return index < 0 ? undefined : args[index + 1];\n}\n\n/** This function writes a step of the board as a line. */\nfunction actionLine(action: BoardAction): string {\n if (action.kind === \"create\") return `open ${action.target}`;\n if (action.kind === \"update\") return `${action.reopen ? \"reopen \" : \"change \"} #${String(action.number)} ${action.target}`;\n if (action.kind === \"close\") return `close #${String(action.number)} ${action.target} (${action.reason})`;\n return `release #${String(action.number)} ${action.target} (${action.users.join(\", \")})`;\n}\n\n/** This function runs the command `clones`. It gives the exit code: 1 when the read of the atlas fails. */\nasync function clones(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const floorText = valueOf(args, \"--floor\");\n const floor = floorText === undefined ? CLONE_FLOOR : Number(floorText);\n if (!Number.isInteger(floor) || floor < 0) {\n printer.status(\"fail\", `The floor ${floorText ?? \"\"} is not a whole number of 0 or more.`);\n return 2;\n }\n const read = readAtlas((await (options.fetch ?? politeFetch())([ATLAS_URL])).get(ATLAS_URL));\n if (\"error\" in read) {\n printer.status(\"fail\", read.error);\n return 1;\n }\n const records = ontology.records.map((loaded) => loaded.record);\n printer.line(cloneReport(cloneGroups(read.atlas, records, floor), records, floor));\n return 0;\n}\n\n/** This function gives the API of the issues, or writes why there is none. */\nfunction issueApi(printer: Printer, options: CliOptions): IssueApi | undefined {\n if (options.issues === undefined) {\n printer.status(\"fail\", \"This command needs the API of GitHub. Set GITHUB_TOKEN.\");\n return undefined;\n }\n return options.issues();\n}\n\n/** This function runs the command `board`. It gives the exit code. */\nasync function board(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const limitText = valueOf(args, \"--limit\");\n const limit = limitText === undefined ? BOARD_LIMIT : Number(limitText);\n if (!Number.isSafeInteger(limit) || limit < 0) {\n printer.status(\"fail\", `The limit ${String(limitText)} is not a whole number of 0 or more.`);\n return 2;\n }\n const api = issueApi(printer, options);\n if (api === undefined) return 2;\n const now = (options.now ?? Date.now)();\n const issues = await api.issues();\n const pulls = new Set<string>();\n for (const issue of issues.filter((candidate) => candidate.state === \"open\" && isExpired(candidate, now))) {\n const id = targetOfIssue(issue.body);\n if (id !== undefined && (await api.hasOpenPull(id))) pulls.add(id);\n }\n const actions = planBoard({ targets: targetsOf(ontology), issues, now, pulls, limit });\n for (const action of actions) printer.line(actionLine(action));\n if (!args.includes(\"--apply\")) {\n printer.status(\"info\", `${String(actions.length)} changes. Give --apply to make them.`);\n return 0;\n }\n const created = await applyBoard(api, actions);\n printer.status(\"ok\", `${String(actions.length)} changes, ${String(created.length)} new issues.`);\n return 0;\n}\n\n/** This function runs the command `claim`. It gives the exit code. */\nasync function claim(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const number = Number(valueOf(args, \"--issue\"));\n const user = valueOf(args, \"--user\") ?? \"\";\n const command = claimCommandOf(valueOf(args, \"--comment\") ?? \"\");\n if (!Number.isSafeInteger(number) || number < 1 || user === \"\") {\n printer.status(\"fail\", \"Give --issue <number>, --user <login> and --comment <text>.\");\n return 2;\n }\n if (command === undefined) {\n printer.status(\"info\", \"The comment is not /claim or /unclaim. No change.\");\n return 0;\n }\n const api = issueApi(printer, options);\n if (api === undefined) return 2;\n const issues = await api.issues();\n const issue = issues.find((candidate) => candidate.number === number);\n if (issue === undefined) {\n printer.status(\"info\", `The issue #${String(number)} is not an issue of the board. No change.`);\n return 0;\n }\n const id = targetOfIssue(issue.body);\n const target = targetsOf(ontology).find((candidate) => candidate.id === id);\n const decision = decideClaim({ command, user, issue, target, issues, now: (options.now ?? Date.now)() });\n if (decision.kind === \"set\") {\n const after = await api.update(number, { assignees: decision.assignees });\n if (command === \"claim\" && !after.assignees.includes(user)) {\n await api.comment(number, `GitHub did not assign \\`${user}\\`, so the claim did not start. Write the comment \\`/claim\\` again.`);\n printer.status(\"fail\", `GitHub did not assign ${user} to #${String(number)}.`);\n return 1;\n }\n }\n await api.comment(number, decision.comment);\n printer.status(decision.kind === \"set\" ? \"ok\" : \"info\", decision.comment);\n return 0;\n}\n\n/**\n * This function runs the command line with the arguments `args`, and gives the exit code. It writes only to `printer`.\n * The folder `cwd` is the start of the search for the root. The commands `board` and `claim` use `options.issues`.\n */\nexport async function runCli(args: readonly string[], printer: Printer, cwd: string, options: CliOptions = {}): Promise<number> {\n const rootIndex = args.indexOf(\"--root\");\n const rootArg = rootIndex < 0 ? undefined : args[rootIndex + 1];\n const rest = rootIndex < 0 ? args : [...args.slice(0, rootIndex), ...args.slice(rootIndex + 2)];\n const [command, ...flagList] = rest;\n const flags = new Set(flagList);\n if (command === undefined || command === \"--help\" || command === \"help\") {\n printer.line(USAGE);\n return command === undefined ? 2 : 0;\n }\n const root = rootArg ?? findRoot(cwd);\n if (root === undefined) {\n 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>.`);\n return 2;\n }\n try {\n const ontology = readOntology(root);\n if (command === \"check\") return check(printer, ontology);\n if (command === \"targets\") return targets(printer, root, ontology, flags);\n if (command === \"results\") return results(printer, ontology, flags);\n if (command === \"engine\") return await engine(printer, root, ontology, flags);\n if (command === \"import\") return await importHomes(printer, root, ontology, options);\n if (command === \"board\") return await board(printer, ontology, flagList, options);\n if (command === \"claim\") return await claim(printer, ontology, flagList, options);\n if (command === \"clones\") return await clones(printer, ontology, flagList, options);\n } catch (error) {\n printer.error(error);\n return 1;\n }\n printer.status(\"fail\", `The command ${command} is not a command of canon.`);\n printer.line(USAGE);\n return 2;\n}\n","// The API of the issues of a GitHub repository, for the target board. It sends each request through a REST client of\n// @procedures/gh, which holds the limits of GitHub.\nimport { arrayOf, numberOf, readArray, recordOf, textOf, timeOf } from \"@mark1russell7/optional/read\";\nimport type { RestAnswer, RestClient, RestRequest } from \"@procedures/gh\";\nimport { type BoardIssue, type IssueApi, type IssueChange, type IssueText, TARGET_LABEL } from \"./board.ts\";\n\n/** The most items of one page of a list. */\nconst PAGE = 100;\n\n/** The most pages of the list of issues: 1,000 issues. */\nconst MAX_PAGES = 10;\n\n/** The colors of the labels of the board, by the start of their names. */\nconst LABEL_COLOR = { target: \"0e8a16\", gap: \"c5def5\" } as const;\n\n/** This error tells that GitHub refused a request of the board. Its text has no token and no body of an answer. */\nexport class IssueApiError extends Error {\n override readonly name = \"IssueApiError\";\n /** This number is the status of the answer of GitHub. */\n readonly status: number;\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n\n/** This function gives the issue of an item of the REST API, or undefined for a pull request or an item that is not an issue. */\nexport function issueOfItem(item: unknown): BoardIssue | undefined {\n const number = numberOf(item, \"number\");\n const title = textOf(item, \"title\");\n const state = textOf(item, \"state\");\n if (number === undefined || title === undefined || (state !== \"open\" && state !== \"closed\")) return undefined;\n if (recordOf(item, \"pull_request\") !== undefined) return undefined;\n return {\n number,\n title,\n body: textOf(item, \"body\") ?? \"\",\n state,\n labels: arrayOf(item, \"labels\", (label) => textOf(label, \"name\")) ?? [],\n assignees: arrayOf(item, \"assignees\", (user) => textOf(user, \"login\")) ?? [],\n };\n}\n\n/** This function gives the time of the last event that assigned one of the assignees, or undefined when there is none. */\nexport function claimTimeOf(events: unknown, assignees: readonly string[]): number | undefined {\n let last: number | undefined;\n for (const event of readArray(events, (value) => value) ?? []) {\n const at = timeOf(event, \"created_at\");\n const login = textOf(recordOf(event, \"assignee\"), \"login\");\n if (textOf(event, \"event\") === \"assigned\" && at !== undefined && login !== undefined && assignees.includes(login)) last = Math.max(last ?? at, at);\n }\n return last;\n}\n\n/** The body of a PATCH of an issue for a change. */\nfunction patchOf(change: IssueChange): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (change.title !== undefined) body[\"title\"] = change.title;\n if (change.body !== undefined) body[\"body\"] = change.body;\n if (change.labels !== undefined) body[\"labels\"] = change.labels;\n if (change.state !== undefined) body[\"state\"] = change.state;\n if (change.stateReason !== undefined) body[\"state_reason\"] = change.stateReason;\n if (change.assignees !== undefined) body[\"assignees\"] = change.assignees;\n return body;\n}\n\n/**\n * This function gives the API of the issues of the repository `owner/name` through a REST client of GitHub. Each\n * request stops at `signal`. A status of 400 or more throws an `IssueApiError`.\n */\nexport function githubIssueApi(client: Pick<RestClient, \"request\">, repository: string, signal: AbortSignal): IssueApi {\n const base = `/repos/${repository}`;\n const send = async (request: RestRequest, what: string): Promise<RestAnswer> => {\n const answer = await client.request(request, signal);\n if (answer.status >= 400) throw new IssueApiError(`GitHub refused ${what} of ${repository} with the status ${String(answer.status)}.`, answer.status);\n return answer;\n };\n const issueAnswer = (answer: RestAnswer, what: string): BoardIssue => {\n const issue = issueOfItem(answer.body);\n if (issue === undefined) throw new IssueApiError(`GitHub gave no issue for ${what} of ${repository}.`, answer.status);\n return issue;\n };\n return {\n async issues() {\n const issues: BoardIssue[] = [];\n for (let page = 1; page <= MAX_PAGES; page += 1) {\n const query = { labels: TARGET_LABEL, state: \"all\", per_page: String(PAGE), page: String(page) };\n const items = readArray((await send({ method: \"GET\", path: `${base}/issues`, query }, \"the list of issues\")).body, (item) => item) ?? [];\n issues.push(...items.flatMap((item) => issueOfItem(item) ?? []));\n if (items.length < PAGE) break;\n }\n const claimed: BoardIssue[] = [];\n for (const issue of issues) {\n if (issue.state !== \"open\" || issue.assignees.length === 0) {\n claimed.push(issue);\n continue;\n }\n const events = await send({ method: \"GET\", path: `${base}/issues/${String(issue.number)}/events`, query: { per_page: String(PAGE) } }, \"the events of an issue\");\n claimed.push({ ...issue, claimedAt: claimTimeOf(events.body, issue.assignees) });\n }\n return claimed;\n },\n async hasOpenPull(targetId) {\n const answer = await send({ method: \"GET\", path: \"/search/issues\", query: { q: `\"${targetId}\" type:pr state:open`, per_page: String(PAGE) } }, \"a search of pull requests\");\n const items = arrayOf(answer.body, \"items\", (item) => textOf(item, \"body\")) ?? [];\n return items.some((body) => body.includes(targetId));\n },\n async ensureLabels(names) {\n const answer = await send({ method: \"GET\", path: `${base}/labels`, query: { per_page: String(PAGE) } }, \"the list of labels\");\n const have = new Set(readArray(answer.body, (label) => textOf(label, \"name\")) ?? []);\n for (const name of names.filter((label) => !have.has(label))) {\n const color = name === TARGET_LABEL ? LABEL_COLOR.target : LABEL_COLOR.gap;\n await send({ method: \"POST\", path: `${base}/labels`, body: { name, color } }, \"a new label\");\n }\n },\n async create(text: IssueText) {\n const answer = await send({ method: \"POST\", path: `${base}/issues`, body: { title: text.title, body: text.body, labels: text.labels } }, \"a new issue\");\n return issueAnswer(answer, \"a new issue\").number;\n },\n async update(number, change) {\n return issueAnswer(await send({ method: \"PATCH\", path: `${base}/issues/${String(number)}`, body: patchOf(change) }, \"a change of an issue\"), \"a change of an issue\");\n },\n async comment(number, text) {\n await send({ method: \"POST\", path: `${base}/issues/${String(number)}/comments`, body: { body: text } }, \"a comment\");\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAQA,M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O,MAAM;IAAK,MAAM,QAAQ,MAAM;GAAE,GAAG,sBAAsB,GAAG,sBAAsB;EACrK;EACA,MAAM,QAAQ,QAAQ,MAAM;GAC1B,MAAM,KAAK;IAAE,QAAQ;IAAQ,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,EAAE;IAAY,MAAM,EAAE,MAAM,KAAK;GAAE,GAAG,WAAW;EACrH;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["compareText","kindOf","relationOf"],"sources":["../src/atlas.ts","../src/check.ts","../src/clones.ts","../src/engine.ts","../src/homes.ts","../src/polite.ts","../src/facts.ts","../src/load.ts","../../../node_modules/.pnpm/@mark1russell7+rigor-generators@0.2.10/node_modules/@mark1russell7/rigor-generators/build/random.js","../src/pick.ts","../src/test-gates.ts","../src/write.ts","../src/cli.ts","../src/github.ts"],"sourcesContent":["// The read of the duplication atlas of codeatlas into records of kind candidate.\nimport type { HomeAnswer } from \"@mark1russell7/conventions\";\nimport { arrayOf, booleanOf, numberOf, readText, textOf } from \"@mark1russell7/optional/read\";\nimport type { PublicRepository } from \"./homes.ts\";\nimport { makeId, repositoryId } from \"./ids.ts\";\nimport type { EntityRecord } from \"./types.ts\";\n\n/** The URL of the data of the duplication atlas. */\nexport const ATLAS_URL = \"https://metrograph-labs.github.io/codeatlas/data/atlas.json\";\n\n/** The id of the record of kind source for the duplication atlas. */\nexport const ATLAS_SOURCE_ID = \"source.codeatlas\";\n\n/** The schema of the atlas that this reader knows. The reader refuses an atlas with a different schema. */\nexport const ATLAS_SCHEMA = \"codeatlas/1\";\n\n/** The largest text of an atlas that the reader accepts, in characters. */\nexport const ATLAS_LIMIT: number = 32 * 1024 * 1024;\n\n/** A function of a repository that the atlas finds with the names of an area. */\nexport interface AtlasCopy {\n readonly repo: string;\n readonly file: string;\n readonly line: number;\n readonly name: string;\n}\n\n/** The functions that the atlas finds for one area of the map of homes. */\nexport interface AtlasRow {\n readonly area: string;\n readonly copies: readonly AtlasCopy[];\n}\n\n/** A repository that the atlas read, with its owner and the commit that it read. */\nexport interface AtlasRepository {\n readonly repo: string;\n readonly owner: string;\n readonly commit: string;\n}\n\n/** A class of cloned code: functions with the same shape in two or more places. */\nexport interface AtlasClass {\n /** The count of syntax nodes of one copy. */\n readonly nodes: number;\n /** The areas of the map of homes that the atlas finds for the class. */\n readonly areas: readonly string[];\n /** The copies. A function of a test file is not a copy. A function with no name has the name `<anonymous>`. */\n readonly members: readonly AtlasCopy[];\n}\n\n/** The parts of the atlas that canon uses. */\nexport interface Atlas {\n readonly repositories: readonly AtlasRepository[];\n readonly rows: readonly AtlasRow[];\n readonly classes: readonly AtlasClass[];\n}\n\n/** The result of a read of the atlas: the atlas, or the reason that the import cannot use it. */\nexport type AtlasRead = { readonly atlas: Atlas } | { readonly error: string };\n\n/** The result of the atlas import: the records of kind candidate and the source, and a text for each copy that it left out. */\nexport interface AtlasImport {\n readonly records: readonly EntityRecord[];\n readonly skipped: readonly string[];\n}\n\nconst COMMIT = /^[0-9a-f]{40}$/;\n\n/**\n * This function reads one function. It drops a function of a test file. It also drops a function with no name, unless\n * `anonymous` is true.\n */\nfunction copyOf(value: unknown, anonymous = false): AtlasCopy | undefined {\n const repo = textOf(value, \"repo\");\n const file = textOf(value, \"file\");\n const line = numberOf(value, \"line\");\n const name = textOf(value, \"name\");\n if (repo === undefined || file === undefined || line === undefined || name === undefined) return undefined;\n if (booleanOf(value, \"test\") !== false || !Number.isInteger(line) || line < 1 || name === \"\") return undefined;\n if (name.startsWith(\"<\") && (!anonymous || name !== \"<anonymous>\")) return undefined;\n return { repo, file, line, name };\n}\n\n/** This function reads one class of cloned code. It drops a class with a bad count of nodes. */\nfunction classOf(value: unknown): AtlasClass | undefined {\n const nodes = numberOf(value, \"nodes\");\n if (nodes === undefined || !Number.isInteger(nodes) || nodes < 1) return undefined;\n return { nodes, areas: arrayOf(value, \"homes\", readText) ?? [], members: arrayOf(value, \"members\", (member) => copyOf(member, true)) ?? [] };\n}\n\n/**\n * This function reads the answer of the fetch of the atlas. It gives an error for a failed fetch, a text of more than\n * `limit` characters and a text that is not JSON. A schema that is not `ATLAS_SCHEMA` also gives an error. It drops each\n * row with a bad field. An atlas with no list of classes has no classes.\n */\nexport function readAtlas(answer: HomeAnswer | undefined, limit: number = ATLAS_LIMIT): AtlasRead {\n if (answer === undefined) return { error: \"The fetch gave no answer for the atlas.\" };\n if (\"error\" in answer) return { error: `The fetch of the atlas gave the error ${answer.error}.` };\n if (answer.text.length > limit) return { error: `The atlas has more than ${String(limit)} characters.` };\n let data: unknown;\n try {\n data = JSON.parse(answer.text);\n } catch {\n return { error: \"The atlas is not JSON.\" };\n }\n const schema = textOf(data, \"schema\");\n if (schema !== ATLAS_SCHEMA) return { error: `The atlas has the schema ${schema ?? \"(none)\"}, not ${ATLAS_SCHEMA}.` };\n const repositories = arrayOf(data, \"repos\", (row): AtlasRepository | undefined => {\n const repo = textOf(row, \"repo\");\n const owner = textOf(row, \"owner\");\n const commit = textOf(row, \"commit\");\n return repo === undefined || owner === undefined || commit === undefined || !COMMIT.test(commit) ? undefined : { repo, owner, commit };\n });\n const rows = arrayOf(data, \"homed\", (row): AtlasRow | undefined => {\n const area = textOf(row, \"area\");\n return area === undefined ? undefined : { area, copies: arrayOf(row, \"copies\", copyOf) ?? [] };\n });\n if (repositories === undefined || rows === undefined) return { error: \"The atlas has no list of repositories or no list of homed rows.\" };\n return { atlas: { repositories, rows, classes: arrayOf(data, \"classes\", classOf) ?? [] } };\n}\n\n/** This function gives the repositories of each area that hold its own code: the home and each repository of a package of the area. */\nexport function ownRepositories(records: readonly EntityRecord[]): ReadonlyMap<string, ReadonlySet<string>> {\n const own = new Map<string, Set<string>>();\n const add = (area: string, repository: string): void => {\n const set = own.get(area) ?? new Set<string>();\n set.add(repository);\n own.set(area, set);\n };\n for (const record of records) {\n const edges = record.edges ?? [];\n if (record.kind === \"repository\") for (const edge of edges) if (edge.type === \"home-of\") add(edge.to, record.id);\n const partOf = edges.find((edge) => edge.type === \"part-of\")?.to;\n if (record.kind === \"package\" && partOf !== undefined) for (const edge of edges) if (edge.type === \"covers\") add(edge.to, partOf);\n }\n return own;\n}\n\n/** The repository of a name of the atlas and the commit that the atlas read, or the reason that there is none. */\nexport type AtlasFound = { readonly repository: PublicRepository; readonly commit: string } | { readonly why: string };\n\n/**\n * This function gives a function that finds the repository of a name of the atlas. It finds the repository under the\n * owner that the atlas names, or under the one owner that has a repository of that name. A fork and an archived\n * repository are not found.\n */\nexport function repositoryFinder(atlas: Atlas, repositories: readonly PublicRepository[]): (repo: string) => AtlasFound {\n const live = repositories.filter((repository) => repository.fork !== true && repository.archived !== true);\n const byFullName = new Map(live.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository]));\n const byName = new Map<string, PublicRepository[]>();\n for (const repository of live) byName.set(repository.name.toLowerCase(), [...(byName.get(repository.name.toLowerCase()) ?? []), repository]);\n const read = new Map(atlas.repositories.map((row) => [row.repo.toLowerCase(), row]));\n return (repo) => {\n const scan = read.get(repo.toLowerCase());\n const named = byName.get(repo.toLowerCase()) ?? [];\n const found = (scan === undefined ? undefined : byFullName.get(`${scan.owner}/${repo}`.toLowerCase())) ?? (named.length === 1 ? named[0] : undefined);\n if (scan !== undefined && found !== undefined) return { repository: found, commit: scan.commit };\n const why = scan === undefined ? \"the atlas has no commit for it\" : named.length > 1 ? \"two owners have a repository of that name\" : \"GitHub lists no public repository of that name that is not a fork and not archived\";\n return { why };\n };\n}\n\n/**\n * This function makes a record of kind candidate for each pair of a repository and an area that the atlas finds. It\n * reads nothing itself.\n *\n * - The import finds each repository of the atlas under its owner, or under the one owner that has a repository of that\n * name. It leaves out a name of two owners, a fork, an archived repository and a repository that is not public.\n * - It leaves out an area that the map of homes does not have, and the repositories that hold the own code of the area.\n * - Each candidate has the commit that the atlas read, and each place once, in the order of the file and the line.\n */\nexport function recordsFromAtlas(atlas: Atlas, repositories: readonly PublicRepository[], mapRecords: readonly EntityRecord[]): AtlasImport {\n const skipped = new Set<string>();\n const find = repositoryFinder(atlas, repositories);\n const areas = new Set(mapRecords.filter((record) => record.kind === \"area\").map((record) => record.id));\n const own = ownRepositories(mapRecords);\n const pairs = new Map<string, { id: string; repository: string; area: string; commit: string; places: Map<string, AtlasCopy> }>();\n for (const row of atlas.rows) {\n const area = makeId(\"area\", row.area);\n if (!areas.has(area)) {\n skipped.add(`The atlas names the area ${row.area}, which the map of homes does not have.`);\n continue;\n }\n for (const copy of row.copies) {\n const found = find(copy.repo);\n if (\"why\" in found) {\n skipped.add(`The atlas names the repository ${copy.repo}, but ${found.why}.`);\n continue;\n }\n const repository = repositoryId(found.repository.owner, found.repository.name);\n if (own.get(area)?.has(repository) === true) continue;\n const key = `${repository} ${area}`;\n const id = makeId(\"candidate\", found.repository.owner, found.repository.name, row.area);\n const pair = pairs.get(key) ?? { id, repository, area, commit: found.commit, places: new Map<string, AtlasCopy>() };\n pair.places.set(`${copy.file}:${String(copy.line)}:${copy.name}`, copy);\n pairs.set(key, pair);\n }\n }\n const records: EntityRecord[] = [\n {\n id: ATLAS_SOURCE_ID,\n kind: \"source\",\n attrs: { title: \"The duplication atlas of codeatlas\", url: \"https://metrograph-labs.github.io/codeatlas/\", version: ATLAS_SCHEMA, license: \"MIT\" },\n },\n ];\n for (const pair of pairs.values()) {\n const places = [...pair.places.values()]\n .sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)))\n .map(({ file, line, name }) => ({ file, line, name }));\n records.push({\n id: pair.id,\n kind: \"candidate\",\n attrs: { commit: pair.commit, places },\n envelope: { source_ids: [ATLAS_SOURCE_ID] },\n edges: [\n { type: \"about\", to: pair.area },\n { type: \"about\", to: pair.repository },\n ],\n });\n }\n records.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n return { records, skipped: [...skipped].sort() };\n}\n","// The check of the ontology: the grammar, the shape of each record file, and the integrity of the graph.\nimport { instantNanos } from \"@mark1russell7/algebra/clock\";\nimport { Ajv2020, type ErrorObject, type ValidateFunction } from \"ajv/dist/2020.js\";\nimport formats from \"ajv-formats\";\nimport { edgesOf, isKindIn, isLive, kindOf, lineageOf, relationOf } from \"./grammar.ts\";\nimport { GRAMMAR_FILE, kindOfId, pathOfId } from \"./ids.ts\";\nimport { formalKeyOf } from \"./problems.ts\";\nimport { canonicalScope, readScope, type Scope } from \"./scope.ts\";\nimport type { Edge, Envelope, Grammar, JsonSchema, Ontology, Problem } from \"./types.ts\";\n\n/** This function makes a validator of JSON Schema 2020-12 with the formats `uri` and `date-time`. */\nfunction makeAjv(): Ajv2020 {\n const ajv = new Ajv2020({ allErrors: true, strict: true, strictTypes: false, logger: false });\n formats[\"default\"](ajv);\n return ajv;\n}\n\n/** This function gives the text of each error of a validation, with the name `name` for the value. */\nfunction errorTexts(name: string, errors: readonly ErrorObject[] | null | undefined): string[] {\n return (errors ?? []).map((error) => {\n const extra = error.keyword === \"additionalProperties\" ? ` (${String(error.params[\"additionalProperty\"])})` : \"\";\n const allowed = error.keyword === \"enum\" ? `: ${JSON.stringify(error.params[\"allowedValues\"])}` : \"\";\n return `${name}${error.instancePath} ${error.message ?? error.keyword}${extra}${allowed}`;\n });\n}\n\n/** The validators of the grammar: one for the attributes of each kind and one for the qualifiers of each relation kind. */\nexport interface Validators {\n readonly record: ValidateFunction;\n readonly kinds: ReadonlyMap<string, ValidateFunction>;\n readonly qualifiers: ReadonlyMap<string, ValidateFunction>;\n}\n\n/** This function compiles a schema of the grammar with the shared `$defs`. It gives a problem when the schema is not valid. */\nfunction compile(ajv: Ajv2020, grammar: Grammar, schema: JsonSchema, what: string, problems: Problem[]): ValidateFunction | undefined {\n try {\n return ajv.compile({ $defs: grammar.$defs, ...schema });\n } catch (error) {\n problems.push({ path: GRAMMAR_FILE, message: `${what}: ${error instanceof Error ? error.message : String(error)}` });\n return undefined;\n }\n}\n\n/** This function checks the grammar itself, and compiles its validators. */\nexport function checkGrammar(ontology: Ontology, problems: Problem[]): Validators {\n const { grammar } = ontology;\n const ajv = makeAjv();\n const name = new RegExp(grammar.namePattern);\n const kinds = new Map<string, ValidateFunction>();\n const qualifiers = new Map<string, ValidateFunction>();\n const fail = (message: string): void => {\n problems.push({ path: GRAMMAR_FILE, message });\n };\n const seen = new Set<string>();\n for (const kind of grammar.kinds) {\n if (seen.has(kind.name)) fail(`The kind ${kind.name} comes more than one time.`);\n seen.add(kind.name);\n if (!name.test(kind.name)) fail(`The kind name ${kind.name} does not agree with the name pattern.`);\n if (kind.parent !== null && kindOf(grammar, kind.parent) === undefined) fail(`The parent ${kind.parent} of the kind ${kind.name} is not a kind.`);\n if (kind.parent !== null && lineageOf(grammar, kind.name).length <= lineageOf(grammar, kind.parent).length) fail(`The parents of the kind ${kind.name} make a loop.`);\n const validate = compile(ajv, grammar, kind.attributes, `the attributes of the kind ${kind.name}`, problems);\n if (validate !== undefined) kinds.set(kind.name, validate);\n }\n for (const relation of grammar.relations) {\n if (seen.has(relation.name)) fail(`The name ${relation.name} is a kind and a relation kind, or two relation kinds.`);\n seen.add(relation.name);\n if (!name.test(relation.name)) fail(`The relation name ${relation.name} does not agree with the name pattern.`);\n for (const end of [...relation.from, ...relation.to]) {\n if (kindOf(grammar, end) === undefined) fail(`The relation ${relation.name} names ${end}, which is not a kind.`);\n }\n if (relation.parent !== undefined && relationOf(grammar, relation.parent) === undefined) fail(`The parent ${relation.parent} of the relation ${relation.name} is not a relation kind.`);\n const fields = Object.keys((relation.qualifiers?.[\"properties\"] as Record<string, unknown> | undefined) ?? {});\n for (const part of relation.key ?? []) {\n if (part !== \"from\" && part !== \"to\" && !fields.includes(part)) fail(`The key of the relation ${relation.name} names ${part}, which is not an end or a qualifier.`);\n }\n if (relation.qualifiers !== undefined) {\n const validate = compile(ajv, grammar, relation.qualifiers, `the qualifiers of the relation ${relation.name}`, problems);\n if (validate !== undefined) qualifiers.set(relation.name, validate);\n }\n }\n return { record: ajv.compile(ontology.recordSchema), kinds, qualifiers };\n}\n\n/** This function checks that each id of an envelope names a record, and that each source id names a record of kind source. */\nfunction checkEnvelope(envelope: Envelope | undefined, what: string, path: string, kinds: ReadonlyMap<string, string>, grammar: Grammar, problems: Problem[]): void {\n if (envelope === undefined) return;\n for (const source of envelope.source_ids ?? []) {\n const kind = kinds.get(source);\n if (kind === undefined) problems.push({ path, message: `${what}: the source ${source} is not a record.` });\n else if (!isKindIn(grammar, kind, [\"source\"])) problems.push({ path, message: `${what}: the source ${source} is a ${kind}, not a source.` });\n }\n for (const field of [\"superseded_by\", \"retired_from\"] as const) {\n const id = envelope[field];\n if (id !== undefined && !kinds.has(id)) problems.push({ path, message: `${what}: ${field} names ${id}, which is not a record.` });\n }\n if (!timesInOrder(envelope)) problems.push({ path, message: `${what}: valid_from ${String(envelope.valid_from)} is after valid_to ${String(envelope.valid_to)}.` });\n}\n\n/**\n * This function tells if the `valid_from` of an envelope is not after its `valid_to`. The comparison uses the instants\n * in nanoseconds, so two times with different offsets or in one millisecond compare correctly. The record schema refuses\n * a time that is not valid.\n */\nexport function timesInOrder(envelope: Envelope): boolean {\n const from = instantNanos(envelope.valid_from ?? \"\");\n const to = instantNanos(envelope.valid_to ?? \"\");\n return from === undefined || to === undefined || from <= to;\n}\n\n/** 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. */\n/**\n * This function examines the scopes (roadmap C16). Each scope is valid and not empty. A live result about a problem has\n * a scope, and the problem has a scope of the same variable. So the rule of the results can compare the two scopes.\n */\nfunction checkScopes(ontology: Ontology, problems: Problem[]): void {\n const scopes = new Map<string, Scope>();\n const records = new Map(ontology.records.map((entry) => [entry.record.id, entry]));\n for (const { path, record } of ontology.records) {\n const value = record.attrs[\"scope\"];\n if (value === undefined) continue;\n const scope = readScope(value);\n if (typeof scope === \"string\") problems.push({ path, message: scope });\n else if (canonicalScope(scope) === undefined) problems.push({ path, message: \"The scope has no value: no value from from to to is in its classes.\" });\n else scopes.set(record.id, scope);\n }\n const named = new Set<string>();\n for (const { path, record } of ontology.records) {\n if (record.kind !== \"result\" || !isLive(record)) continue;\n for (const edge of record.edges ?? []) {\n const problem = records.get(edge.to);\n if (edge.type !== \"about\" || !isLive(edge) || problem?.record.kind !== \"problem\") continue;\n if (record.attrs[\"scope\"] === undefined) problems.push({ path, message: `The result is about ${edge.to}, so it has a scope.` });\n if (problem.record.attrs[\"scope\"] === undefined && !named.has(edge.to)) {\n named.add(edge.to);\n problems.push({ path: problem.path, message: `The result ${record.id} is about the problem, so the problem has a scope.` });\n }\n const own = scopes.get(record.id);\n const theirs = scopes.get(edge.to);\n if (own !== undefined && theirs !== undefined && own.variable !== theirs.variable) {\n problems.push({ path, message: `The scope of the result has the variable ${own.variable}, and the scope of ${edge.to} has ${theirs.variable}.` });\n }\n }\n }\n}\n\n/**\n * This function examines the formal names (roadmap C12). Two live problems cannot have one Lean key, because a tool\n * finds a problem by its formal name. A short name, for example `conjecture`, names many statements.\n */\nfunction checkFormalNames(ontology: Ontology, problems: Problem[]): void {\n const first = new Map<string, string>();\n for (const { path, record } of ontology.records) {\n if (record.kind !== \"problem\" || !isLive(record)) continue;\n const key = formalKeyOf(record);\n if (key === undefined) continue;\n const earlier = first.get(key);\n if (earlier === undefined) first.set(key, record.id);\n else problems.push({ path, message: `The formal name ${key} is also the formal name of ${earlier}. Give the full name, with its namespaces.` });\n }\n}\n\nfunction keyOf(edge: Edge, key: readonly string[]): string {\n return JSON.stringify(key.map((part) => (part === \"from\" ? edge.from : part === \"to\" ? edge.to : (edge.qualifiers[part] ?? null))));\n}\n\n/**\n * This function checks the ontology, and gives each problem that it finds, in the order of the paths. No problem means\n * that the data is valid:\n *\n * - The grammar is valid: unique names, known parents and ends, keys of known parts and schemas that compile.\n * - Each record file agrees with `schema/record.schema.json`, and its attributes agree with the schema of its kind.\n * - The id of each record starts with its kind, its file is at the path of its id, and no two records have one id.\n * - Each relation has a relation kind that is not abstract, ends of the correct kinds, and correct qualifiers.\n * - No two live relations of a kind have the same key. For example, an area has at most one home.\n * - Each id of an envelope names a record, and each source is a record of kind source.\n */\nexport function checkOntology(ontology: Ontology): readonly Problem[] {\n const problems: Problem[] = [];\n const { grammar } = ontology;\n const validators = checkGrammar(ontology, problems);\n const idPattern = new RegExp(grammar.idPattern);\n const kinds = new Map<string, string>();\n const paths = new Map<string, string>();\n for (const { path, record } of ontology.records) {\n if (!validators.record(record)) {\n for (const message of errorTexts(\"record\", validators.record.errors)) problems.push({ path, message });\n continue;\n }\n const earlier = paths.get(record.id);\n if (earlier !== undefined) problems.push({ path, message: `The id ${record.id} is also the id of ${earlier}.` });\n paths.set(record.id, path);\n kinds.set(record.id, record.kind);\n }\n for (const { path, record } of ontology.records) {\n if (paths.get(record.id) !== path) continue;\n if (!idPattern.test(record.id)) problems.push({ path, message: `The id ${record.id} does not agree with the id pattern.` });\n if (kindOfId(record.id) !== record.kind) problems.push({ path, message: `The id ${record.id} does not start with its kind ${record.kind} and a dot.` });\n else if (pathOfId(record.id) !== path) problems.push({ path, message: `The file of ${record.id} is not at ${pathOfId(record.id)}.` });\n const validate = validators.kinds.get(record.kind);\n if (kindOf(grammar, record.kind) === undefined) problems.push({ path, message: `The kind ${record.kind} is not a kind of the grammar.` });\n else if (validate !== undefined && !validate(record.attrs)) {\n for (const message of errorTexts(\"attrs\", validate.errors)) problems.push({ path, message });\n }\n checkEnvelope(record.envelope, \"envelope\", path, kinds, grammar, problems);\n for (const [index, edge] of (record.edges ?? []).entries()) {\n const what = `edges/${String(index)} (${edge.type} ${edge.to})`;\n const relation = relationOf(grammar, edge.type);\n if (relation === undefined) {\n problems.push({ path, message: `${what}: ${edge.type} is not a relation kind of the grammar.` });\n continue;\n }\n if (relation.abstract === true) problems.push({ path, message: `${what}: the relation kind ${edge.type} is abstract.` });\n if (!isKindIn(grammar, record.kind, relation.from)) problems.push({ path, message: `${what}: a ${record.kind} cannot start a relation ${edge.type}.` });\n const to = kinds.get(edge.to);\n if (to === undefined) problems.push({ path, message: `${what}: ${edge.to} is not a record.` });\n else if (!isKindIn(grammar, to, relation.to)) problems.push({ path, message: `${what}: a relation ${edge.type} cannot end at a ${to}.` });\n const validate = validators.qualifiers.get(edge.type);\n if (validate === undefined && relation.qualifiers === undefined && Object.keys(edge.qualifiers ?? {}).length > 0) {\n problems.push({ path, message: `${what}: the relation kind ${edge.type} has no qualifiers.` });\n } else if (validate !== undefined && !validate(edge.qualifiers ?? {})) {\n for (const message of errorTexts(`${what} qualifiers`, validate.errors)) problems.push({ path, message });\n }\n checkEnvelope(edge.envelope, `${what} envelope`, path, kinds, grammar, problems);\n }\n }\n const facts = new Map<string, string>();\n for (const edge of edgesOf(ontology).filter(isLive)) {\n const relation = relationOf(grammar, edge.type);\n if (relation === undefined) continue;\n const fact = `${edge.type} ${keyOf(edge, relation.key ?? [\"from\", \"to\"])}`;\n const first = facts.get(fact);\n const path = paths.get(edge.from) ?? pathOfId(edge.from);\n if (first !== undefined) {\n const parts = (relation.key ?? [\"from\", \"to\"]).join(\" and \");\n problems.push({ path, message: `The relation ${edge.type} to ${edge.to} has the same ${parts} as a relation ${edge.type} of ${first}. The two cannot both be true.` });\n }\n else facts.set(fact, edge.from);\n }\n checkScopes(ontology, problems);\n checkFormalNames(ontology, problems);\n return problems.sort((a, b) => (a.path === b.path ? 0 : a.path < b.path ? -1 : 1));\n}\n","// The report of the cloned code with no home: the classes of the duplication atlas that no area of the map covers.\nimport { textOf } from \"@mark1russell7/optional/read\";\nimport { countOf, listOf } from \"@mark1russell7/text/english\";\nimport { compareCodeUnits as compareText } from \"@mark1russell7/text/order\";\nimport { type Atlas, ownRepositories, repositoryFinder } from \"./atlas.ts\";\nimport type { PublicRepository } from \"./homes.ts\";\nimport { repositoryId } from \"./ids.ts\";\nimport type { EntityRecord } from \"./types.ts\";\n\n/** The fewest copied syntax nodes of a class in the report. A smaller class is too small for a home. */\nexport const CLONE_FLOOR = 200;\n\n/** A copy of a class of cloned code, in a repository of the records. */\nexport interface CloneMember {\n /** The id of the record of the repository. */\n readonly repository: string;\n readonly file: string;\n readonly line: number;\n /** The name of the function, or `<anonymous>`. */\n readonly name: string;\n}\n\n/** A class of cloned code that no area of the map of homes covers. */\nexport interface CloneClass {\n /** The syntax nodes of the copies after the first: the nodes of one copy, times the count of copies less one. */\n readonly copied: number;\n /** The copies, in the order of the repository, the file and the line. */\n readonly members: readonly CloneMember[];\n}\n\n/** The classes of cloned code with no home that have their copies in the same repositories. */\nexport interface CloneGroup {\n /** The ids of the records of the repositories, in order. */\n readonly repositories: readonly string[];\n /** The sum of the copied syntax nodes of the classes. */\n readonly copied: number;\n /** The classes, the largest first. */\n readonly classes: readonly CloneClass[];\n}\n\n/** This function gives the public repositories of the records: each record of kind repository that exists. */\nfunction repositoriesOf(records: readonly EntityRecord[]): readonly PublicRepository[] {\n const repositories: PublicRepository[] = [];\n for (const record of records) {\n if (record.kind !== \"repository\" || record.attrs[\"exists\"] !== true) continue;\n const owner = textOf(record.attrs, \"owner\");\n const name = textOf(record.attrs, \"name\");\n const url = textOf(record.attrs, \"url\");\n if (owner !== undefined && name !== undefined && url !== undefined) repositories.push({ owner, name, url });\n }\n return repositories;\n}\n\n/**\n * This function gives the classes of cloned code that no area covers, in groups by their repositories. It keeps a\n * class with copies in two or more public repositories of the records and `floor` or more copied syntax nodes.\n *\n * - The atlas names each repository. This function finds it in the records as the import does. A copy in a\n * repository that it cannot find is not a copy of the report.\n * - The largest group comes first. Two groups of the same size are in the order of their repositories.\n */\nexport function cloneGroups(atlas: Atlas, records: readonly EntityRecord[], floor: number = CLONE_FLOOR): readonly CloneGroup[] {\n const find = repositoryFinder(atlas, repositoriesOf(records));\n const groups = new Map<string, { repositories: readonly string[]; classes: CloneClass[] }>();\n for (const found of atlas.classes) {\n if (found.areas.length > 0) continue;\n const members = new Map<string, CloneMember>();\n for (const copy of found.members) {\n const place = find(copy.repo);\n if (\"why\" in place) continue;\n const member = { repository: repositoryId(place.repository.owner, place.repository.name), file: copy.file, line: copy.line, name: copy.name };\n members.set(`${member.repository} ${member.file}:${String(member.line)} ${member.name}`, member);\n }\n const repositories = [...new Set([...members.values()].map((member) => member.repository))].sort(compareText);\n const copied = found.nodes * (members.size - 1);\n if (repositories.length < 2 || copied < floor) continue;\n const ordered = [...members.values()].sort((a, b) => compareText(a.repository, b.repository) || compareText(a.file, b.file) || a.line - b.line);\n const key = repositories.join(\" \");\n const group = groups.get(key) ?? { repositories, classes: [] };\n group.classes.push({ copied, members: ordered });\n groups.set(key, group);\n }\n const placeOf = (clone: CloneClass): string => clone.members.map((member) => `${member.repository} ${member.file}:${String(member.line)}`).join(\" \");\n return [...groups.values()]\n .map(({ repositories, classes }) => ({\n repositories,\n copied: classes.reduce((sum, clone) => sum + clone.copied, 0),\n classes: classes.sort((a, b) => b.copied - a.copied || compareText(placeOf(a), placeOf(b))),\n }))\n .sort((a, b) => b.copied - a.copied || compareText(a.repositories.join(\" \"), b.repositories.join(\" \")));\n}\n\n/** This function gives the name of a repository for a person: `owner/name`. */\nfunction repositoryName(id: string, byId: ReadonlyMap<string, EntityRecord>): string {\n const attrs = byId.get(id)?.attrs;\n const owner = attrs === undefined ? undefined : textOf(attrs, \"owner\");\n const name = attrs === undefined ? undefined : textOf(attrs, \"name\");\n return owner === undefined || name === undefined ? id : `${owner}/${name}`;\n}\n\n/** This function gives the text of the functions of one file: each name with its line. */\nfunction functionsText(members: readonly CloneMember[]): string {\n const parts = [...new Map(members.map((member) => [`${String(member.line)} ${member.name}`, member])).values()]\n .sort((a, b) => a.line - b.line || compareText(a.name, b.name))\n .map((member) => (member.name === \"<anonymous>\" ? `a function with no name at line ${String(member.line)}` : `\\`${member.name}\\` at line ${String(member.line)}`));\n return listOf(parts);\n}\n\n/**\n * This function gives the report of the groups as Markdown, for the maintainer of the map of homes. The report names\n * each repository, the areas whose code it holds, and each file and function of the copies. It names no hash, so a\n * new read of the atlas gives the same keys. Each title of an area is in quotes, because a title can have commas.\n */\nexport function cloneReport(groups: readonly CloneGroup[], records: readonly EntityRecord[], floor: number = CLONE_FLOOR): string {\n const byId = new Map(records.map((record) => [record.id, record]));\n const areasOf = new Map<string, string[]>();\n for (const [area, repositories] of ownRepositories(records)) {\n const title = textOf(byId.get(area)?.attrs ?? {}, \"title\") ?? area;\n for (const repository of repositories) areasOf.set(repository, [...(areasOf.get(repository) ?? []), title]);\n }\n const classes = groups.reduce((sum, group) => sum + group.classes.length, 0);\n const lines = [\"# The cloned code with no home\", \"\"];\n if (classes === 0) {\n lines.push(`The duplication atlas finds no class of cloned code with no home, with ${String(floor)} or more copied syntax nodes.`);\n return lines.join(\"\\n\");\n }\n lines.push(\n `The duplication atlas finds ${countOf(classes, \"class\", \"classes\")} of cloned code that no area of the map of homes covers, in ${countOf(groups.length, \"group\")}.`,\n `Each class has copies in two or more public repositories, and ${String(floor)} or more copied syntax nodes.`,\n \"For each group, the maintainer chooses a home, or writes why the copies stay.\",\n );\n for (const group of groups) {\n lines.push(\"\", `## ${listOf(group.repositories.map((id) => `\\`${repositoryName(id, byId)}\\``))}`, \"\");\n lines.push(`${countOf(group.classes.length, \"class\", \"classes\")}, ${group.copied.toLocaleString(\"en-US\")} copied syntax nodes.`, \"\");\n for (const repository of group.repositories) {\n const areas = (areasOf.get(repository) ?? []).sort(compareText).map((title) => `\"${title}\"`);\n const holds = areas.length === 0 ? \"It holds the code of no area.\" : `It holds the code of the ${areas.length === 1 ? \"area\" : \"areas\"} ${listOf(areas)}.`;\n lines.push(`- \\`${repositoryName(repository, byId)}\\`. ${holds}`);\n const files = new Map<string, CloneMember[]>();\n for (const clone of group.classes) for (const member of clone.members) if (member.repository === repository) files.set(member.file, [...(files.get(member.file) ?? []), member]);\n for (const [file, members] of [...files.entries()].sort(([a], [b]) => compareText(a, b))) lines.push(` - \\`${file}\\`: ${functionsText(members)}.`);\n }\n }\n return lines.join(\"\\n\");\n}\n","// The kinds of canon as an add-on of the ontology engine (roadmap C18). The grammar file stays the one source of the\n// kinds. This module reads the grammar into the engine, and it refuses each rule that the engine cannot keep.\nimport {\n type AttrShape,\n type Edge as EngineEdge,\n type Entity,\n type FacetDef as EngineFacet,\n type GenerateOptions,\n type KindDef as EngineKind,\n type Registry,\n type RegistryInput,\n type RelationExtension,\n type RelationKindDef as EngineRelation,\n type Requirement,\n type RequirementValue,\n type Scope as EngineScope,\n spineRegistry,\n spineRelations,\n} from \"@mark1russell7/ontology\";\nimport { errorMessage } from \"@mark1russell7/text\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport { GRAMMAR_FILE } from \"./ids.ts\";\nimport type { Grammar, JsonSchema, KindDef, LoadedRecord, RelationKindDef } from \"./types.ts\";\n\n/**\n * The audience of canon: each record is public (`schema/record.schema.json`). It is the default scope of each kind, and\n * the engine refuses a record or an edge with a more private scope.\n */\nconst CANON_AUDIENCE: EngineScope = \"public\";\n\n/** The folder of the files that the engine generates from the grammar, relative to the root of the repository. */\nexport const ENGINE_FOLDER = \"schema/engine\";\n\n/** The options of the generation: the first line of each SQL file names the command that makes the files. */\nexport const ENGINE_GENERATE_OPTIONS: GenerateOptions = {\n header: `-- Generated by \\`pnpm canon engine --write\\` from ${GRAMMAR_FILE}. Do not edit by hand.`,\n};\n\n/**\n * The keywords of JSON Schema that the add-on gives to the engine. A test holds each keyword: ajv and the engine give\n * the same verdict on each value of the test.\n */\nexport const ENGINE_KEYWORDS: ReadonlySet<string> = new Set([\n \"$ref\",\n \"additionalProperties\",\n \"anyOf\",\n \"const\",\n \"description\",\n \"enum\",\n \"format\",\n \"items\",\n \"maximum\",\n \"minItems\",\n \"minLength\",\n \"minimum\",\n \"oneOf\",\n \"pattern\",\n \"properties\",\n \"required\",\n \"type\",\n \"uniqueItems\",\n]);\n\n/**\n * The values of the keyword `format` that the add-on gives to the engine. In JSON Schema 2020-12, a format is only an\n * annotation. So each field with a format also has a pattern, and each reader gives the same verdict. The format `uri`\n * is not in the list: zod reads it as `z.url()`, which removes the spaces at the two ends of the value.\n */\nexport const ENGINE_FORMATS: ReadonlySet<string> = new Set([\"date-time\"]);\n\n/** The error of a grammar rule that the engine cannot keep. Each problem has the path of the rule in the grammar. */\nexport class EngineGrammarError extends Error {\n /** The problems: one text for each rule that the engine cannot keep. */\n readonly problems: readonly string[];\n\n constructor(problems: readonly string[]) {\n super(`The ontology engine cannot keep ${String(problems.length)} rules of ${GRAMMAR_FILE}:\\n${problems.join(\"\\n\")}`);\n this.name = \"EngineGrammarError\";\n this.problems = problems;\n }\n}\n\n/** This function tells if a value is a JSON object, not an array and not null. */\nconst isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** This function adds a problem for each keyword of a schema that the engine does not keep, also in the parts of the schema. */\nfunction checkKeywords(schema: unknown, path: string, problems: string[]): void {\n if (!isObject(schema)) {\n problems.push(`${path}: the engine keeps only a schema that is an object, not ${JSON.stringify(schema)}.`);\n return;\n }\n // zod reads an object next to oneOf or anyOf as an intersection of open objects, so it loses the rules of the object\n const next = Object.keys(schema).filter((keyword) => ![\"anyOf\", \"description\", \"oneOf\"].includes(keyword));\n if ((schema[\"oneOf\"] !== undefined || schema[\"anyOf\"] !== undefined) && next.length > 0) {\n problems.push(`${path}: a schema with oneOf or anyOf has only a description next to it, not ${next.join(\", \")}.`);\n }\n // zod removes the unknown keys of an open object, so the engine changes the value where ajv keeps it\n if ((schema[\"type\"] === \"object\" || schema[\"properties\"] !== undefined) && schema[\"additionalProperties\"] !== false) {\n problems.push(`${path}: the engine keeps only an object with additionalProperties false.`);\n }\n for (const [keyword, value] of Object.entries(schema)) {\n const at = `${path}/${keyword}`;\n if (!ENGINE_KEYWORDS.has(keyword)) problems.push(`${at}: the engine does not keep the keyword ${keyword}.`);\n else if (keyword === \"format\" && !ENGINE_FORMATS.has(String(value))) problems.push(`${at}: the engine does not keep the format ${String(value)}.`);\n else if (keyword === \"additionalProperties\" && value !== false) problems.push(`${at}: the engine keeps only additionalProperties false.`);\n else if (keyword === \"properties\" && isObject(value)) {\n for (const [name, part] of Object.entries(value)) checkKeywords(part, `${at}/${name}`, problems);\n } else if (keyword === \"items\") checkKeywords(value, at, problems);\n else if ((keyword === \"oneOf\" || keyword === \"anyOf\") && Array.isArray(value)) {\n value.forEach((part: unknown, index) => {\n checkKeywords(part, `${at}/${String(index)}`, problems);\n });\n }\n }\n}\n\n/** This function gives the zod shape of an object schema of the grammar: one zod schema for each property. */\nfunction shapeOf(schema: JsonSchema, grammar: Grammar, path: string, problems: string[]): AttrShape {\n const { if: _if, then: _then, ...rest } = schema;\n checkKeywords(rest, path, problems);\n if (schema[\"type\"] !== \"object\" || schema[\"additionalProperties\"] !== false) {\n problems.push(`${path}: the engine keeps only a closed object: type object and additionalProperties false.`);\n }\n const required = new Set((schema[\"required\"] as readonly string[] | undefined) ?? []);\n const shape: Record<string, z.ZodType> = {};\n for (const [name, part] of Object.entries((schema[\"properties\"] as Record<string, JsonSchema> | undefined) ?? {})) {\n const zod = z.fromJSONSchema({ ...part, $defs: grammar.$defs } as Parameters<typeof z.fromJSONSchema>[0]);\n shape[name] = required.has(name) ? zod : zod.optional();\n }\n return shape;\n}\n\n/**\n * This function gives the requirements of a kind from the keywords `if` and `then` of its attributes. The engine keeps\n * one form: when each property of `if` has its `const` value, each property of `then` is necessary.\n */\nfunction requirementsOf(schema: JsonSchema, path: string, problems: string[]): readonly Requirement[] {\n const condition = schema[\"if\"];\n const result = schema[\"then\"];\n if (condition === undefined && result === undefined) return [];\n const form = `${path}: the engine keeps only the form if {properties: {name: {const}}, required} then {description, required}`;\n if (!isObject(condition) || !isObject(result) || schema[\"else\"] !== undefined) {\n problems.push(`${form}.`);\n return [];\n }\n const when: Record<string, RequirementValue> = {};\n const properties = condition[\"properties\"];\n const names = isObject(properties) ? Object.keys(properties) : [];\n for (const name of names) {\n const part = (properties as Readonly<Record<string, unknown>>)[name];\n const value = isObject(part) && Object.keys(part).length === 1 ? part[\"const\"] : undefined;\n if (value === undefined || (typeof value === \"object\" && value !== null)) problems.push(`${form}: ${name} has no const value.`);\n else when[name] = value as RequirementValue;\n }\n const conditionKeys = Object.keys(condition).sort().join(\",\");\n const conditionRequired = [...((condition[\"required\"] as readonly string[] | undefined) ?? [])].sort().join(\",\");\n if (conditionKeys !== \"properties,required\" || conditionRequired !== [...names].sort().join(\",\")) problems.push(`${form}: the if part has other keywords.`);\n const then = (result[\"required\"] as readonly string[] | undefined) ?? [];\n const thenProperties = result[\"properties\"];\n const extra = Object.keys(result).filter((keyword) => ![\"description\", \"properties\", \"required\"].includes(keyword));\n const loose = isObject(thenProperties) ? Object.entries(thenProperties).filter(([name, part]) => part !== true || !then.includes(name)) : [];\n if (typeof result[\"description\"] !== \"string\" || then.length === 0 || extra.length > 0 || loose.length > 0) {\n problems.push(`${form}: the then part has other keywords or no description.`);\n }\n return [{ description: String(result[\"description\"]), when, then }];\n}\n\n/** 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. */\nfunction kindOf(kind: KindDef, grammar: Grammar, problems: string[]): EngineKind {\n const path = `${GRAMMAR_FILE}#/kinds/${kind.name}/attributes`;\n const requirements = requirementsOf(kind.attributes, path, problems);\n return {\n name: kind.name,\n parent: kind.parent ?? \"entity\",\n mode: kind.mode,\n description: kind.description,\n attributes: shapeOf(kind.attributes, grammar, path, problems),\n ...(kind.facets.length > 0 ? { facets: kind.facets } : {}),\n defaultScope: CANON_AUDIENCE,\n ...(requirements.length > 0 ? { requirements } : {}),\n };\n}\n\n/** This function gives the relation kind of canon as a relation kind of the engine. */\nfunction relationOf(relation: RelationKindDef, grammar: Grammar, problems: string[]): EngineRelation {\n const path = `${GRAMMAR_FILE}#/relations/${relation.name}/qualifiers`;\n return {\n name: relation.name,\n description: relation.description,\n from: relation.from,\n to: relation.to,\n ...(relation.parent === undefined ? {} : { parent: relation.parent }),\n ...(relation.qualifiers === undefined ? {} : { qualifiers: shapeOf(relation.qualifiers, grammar, path, problems) }),\n ...(relation.symmetric === undefined ? {} : { symmetric: relation.symmetric }),\n ...(relation.transitive === undefined ? {} : { transitive: relation.transitive }),\n ...(relation.abstract === undefined ? {} : { abstract: relation.abstract }),\n ...(relation.key === undefined ? {} : { key: relation.key }),\n };\n}\n\n/**\n * This function gives a relation kind of canon with the name of a relation kind of the engine as an extension. The\n * extension adds one pair of ends: each `from` kind of canon with each `to` kind of canon. The pair of the spine relates\n * no kind of canon, so the engine permits the same edges as canon.\n */\nfunction extensionOf(relation: RelationKindDef, problems: string[]): RelationExtension {\n if (relation.qualifiers !== undefined || relation.key !== undefined || relation.parent !== undefined) {\n problems.push(`${GRAMMAR_FILE}#/relations/${relation.name}: a relation of the engine gets only more kinds at its ends.`);\n }\n return { relation: relation.name, from: [...relation.from], to: [...relation.to] };\n}\n\n/**\n * This function gives the kinds and the relation kinds of the grammar as an add-on of the engine.\n *\n * @throws EngineGrammarError when the grammar has a rule that the engine cannot keep\n */\nexport function engineAddOn(grammar: Grammar): RegistryInput {\n const problems: string[] = [];\n const facets: EngineFacet[] = grammar.facets.map((facet) => ({\n name: facet.name,\n description: facet.description,\n attributes: shapeOf(facet.attributes, grammar, `${GRAMMAR_FILE}#/facets/${facet.name}/attributes`, problems),\n }));\n for (const [name, schema] of Object.entries(grammar.$defs)) checkKeywords(schema, `${GRAMMAR_FILE}#/$defs/${name}`, problems);\n const kinds = grammar.kinds.map((kind) => kindOf(kind, grammar, problems));\n const relations: EngineRelation[] = [];\n const extensions: RelationExtension[] = [];\n for (const relation of grammar.relations) {\n const spine = spineRelations.find((candidate) => candidate.name === relation.name);\n if (spine === undefined) relations.push(relationOf(relation, grammar, problems));\n else extensions.push(extensionOf(relation, problems));\n }\n if (problems.length > 0) throw new EngineGrammarError(problems);\n const input = {\n kinds,\n relations,\n ...(facets.length > 0 ? { facets } : {}),\n ...(extensions.length > 0 ? { extensions } : {}),\n audience: CANON_AUDIENCE,\n };\n return withoutInherited(input);\n}\n\n/** The schema of an attribute that a kind of canon does not have: it refuses each value. */\nconst NO_VALUE = z.never().describe(\"A kind of canon has no value of this attribute of its parents.\").optional();\n\n/**\n * This function narrows each kind to the attributes that canon gives it. In the engine, a kind also gets each attribute\n * of its parents and their facets. Thus the root of the spine gives each kind of canon the attributes `name` and\n * `notes`. The schema of canon has only its own attributes, so the kind refuses each other attribute.\n *\n * @throws EngineGrammarError when a kind gets requirements from its parents in the engine\n */\nfunction withoutInherited(input: RegistryInput & { readonly kinds: readonly EngineKind[] }): RegistryInput {\n const first = spineRegistry(input);\n const problems: string[] = [];\n const kinds = input.kinds.map((kind) => {\n if (first.effectiveRequirements(kind.name).length !== (kind.requirements ?? []).length) {\n problems.push(`${GRAMMAR_FILE}#/kinds/${kind.name}: the engine adds the requirements of the parents, and canon does not.`);\n }\n const inherited = Object.keys(first.effectiveShape(kind.name)).filter((name) => !Object.hasOwn(kind.attributes, name));\n if (inherited.length === 0) return kind;\n return { ...kind, attributes: { ...kind.attributes, ...Object.fromEntries(inherited.map((name) => [name, NO_VALUE])) } };\n });\n if (problems.length > 0) throw new EngineGrammarError(problems);\n return { ...input, kinds };\n}\n\n/**\n * This function gives the registry of the engine with the spine and the kinds of canon.\n *\n * @throws EngineGrammarError when the grammar has a rule that the engine cannot keep\n */\nexport function engineRegistry(grammar: Grammar): Registry {\n return spineRegistry(engineAddOn(grammar));\n}\n\n/** The records of canon in the engine: each entity and each relation, or the problems of the load. */\nexport interface EngineLoad {\n readonly entities: readonly Entity[];\n readonly edges: readonly EngineEdge[];\n /** The problems: one text for each record or relation that the engine refuses or changes. */\n readonly problems: readonly string[];\n}\n\n/** This function gives the names of the fields of two objects that do not have the same value. */\nfunction changedFields(before: object, after: object): readonly string[] {\n const left = new Map(Object.entries(before));\n const right = new Map(Object.entries(after));\n return [...new Set([...left.keys(), ...right.keys()])].filter((name) => !isDeepStrictEqual(left.get(name), right.get(name))).sort();\n}\n\n/**\n * This function loads each record and each relation into the engine. A record or a relation that the engine refuses is a\n * problem. A value that the engine changes is also a problem: the load keeps each value. The engine adds only the scope\n * `public`, the default scope of each kind of canon, to an envelope with no scope.\n */\nexport function loadIntoEngine(registry: Registry, records: readonly LoadedRecord[]): EngineLoad {\n const kinds = new Map(records.map(({ record }) => [record.id, record.kind]));\n const entities: Entity[] = [];\n const edges: EngineEdge[] = [];\n const problems: string[] = [];\n const compare = (path: string, part: string, before: object, after: object): void => {\n const changed = changedFields(before, after);\n if (changed.length > 0) problems.push(`${path}: the engine changes the ${part} ${changed.join(\", \")}.`);\n };\n const refuse = (path: string, error: unknown): void => {\n problems.push(`${path}: ${errorMessage(error).replaceAll(\"\\n\", \" \")}`);\n };\n for (const { path, record } of records) {\n const envelope = record.envelope ?? {};\n try {\n const entity = registry.validateEntity({ id: record.id, kind: record.kind, attrs: { ...record.attrs }, envelope });\n compare(path, \"attributes\", record.attrs, entity.attrs);\n compare(path, \"envelope fields\", { scope: \"public\", ...envelope }, entity.envelope);\n entities.push(entity);\n } catch (error) {\n refuse(path, error);\n }\n for (const edge of record.edges ?? []) {\n const at = `${path} ${edge.type} ${edge.to}`;\n const qualifiers = edge.qualifiers ?? {};\n try {\n const parsed = registry.validateEdge(\n { from: record.id, type: edge.type, to: edge.to, qualifiers: { ...qualifiers }, envelope: edge.envelope ?? {} },\n (id) => kinds.get(id),\n );\n compare(at, \"qualifiers\", qualifiers, parsed.qualifiers);\n compare(at, \"envelope fields\", edge.envelope ?? {}, parsed.envelope);\n edges.push(parsed);\n } catch (error) {\n refuse(at, error);\n }\n }\n }\n return { entities, edges, problems };\n}\n","// The import of the map of homes of @mark1russell7/conventions into records of the ontology.\nimport { type Home, reposOf } from \"@mark1russell7/conventions\";\nimport type { AtlasRead } from \"./atlas.ts\";\nimport { makeId, npmPackageId, npmPurl, repositoryId } from \"./ids.ts\";\nimport type { EdgeRecord, EntityRecord } from \"./types.ts\";\n\n/** The id of the record of kind source for the map of homes. */\nexport const MAP_SOURCE_ID = \"source.conventions-map\";\n\n/** The id of the record of kind source for the lists of the public repositories of each owner on GitHub. */\nexport const GITHUB_SOURCE_ID = \"source.github-repositories\";\n\n/** The ids of the sources of the import. The import writes each record of these sources, and removes the old ones. */\nexport const IMPORT_SOURCE_IDS: readonly string[] = [MAP_SOURCE_ID, GITHUB_SOURCE_ID];\n\n/** A public repository of an owner, as GitHub gives it. */\nexport interface PublicRepository {\n readonly owner: string;\n readonly name: string;\n readonly url: string;\n /** This text is the purpose of the repository, as its owner wrote it on GitHub. */\n readonly description?: string | undefined;\n /** This value is true for a fork of the repository of another account. */\n readonly fork?: boolean | undefined;\n /** This value is true for a repository that its owner archived. */\n readonly archived?: boolean | undefined;\n /** The default branch of the repository. The read of the test gates examines it. */\n readonly defaultBranch?: string | undefined;\n}\n\n/** The facts of npm for one package name. */\nexport interface NpmFact {\n /** True when npm has a version of the package. */\n readonly published: boolean;\n /** The repository of the latest version, as `owner/name`, when its `package.json` names a repository on GitHub. */\n readonly repository?: string;\n}\n\n/** The live facts that the import adds to the map: the public repositories and the facts of npm. */\nexport interface HomeFacts {\n /** Each public repository of each owner. A repository that is not here is private, or it does not exist. */\n readonly repositories: readonly PublicRepository[];\n /** The facts of npm for each package name of the map. */\n readonly npm: ReadonlyMap<string, NpmFact>;\n /** The version of `@mark1russell7/conventions` that has the map. */\n readonly version: string;\n /** The read of the duplication atlas. With no read, the import gives no candidate. */\n readonly atlas?: AtlasRead | undefined;\n}\n\n/** The result of an import: the records, in the order of their ids, and a text for each home or repository that it left out. */\nexport interface HomeImport {\n readonly records: readonly EntityRecord[];\n readonly skipped: readonly string[];\n}\n\n/** The envelope of each record that the import makes from the map. */\nconst ENVELOPE = { source_ids: [MAP_SOURCE_ID] } as const;\n\n/** The envelope of a repository that only the lists of GitHub name. */\nconst GITHUB_ENVELOPE = { source_ids: [GITHUB_SOURCE_ID] } as const;\n\n/** This function gives the repository `owner/name` of a repository URL of npm, or undefined when it is not on GitHub. */\nexport function githubRepositoryOf(url: string): string | undefined {\n const lower = url.toLowerCase();\n const host = \"github.com\";\n const at = lower.indexOf(host);\n const separator = lower.charAt(at + host.length);\n if (at < 0 || (separator !== \"/\" && separator !== \":\")) return undefined;\n const [owner = \"\", rest = \"\"] = lower.slice(at + host.length + 1).split(\"/\");\n const name = (rest.split(\"#\")[0] ?? \"\").replace(/\\.git$/, \"\");\n if (owner === \"\" || name === \"\" || /\\s/.test(owner + name)) return undefined;\n return `${owner}/${name}`;\n}\n\n/** The records of an import while it runs, by id. A second record with the same id adds its edges to the first. */\nclass RecordSet {\n private readonly byId = new Map<string, EntityRecord>();\n\n add(record: EntityRecord): void {\n const earlier = this.byId.get(record.id);\n if (earlier === undefined) {\n this.byId.set(record.id, record);\n return;\n }\n const edges = [...(earlier.edges ?? [])];\n for (const edge of record.edges ?? []) {\n if (!edges.some((other) => other.type === edge.type && other.to === edge.to)) edges.push(edge);\n }\n this.byId.set(record.id, { ...earlier, edges });\n }\n\n /** This function gives each record in the order of the ids, with its edges in the order of their type and end. */\n sorted(): readonly EntityRecord[] {\n const order = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n return [...this.byId.values()]\n .map((record) => {\n const edges = [...(record.edges ?? [])].sort((a, b) => order(`${a.type} ${a.to}`, `${b.type} ${b.to}`));\n const base: EntityRecord = { id: record.id, kind: record.kind, attrs: record.attrs, ...(record.envelope === undefined ? {} : { envelope: record.envelope }) };\n return edges.length === 0 ? base : { ...base, edges };\n })\n .sort((a, b) => order(a.id, b.id));\n }\n}\n\n/**\n * This function makes the records of the ontology from the map of homes and the live facts. It reads nothing itself.\n *\n * - Each home gives a record of kind area, and its repository gives a record of kind repository with the relation home-of.\n * - The import finds each repository under each owner, so a move between the owners does not wait on the map.\n * - A repository that is not public is left out. A home whose repository is not public is left out, except a planned home:\n * its repository is a record with `exists: false`.\n * - Each package of the map gives a record of kind package. Its repository comes from npm when npm names one.\n * - Each repository of `alsoIn` gives the relation holds-copy to the area: the code of the area moves between it and the home.\n * - Each public repository that is not a fork and not archived gives a record of kind repository, also when the map does\n * not name it. Its source is then the lists of GitHub. A repository record has the description of GitHub.\n */\nexport function recordsFromHomes(homes: readonly Home[], facts: HomeFacts): HomeImport {\n const records = new RecordSet();\n const skipped: string[] = [];\n const known = new Map(facts.repositories.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository]));\n const find = (home: Home, ref: string): PublicRepository | undefined => {\n for (const candidate of reposOf({ ...home, repo: ref, alsoIn: [] })) {\n const repository = known.get(candidate.toLowerCase());\n if (repository !== undefined) return repository;\n }\n return undefined;\n };\n const addRepository = (repository: PublicRepository, exists: boolean, edges: readonly EdgeRecord[], envelope: EntityRecord[\"envelope\"] = ENVELOPE): string => {\n const id = repositoryId(repository.owner, repository.name);\n const attrs: Record<string, unknown> = { owner: repository.owner, name: repository.name, url: repository.url, exists };\n const description = repository.description?.trim() ?? \"\";\n if (description !== \"\") attrs[\"description\"] = description;\n records.add({ id, kind: \"repository\", attrs, envelope, edges });\n return id;\n };\n records.add({\n id: MAP_SOURCE_ID,\n kind: \"source\",\n attrs: { title: \"The map of homes of @mark1russell7/conventions\", url: \"https://www.npmjs.com/package/@mark1russell7/conventions\", version: facts.version, license: \"MIT\" },\n });\n for (const home of homes) {\n const areaId = makeId(\"area\", home.area);\n const found = find(home, home.repo);\n const [owner = \"\", name = \"\"] = home.repo.split(\"/\");\n if (found === undefined && home.state !== \"planned\") {\n skipped.push(`The area ${home.area}: its repository is not public.`);\n continue;\n }\n const homeRepository = found ?? { owner, name, url: `https://github.com/${home.repo}` };\n const homeId = addRepository(homeRepository, found !== undefined, [{ type: \"home-of\", to: areaId, qualifiers: { state: home.state } }]);\n const attrs: Record<string, unknown> = { title: home.title, covers: home.covers };\n const note = home.note ?? \"\";\n if (note !== \"\") attrs[\"note\"] = note;\n if (home.words.length > 0) attrs[\"words\"] = home.words;\n if (home.signatures !== undefined && home.signatures.length > 0) attrs[\"signatures\"] = home.signatures;\n if (home.modules !== undefined && home.modules.length > 0) attrs[\"modules\"] = home.modules;\n records.add({ id: areaId, kind: \"area\", attrs, envelope: ENVELOPE });\n const pending = new Set(home.pending ?? []);\n for (const packageName of [...new Set([...home.packages, ...pending])]) {\n const fact = facts.npm.get(packageName);\n const published = fact?.published ?? !pending.has(packageName);\n const state = published ? \"published\" : home.packages.includes(packageName) ? \"unpublished\" : \"planned\";\n const npmRepository = fact?.repository === undefined ? undefined : find(home, fact.repository);\n const partOf = npmRepository === undefined ? homeId : addRepository(npmRepository, true, []);\n const packageAttrs: Record<string, unknown> = { name: packageName, registry: \"npm\", purl: npmPurl(packageName), state };\n if (published) packageAttrs[\"url\"] = `https://www.npmjs.com/package/${packageName}`;\n records.add({\n id: npmPackageId(packageName),\n kind: \"package\",\n attrs: packageAttrs,\n envelope: ENVELOPE,\n edges: [\n { type: \"part-of\", to: partOf },\n { type: \"covers\", to: areaId },\n ],\n });\n }\n for (const ref of home.alsoIn ?? []) {\n const repository = find(home, ref);\n if (repository === undefined) {\n skipped.push(`The area ${home.area}: a repository of alsoIn is not public.`);\n continue;\n }\n const id = repositoryId(repository.owner, repository.name);\n if (id !== homeId) addRepository(repository, true, [{ type: \"holds-copy\", to: areaId }]);\n }\n }\n records.add({\n id: GITHUB_SOURCE_ID,\n kind: \"source\",\n attrs: { title: \"The lists of the public repositories of each owner on GitHub\", url: \"https://docs.github.com/en/rest/repos/repos#list-repositories-for-a-user\" },\n });\n for (const repository of facts.repositories) {\n if (repository.fork !== true && repository.archived !== true) addRepository(repository, true, [], GITHUB_ENVELOPE);\n }\n return { records: records.sorted(), skipped };\n}\n","// The polite read of the URLs of the import: each request at the pace of its host, through polite-crawler/api.\nimport type { HomeAnswer } from \"@mark1russell7/conventions\";\nimport { errorMessage } from \"@mark1russell7/text\";\nimport { redactSecrets } from \"@mark1russell7/text/redact\";\nimport { fetchTransport, send, type Transport } from \"polite-crawler/api\";\nimport { HostScheduler, realClock } from \"polite-crawler/politeness\";\n\n/** The answers for a list of URLs: the text of each URL, or the reason why there is no text. */\nexport type UrlAnswers = ReadonlyMap<string, HomeAnswer>;\n\n/** A function that reads each URL and gives the answer for each URL. A fake of a test can give the answers at once. */\nexport type UrlFetch = (urls: readonly string[]) => UrlAnswers | Promise<UrlAnswers>;\n\n/** The name of the client in each request. The repository is the contact. */\nexport const USER_AGENT = \"canon-import/1 (+https://github.com/metrograph-labs/canon)\";\n\n/** The most requests in progress at one time. Each host has one request in progress at most. */\nexport const HOSTS_AT_ONCE = 4;\n\n/** The name of each API in a message. Another host has its own name in the message. */\nconst SOURCES: Readonly<Record<string, string>> = { \"api.github.com\": \"the GitHub API\", \"registry.npmjs.org\": \"the npm registry\" };\n\n/** The options of `politeFetch`. */\nexport interface PoliteFetchOptions {\n /** This value is a GitHub token. Only the requests to `api.github.com` send it, for the rate limit of a token. */\n readonly githubToken?: string | undefined;\n /** This function sends each request. The default is `fetchTransport` of `polite-crawler/api` with `USER_AGENT`. A test gives a fake. */\n readonly transport?: Transport | undefined;\n}\n\n/**\n * This function gives a fetch that reads each URL through `send` of `polite-crawler/api`. Each host has one request in\n * progress at most, and the policy of the crawler sets the rest between two requests of a host.\n *\n * - An answer 2xx gives its text. Another status gives the error `HTTP <status>`, as `githubFetch` of conventions does.\n * The fetch follows no redirect.\n * - A request with no answer, or a stopped host, gives the text of the error. The text has no token.\n */\nexport function politeFetch(options: PoliteFetchOptions = {}): (urls: readonly string[]) => Promise<UrlAnswers> {\n const transport = options.transport ?? fetchTransport({ userAgent: USER_AGENT });\n const pace = { scheduler: new HostScheduler(realClock, HOSTS_AT_ONCE), now: realClock.now };\n const token = options.githubToken === undefined || options.githubToken === \"\" ? undefined : options.githubToken;\n const answerOf = async (url: string): Promise<HomeAnswer> => {\n const host = new URL(url).host;\n const secrets = host === \"api.github.com\" && token !== undefined ? [token] : [];\n const headers: Record<string, string> = secrets.length > 0 ? { accept: \"application/vnd.github+json\", authorization: `Bearer ${String(token)}` } : {};\n try {\n const { reply } = await send(pace, transport, {\n source: SOURCES[host] ?? host,\n host,\n what: url,\n exchange: { method: \"GET\", url, headers, body: null },\n secrets,\n redact: redactSecrets,\n });\n return reply.status >= 200 && reply.status < 300 ? { text: reply.body } : { error: `HTTP ${String(reply.status)}` };\n } catch (error) {\n return { error: redactSecrets(errorMessage(error), secrets) };\n }\n };\n return async (urls) => new Map(await Promise.all(urls.map(async (url) => [url, await answerOf(url)] as const)));\n}\n","// The read of the live facts of the import: the public repositories of each owner, the facts of npm and the duplication atlas.\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { type Home, type HomeAnswer, OWNERS } from \"@mark1russell7/conventions\";\nimport { ATLAS_URL, readAtlas } from \"./atlas.ts\";\nimport { githubRepositoryOf, type HomeFacts, type NpmFact, type PublicRepository } from \"./homes.ts\";\nimport { politeFetch, type UrlAnswers, type UrlFetch } from \"./polite.ts\";\n\n/** The most pages of 100 repositories that the read asks for each owner. A full last page is an error. */\nexport const REPOSITORY_PAGES = 5;\n\n/** This function gives the URLs of the pages of the public repositories of each owner. */\nexport function repositoryPageUrls(): readonly string[] {\n return OWNERS.flatMap((owner) =>\n Array.from({ length: REPOSITORY_PAGES }, (_, page) => `https://api.github.com/users/${owner.login}/repos?type=owner&per_page=100&page=${String(page + 1)}`),\n );\n}\n\n/** This function gives the URL of the latest version of an npm package in the registry. */\nexport function npmLatestUrl(name: string): string {\n return `https://registry.npmjs.org/${name.replaceAll(\"/\", \"%2f\")}/latest`;\n}\n\n/** This function reads the public repositories of the answers of the pages. It throws when a page has no answer, or the last page is full. */\nexport function repositoriesOfPages(answers: UrlAnswers): readonly PublicRepository[] {\n const repositories: PublicRepository[] = [];\n for (const owner of OWNERS) {\n for (let page = 1; page <= REPOSITORY_PAGES; page += 1) {\n const url = `https://api.github.com/users/${owner.login}/repos?type=owner&per_page=100&page=${String(page)}`;\n const answer = answers.get(url);\n if (answer === undefined || \"error\" in answer) throw new Error(`GitHub gave no list of the repositories of ${owner.login}: ${answer?.error ?? \"no answer\"}`);\n const list = JSON.parse(answer.text) as readonly { name: string; owner: { login: string }; html_url: string; private: boolean; fork?: boolean; archived?: boolean; description?: string | null; default_branch?: string }[];\n if (page === REPOSITORY_PAGES && list.length === 100) throw new Error(`${owner.login} has more than ${String(REPOSITORY_PAGES * 100)} repositories: increase REPOSITORY_PAGES.`);\n for (const item of list) {\n if (!item.private) {\n repositories.push({ owner: item.owner.login, name: item.name, url: item.html_url, description: item.description ?? undefined, fork: item.fork === true, archived: item.archived === true, defaultBranch: item.default_branch });\n }\n }\n if (list.length < 100) break;\n }\n }\n return repositories;\n}\n\n/** This function reads the fact of npm for one package from the answer for its latest version. It throws on an error that is not 404. */\nexport function npmFactOf(name: string, answer: HomeAnswer | undefined): NpmFact {\n if (answer === undefined) throw new Error(`npm gave no answer for ${name}.`);\n if (\"error\" in answer) {\n if (answer.error === \"HTTP 404\") return { published: false };\n throw new Error(`npm gave an error for ${name}: ${answer.error}`);\n }\n const manifest = JSON.parse(answer.text) as { repository?: string | { url?: string } };\n const url = typeof manifest.repository === \"string\" ? manifest.repository : manifest.repository?.url;\n const repository = url === undefined ? undefined : githubRepositoryOf(url);\n return repository === undefined ? { published: true } : { published: true, repository };\n}\n\n/** This function gives the version of the installed `@mark1russell7/conventions`, which has the map. */\nexport function conventionsVersion(): string {\n const file = createRequire(import.meta.url).resolve(\"@mark1russell7/conventions/package.json\");\n return (JSON.parse(readFileSync(file, \"utf8\")) as { version: string }).version;\n}\n\n/**\n * This function reads the live facts of the homes from GitHub, npm and the duplication atlas. The facts are the public\n * repositories of each owner, the latest version of each package of the map, and the atlas. The default fetch is\n * `politeFetch` with no token. Each request goes at the pace of its host.\n */\nexport async function readHomeFacts(homes: readonly Home[], fetch: UrlFetch = politeFetch()): Promise<HomeFacts> {\n const names = [...new Set(homes.flatMap((home) => [...home.packages, ...(home.pending ?? [])]))].sort();\n const answers = await fetch([...repositoryPageUrls(), ...names.map(npmLatestUrl), ATLAS_URL]);\n const npm = new Map(names.map((name) => [name, npmFactOf(name, answers.get(npmLatestUrl(name)))]));\n return { repositories: repositoriesOfPages(answers), npm, version: conventionsVersion(), atlas: readAtlas(answers.get(ATLAS_URL)) };\n}\n","// The read of the grammar and of each record file from the folders of a repository.\nimport { readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { findFiles, toPosix } from \"@mark1russell7/files\";\nimport { GRAMMAR_FILE, ONTOLOGY_FOLDER, RECORD_SCHEMA_FILE } from \"./ids.ts\";\nimport type { EntityRecord, Grammar, JsonSchema, LoadedRecord, Ontology } from \"./types.ts\";\n\n/** This error tells that a file of the ontology is not valid JSON. The check gives each other problem as a `Problem`. */\nexport class OntologyReadError extends Error {\n /** The path of the file, relative to the root. */\n readonly path: string;\n\n constructor(path: string, message: string) {\n super(`${path}: ${message}`);\n this.name = \"OntologyReadError\";\n this.path = path;\n }\n}\n\n/** This function reads a JSON file. It throws an `OntologyReadError` with the relative path when the text is not JSON. */\nfunction readJson(root: string, path: string): unknown {\n const text = readFileSync(join(root, path), \"utf8\");\n try {\n return JSON.parse(text) as unknown;\n } catch (error) {\n throw new OntologyReadError(path, error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * This function reads the grammar, the schema of a record file and each record file of the repository at `root`. The\n * record files are each `.json` file under the folder `ontology`, in sorted order. The function does not check them:\n * `checkOntology` does that.\n */\nexport function readOntology(root: string): Ontology {\n const grammar = readJson(root, GRAMMAR_FILE) as Grammar;\n const recordSchema = readJson(root, RECORD_SCHEMA_FILE) as JsonSchema;\n const files = findFiles({ root, include: [`${ONTOLOGY_FOLDER}/**/*.json`] });\n const records: LoadedRecord[] = files.map((file) => {\n const path = toPosix(relative(root, file));\n return { path, record: readJson(root, path) as EntityRecord };\n });\n return { grammar, recordSchema, records };\n}\n","// src/random.ts\n/** The generator mulberry32. The seed is read as a 32-bit unsigned integer. */\nfunction mulberry32(seed) {\n\tlet state = seed >>> 0;\n\treturn () => {\n\t\tstate = state + 0x6d2b79f5 >>> 0;\n\t\tlet t = state;\n\t\tt = Math.imul(t ^ t >>> 15, t | 1);\n\t\tt ^= t + Math.imul(t ^ t >>> 7, t | 61);\n\t\treturn ((t ^ t >>> 14) >>> 0) / 4294967296;\n\t};\n}\n/**\n* The FNV-1a hash of 32 bits of a string. The option `input` selects the units that the hash reads:\n*\n* - `\"utf8\"` (the default): the UTF-8 bytes, equal to the bytes of `TextEncoder`. A lone surrogate becomes the bytes of U+FFFD.\n* - `\"utf16\"`: the UTF-16 code units of the string, one unit for each step, from `charCodeAt`.\n* - `\"wtf8\"`: the UTF-8 bytes of each code point. A lone surrogate becomes its own 3 bytes (WTF-8).\n*\n* For a string without a lone surrogate, `\"utf8\"` and `\"wtf8\"` give the same hash. The function uses no API of Node or\n* of the browser, so the hash is the same on each platform.\n*/\nfunction fnv1a32(text, options) {\n\tconst input = options?.input ?? \"utf8\";\n\tlet h = 0x811c9dc5;\n\tif (input === \"utf16\") {\n\t\tfor (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619);\n\t\treturn h >>> 0;\n\t}\n\tif (input !== \"utf8\" && input !== \"wtf8\") throw new RangeError(`fnv1a32: input is \"utf8\", \"utf16\" or \"wtf8\", not ${String(input)}.`);\n\tfor (const ch of text) {\n\t\tlet c = ch.codePointAt(0);\n\t\tif (input === \"utf8\" && c >= 55296 && c <= 57343) c = 65533;\n\t\tif (c < 128) h = Math.imul(h ^ c, 16777619);\n\t\telse if (c < 2048) {\n\t\t\th = Math.imul(h ^ (192 | c >> 6), 16777619);\n\t\t\th = Math.imul(h ^ (128 | c & 63), 16777619);\n\t\t} else if (c < 65536) {\n\t\t\th = Math.imul(h ^ (224 | c >> 12), 16777619);\n\t\t\th = Math.imul(h ^ (128 | c >> 6 & 63), 16777619);\n\t\t\th = Math.imul(h ^ (128 | c & 63), 16777619);\n\t\t} else {\n\t\t\th = Math.imul(h ^ (240 | c >> 18), 16777619);\n\t\t\th = Math.imul(h ^ (128 | c >> 12 & 63), 16777619);\n\t\t\th = Math.imul(h ^ (128 | c >> 6 & 63), 16777619);\n\t\t\th = Math.imul(h ^ (128 | c & 63), 16777619);\n\t\t}\n\t}\n\treturn h >>> 0;\n}\n/** The 32-bit seed of a number (its low 32 bits, unsigned) or of a string (its FNV-1a hash). */\nfunction seedOf(seed) {\n\tif (typeof seed === \"string\") return fnv1a32(seed);\n\tif (!Number.isFinite(seed)) throw new RangeError(`seedOf: a seed is a finite number or a string, not ${seed}.`);\n\treturn seed >>> 0;\n}\n/** The seed of the stream with the name `label` under `seed`: the hash of `\"<seed>:<label>\"`. */\nfunction deriveSeed(seed, label) {\n\treturn fnv1a32(`${seed}:${label}`);\n}\n/**\n* One item of a list, chosen by highest random weight: each key has a weight from `seed`, and the largest weight wins.\n*\n* - The order of the list does not change the choice. The smaller key wins a tie of weights.\n* - When a list gains an item, only the draws that the new item wins change. For `n` items, the share of those draws is approximately `1 / (n + 1)`.\n* - When a list loses an item, only the draws of that item change.\n*\n* The function reads one hash for each item, so a choice costs O(n). The list is not empty, and each key occurs once.\n*/\nfunction stablePick(seed, items, keyOf = String) {\n\tif (items.length === 0) throw new RangeError(\"stablePick: the list is empty.\");\n\tconst start = seedOf(seed);\n\tconst seen = /* @__PURE__ */ new Set();\n\tlet best;\n\tfor (const item of items) {\n\t\tconst key = keyOf(item);\n\t\tif (seen.has(key)) throw new RangeError(`stablePick: the key ${JSON.stringify(key)} occurs twice.`);\n\t\tseen.add(key);\n\t\tconst weight = mulberry32(deriveSeed(start, key))();\n\t\tif (best === void 0 || weight > best.weight || weight === best.weight && key < best.key) best = {\n\t\t\titem,\n\t\t\tkey,\n\t\t\tweight\n\t\t};\n\t}\n\treturn best.item;\n}\n/**\n* A random order of a list with the Plackett-Luce law of the weights (the Gumbel-max method). Each item gets the sum of\n* its log-weight and a Gumbel draw. The order goes from the largest sum to the smallest.\n*\n* - The first item is item `i` with the probability `w_i / sum(w)`. Each next item has the same law over the items that remain.\n* - The draw of an item comes from the stream `random(seed).fork(key)`. Thus a new item or a lost item does not change the order of the other items.\n* - Items with equal sums keep the order of the list. Thus the items with the log-weight `-Infinity` come last, in the order of the list.\n*\n* The function reads one draw for each item, and it does not change its inputs. Each key occurs once. A log-weight is\n* finite or `-Infinity`.\n*/\nfunction plackettLuceOrder(seed, items, logWeightOf, keyOf = String) {\n\tconst root = random(seed);\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst sums = items.map((item) => {\n\t\tconst key = keyOf(item);\n\t\tif (seen.has(key)) throw new RangeError(`plackettLuceOrder: the key ${JSON.stringify(key)} occurs twice.`);\n\t\tseen.add(key);\n\t\tconst logWeight = logWeightOf(item);\n\t\tif (Number.isNaN(logWeight) || logWeight === Number.POSITIVE_INFINITY) throw new RangeError(`plackettLuceOrder: the log-weight of the key ${JSON.stringify(key)} is ${logWeight}, and a log-weight is finite or -Infinity.`);\n\t\treturn logWeight + root.fork(key).gumbel();\n\t});\n\treturn items.map((_, index) => index).sort((x, y) => sums[y] - sums[x] || x - y).map((index) => items[index]);\n}\nfunction wholeOrThrow(name, value) {\n\tif (!Number.isSafeInteger(value)) throw new RangeError(`${name}: ${value} is not a safe integer.`);\n}\n/** A generator with draws, from a seed. The default source is mulberry32. */\nfunction random(seed, source = mulberry32) {\n\tconst start = seedOf(seed);\n\treturn randomOf(source(start), start, source);\n}\n/** A generator with draws, from a source that you give. `fork` uses `source` for the new streams. */\nfunction randomOf(next, seed, source = mulberry32) {\n\tconst below = (n) => {\n\t\twholeOrThrow(\"below\", n);\n\t\tif (n < 1) throw new RangeError(`below: n is 1 or more, not ${n}.`);\n\t\treturn Math.floor(next() * n);\n\t};\n\treturn {\n\t\tseed,\n\t\tnext,\n\t\tint(min, max) {\n\t\t\twholeOrThrow(\"int\", min);\n\t\t\twholeOrThrow(\"int\", max);\n\t\t\tif (min > max) throw new RangeError(`int: min ${min} is more than max ${max}.`);\n\t\t\treturn min + Math.floor(next() * (max - min + 1));\n\t\t},\n\t\tbelow,\n\t\trange: (min, max) => min + next() * (max - min),\n\t\tchance: (p) => next() < p,\n\t\tpick(items) {\n\t\t\tif (items.length === 0) throw new RangeError(\"pick: the list is empty.\");\n\t\t\treturn items[below(items.length)];\n\t\t},\n\t\tweighted(weights) {\n\t\t\tlet total = 0;\n\t\t\tfor (const w of weights) {\n\t\t\t\tif (!(Number.isFinite(w) && w >= 0)) throw new RangeError(`weighted: each weight is finite and 0 or more, not ${w}.`);\n\t\t\t\ttotal += w;\n\t\t\t}\n\t\t\tif (!(total > 0)) throw new RangeError(\"weighted: the sum of the weights is 0.\");\n\t\t\tlet left = next() * total;\n\t\t\tfor (let i = 0; i < weights.length; i++) {\n\t\t\t\tleft -= weights[i];\n\t\t\t\tif (left < 0) return i;\n\t\t\t}\n\t\t\tfor (let i = weights.length - 1;; i--) if (weights[i] > 0) return i;\n\t\t},\n\t\tshuffle(items) {\n\t\t\tconst out = [...items];\n\t\t\tfor (let i = out.length - 1; i > 0; i--) {\n\t\t\t\tconst j = below(i + 1);\n\t\t\t\t[out[i], out[j]] = [out[j], out[i]];\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t\tsample(items, k) {\n\t\t\twholeOrThrow(\"sample\", k);\n\t\t\tif (k < 0 || k > items.length) throw new RangeError(`sample: k is from 0 to ${items.length}, not ${k}.`);\n\t\t\tconst out = [...items];\n\t\t\tfor (let i = 0; i < k; i++) {\n\t\t\t\tconst j = i + below(out.length - i);\n\t\t\t\t[out[i], out[j]] = [out[j], out[i]];\n\t\t\t}\n\t\t\treturn out.slice(0, k);\n\t\t},\n\t\tnormal(mean = 0, sd = 1) {\n\t\t\tconst u1 = Math.max(next(), 1e-12);\n\t\t\tconst u2 = next();\n\t\t\treturn mean + sd * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n\t\t},\n\t\tgumbel(location = 0, scale = 1) {\n\t\t\tif (!(Number.isFinite(scale) && scale > 0)) throw new RangeError(`gumbel: the scale is finite and more than 0, not ${scale}.`);\n\t\t\tconst u = Math.max(next(), 1e-12);\n\t\t\treturn location - scale * Math.log(-Math.log(u));\n\t\t},\n\t\tfork(label) {\n\t\t\tconst child = deriveSeed(seed, label);\n\t\t\treturn randomOf(source(child), child, source);\n\t\t}\n\t};\n}\n/** The largest count of seeds that one range gives. A larger range is an error, not a long run. */\nconst MAX_RANGE = 1e6;\n/**\n* The seeds of a run: the seeds in `given` (the text of an environment variable, for example\n* `process.env.SEED`), else the default seeds. An empty text gives the defaults.\n*\n* The text is one seed (`17`) or a list of seeds and ranges with commas (`1,3,9-11` gives 1, 3, 9, 10\n* and 11), in the order of the list. A range has two whole numbers, the low one first. An empty part, a\n* part that is not an integer and a range with the low end last are each a `RangeError`.\n*/\nfunction seedsFrom(given, defaults) {\n\tif (given === void 0 || given.trim() === \"\") return [...defaults];\n\treturn given.split(\",\").flatMap((raw) => {\n\t\tconst part = raw.trim();\n\t\tconst range = /^(\\d+)\\s*-\\s*(\\d+)$/u.exec(part);\n\t\tif (range !== null) {\n\t\t\tconst [low, high] = [Number(range[1]), Number(range[2])];\n\t\t\tif (!Number.isSafeInteger(high) || high < low || high - low >= MAX_RANGE) throw new RangeError(`seedsFrom: the range ${part} is not low-high with at most ${MAX_RANGE} seeds.`);\n\t\t\treturn Array.from({ length: high - low + 1 }, (_, i) => low + i);\n\t\t}\n\t\tconst seed = part === \"\" ? NaN : Number(part);\n\t\tif (!Number.isSafeInteger(seed)) throw new RangeError(`seedsFrom: a seed is an integer, not ${part === \"\" ? \"an empty part\" : part}.`);\n\t\treturn [seed];\n\t});\n}\nexport { deriveSeed, fnv1a32, mulberry32, plackettLuceOrder, random, randomOf, seedOf, seedsFrom, stablePick };\n\n//# sourceMappingURL=random.js.map","// The pick of one target for an agent (roadmap C71). Two agents that read the same sorted list go to the same small\n// target. The pick gives each agent a random target of size XS or S that has no live claim and no open pull request.\nimport { random } from \"@mark1russell7/rigor-generators\";\nimport { type BoardIssue, isExpired, targetOfIssue } from \"./board.ts\";\nimport type { Size, TargetRecord } from \"./targets.ts\";\n\n/** The sizes that a pick gives: less than one day of work. */\nexport const PICK_SIZES: readonly Size[] = [\"XS\", \"S\"];\n\n/** The most candidates that a pick asks GitHub about. Each question is one search request. */\nexport const PICK_TRIES = 5;\n\n/** The result of a pick. */\nexport interface TargetPick {\n /** The target, or undefined when no candidate is free. */\n readonly target: TargetRecord | undefined;\n /** The number of the open issue of the target, or undefined when the target has no open issue. */\n readonly issue: number | undefined;\n /** The candidates that an open pull request names, in the order of the pick. */\n readonly skipped: readonly string[];\n /** The number of candidates before the check of the pull requests. */\n readonly candidates: number;\n}\n\n/**\n * This function gives the targets that a pick can give: each claimable target of size XS or S that has no live claim.\n * A claim is live when its open issue has an assignee and the claim is not older than `CLAIM_HOURS`.\n */\nexport function pickCandidates(targets: readonly TargetRecord[], issues: readonly BoardIssue[], now: number): TargetRecord[] {\n const claimed = new Set<string>();\n for (const issue of issues) {\n if (issue.state !== \"open\" || issue.assignees.length === 0 || isExpired(issue, now)) continue;\n const id = targetOfIssue(issue.body);\n if (id !== undefined) claimed.add(id);\n }\n return targets.filter((target) => target.attrs.claimable && PICK_SIZES.includes(target.attrs.size) && !claimed.has(target.id));\n}\n\n/**\n * This function picks one target. It puts the candidates in a random order from `seed`, and it gives the first that no\n * open pull request names. It asks `hasOpenPull` about `tries` candidates or fewer. The same inputs give the same pick.\n */\nexport async function pickTarget(\n candidates: readonly TargetRecord[],\n issues: readonly BoardIssue[],\n seed: string,\n hasOpenPull: (targetId: string) => Promise<boolean>,\n tries: number = PICK_TRIES,\n): Promise<TargetPick> {\n const skipped: string[] = [];\n for (const target of random(seed).shuffle(candidates).slice(0, tries)) {\n if (await hasOpenPull(target.id)) {\n skipped.push(target.id);\n continue;\n }\n const issue = issues.find((candidate) => candidate.state === \"open\" && targetOfIssue(candidate.body) === target.id);\n return { target, issue: issue?.number, skipped, candidates: candidates.length };\n }\n return { target: undefined, issue: undefined, skipped, candidates: candidates.length };\n}\n","// The read of the test gates of each home repository from public data of GitHub: the tree of the default branch, the\n// workflow files and the package files of that tree, and the rules of the branch.\nimport { utcText } from \"@mark1russell7/algebra/clock\";\nimport type { HomeAnswer } from \"@mark1russell7/conventions\";\nimport { arrayOf, booleanOf, isRecord, readText, recordOf, textOf } from \"@mark1russell7/optional/read\";\nimport { parse } from \"yaml\";\nimport type { PublicRepository } from \"./homes.ts\";\nimport { repositoryId } from \"./ids.ts\";\nimport { politeFetch, type UrlFetch } from \"./polite.ts\";\nimport type { EntityRecord, GateFact, GateName, LoadedRecord, TestGates } from \"./types.ts\";\n\n/** The test gates of the read, in the order of the records. */\nexport const GATE_NAMES: readonly GateName[] = [\"mutation\", \"property\", \"speed\", \"rigs\"];\n\n/** The lane file of the mutation tests, when the caller of the workflow gives no input `lane`. */\nexport const MUTATION_LANE = \"mutation.json\";\n\n/** The file of the rig records of a repository. */\nexport const RIGS_FILE = \"docs/rigs.json\";\n\n/** The packages of property tests. A package file that names one of them in its dependencies has property tests. */\nexport const PROPERTY_PACKAGES: readonly string[] = [\"fast-check\", \"@mark1russell7/rigor-testkit\"];\n\n/** The package of the speed gates. */\nexport const BENCH_PACKAGE = \"@mark1russell7/rigor-bench\";\n\n/** The most rules of a branch that the read asks for. A full page is a no read. */\nexport const RULES_PAGE = 100;\n\n/** A home repository and the branch that the read examines. */\nexport interface GateRepository {\n readonly owner: string;\n readonly name: string;\n readonly branch: string;\n}\n\n/** This function gives the path of a branch in a URL: each part of the name, encoded. */\nfunction branchPath(branch: string): string {\n return branch.split(\"/\").map(encodeURIComponent).join(\"/\");\n}\n\n/** This function gives the URL of the full tree of the branch of a repository: one request for each repository. */\nexport function treeUrl(repository: GateRepository): string {\n return `https://api.github.com/repos/${repository.owner}/${repository.name}/git/trees/${branchPath(repository.branch)}?recursive=1`;\n}\n\n/** This function gives the URL of the rules of the branch of a repository. GitHub gives them with no token. */\nexport function rulesUrl(repository: GateRepository): string {\n return `https://api.github.com/repos/${repository.owner}/${repository.name}/rules/branches/${branchPath(repository.branch)}?per_page=${String(RULES_PAGE)}`;\n}\n\n/**\n * This function gives the URL of the branch of a repository. Its answer has the classic protection of the branch, with\n * its necessary checks. GitHub gives it with no token.\n */\nexport function branchUrl(repository: GateRepository): string {\n return `https://api.github.com/repos/${repository.owner}/${repository.name}/branches/${branchPath(repository.branch)}`;\n}\n\n/** This function gives the URL of the text of one file of the branch. The host of raw files is not the API. */\nexport function fileUrl(repository: GateRepository, path: string): string {\n return `https://raw.githubusercontent.com/${repository.owner}/${repository.name}/${branchPath(repository.branch)}/${path.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n}\n\n/** The files of a tree: the id of the content of each file, by its path. */\nexport interface Tree {\n readonly files: ReadonlyMap<string, string>;\n}\n\n/** A read that cannot tell the facts, and its reason. */\nexport interface NoRead {\n readonly no_read: string;\n}\n\n/** This function gives the text of the answer, or the reason why there is no text. */\nfunction textOrReason(answer: HomeAnswer | undefined, what: string): { readonly text: string } | NoRead {\n if (answer === undefined) return { no_read: `GitHub gave no answer for ${what}.` };\n if (\"error\" in answer) return { no_read: `GitHub gave ${answer.error} for ${what}.` };\n return { text: answer.text };\n}\n\n/** This function reads JSON. It gives undefined when the text is not JSON. */\nfunction jsonOf(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/**\n * This function reads the answer for a tree. A tree that GitHub truncated is a no read, because a missing file of such a\n * tree does not show that the file is absent. A 404 and each other error are a no read too.\n */\nexport function treeOf(answer: HomeAnswer | undefined): Tree | NoRead {\n const read = textOrReason(answer, \"the tree of the branch\");\n if (\"no_read\" in read) return read;\n const body = jsonOf(read.text);\n if (booleanOf(body, \"truncated\") === true) return { no_read: \"GitHub gave a truncated tree, so the read cannot see each file.\" };\n const items = arrayOf(body, \"tree\", (item) => (isRecord(item) ? item : undefined));\n if (items === undefined) return { no_read: \"The answer for the tree has no list of files.\" };\n const files = new Map<string, string>();\n for (const item of items) {\n const path = textOf(item, \"path\");\n const sha = textOf(item, \"sha\");\n if (textOf(item, \"type\") === \"blob\" && path !== undefined && sha !== undefined) files.set(path, sha);\n }\n return { files };\n}\n\n/** This function reads the names of the necessary checks from the answer for the rules of a branch. */\nexport function necessaryChecksOf(answer: HomeAnswer | undefined): { readonly checks: readonly string[] } | NoRead {\n const read = textOrReason(answer, \"the rules of the branch\");\n if (\"no_read\" in read) return read;\n const rules = jsonOf(read.text);\n if (!Array.isArray(rules)) return { no_read: \"The answer for the rules of the branch is not a list.\" };\n if (rules.length >= RULES_PAGE) return { no_read: `The branch has ${String(RULES_PAGE)} rules or more, and the read asks for one page.` };\n const checks = new Set<string>();\n for (const rule of rules) {\n if (textOf(rule, \"type\") !== \"required_status_checks\") continue;\n const parameters = recordOf(rule, \"parameters\");\n for (const check of arrayOf(parameters, \"required_status_checks\", (item) => textOf(item, \"context\")) ?? []) checks.add(check);\n }\n return { checks: [...checks].sort() };\n}\n\n/**\n * This function reads the names of the necessary checks of the classic protection from the answer for a branch. A\n * branch with no classic protection, or with checks that are not enforced, gives no check.\n */\nexport function classicChecksOf(answer: HomeAnswer | undefined): { readonly checks: readonly string[] } | NoRead {\n const read = textOrReason(answer, \"the branch\");\n if (\"no_read\" in read) return read;\n const branch = jsonOf(read.text);\n if (!isRecord(branch)) return { no_read: \"The answer for the branch is not a JSON object.\" };\n const protection = recordOf(branch, \"protection\");\n const required = recordOf(protection, \"required_status_checks\");\n if (booleanOf(protection, \"enabled\") !== true || required === undefined || textOf(required, \"enforcement_level\") === \"off\") return { checks: [] };\n const contexts = arrayOf(required, \"contexts\", readText) ?? [];\n const checks = arrayOf(required, \"checks\", (item) => textOf(item, \"context\")) ?? [];\n return { checks: [...new Set([...contexts, ...checks])].sort() };\n}\n\n/**\n * This function gives the necessary checks of a branch: the checks of its rulesets and of its classic protection. A\n * no read of one of the two is a no read, because the missing part can make a check necessary.\n */\nexport function branchChecksOf(rules: { readonly checks: readonly string[] } | NoRead, classic: { readonly checks: readonly string[] } | NoRead): { readonly checks: readonly string[] } | NoRead {\n if (\"no_read\" in rules) return rules;\n if (\"no_read\" in classic) return classic;\n return { checks: [...new Set([...rules.checks, ...classic.checks])].sort() };\n}\n\n/** This function tells if a path is a workflow of GitHub Actions. GitHub reads only the files at the top of the folder. */\nexport function isWorkflowPath(path: string): boolean {\n return /^\\.github\\/workflows\\/[^/]+\\.ya?ml$/.test(path);\n}\n\n/** This function tells if a path is a package file of the repository: not in `node_modules` and not in a fixture folder. */\nexport function isPackagePath(path: string): boolean {\n const parts = path.split(\"/\");\n return parts.at(-1) === \"package.json\" && !parts.some((part) => part === \"node_modules\" || /^(__)?fixtures?(__)?$/.test(part));\n}\n\n/** This function gives the paths of the files that the read needs from a tree: each workflow and each package file. */\nexport function filesToRead(tree: Tree): readonly string[] {\n return [...tree.files.keys()].filter((path) => isWorkflowPath(path) || isPackagePath(path)).sort();\n}\n\n/** A step of a job of a workflow. */\ninterface Step {\n readonly uses?: string | undefined;\n readonly run?: string | undefined;\n /** The inputs of the action that the step uses. */\n readonly with?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** A job of a workflow. */\ninterface Job {\n readonly id: string;\n /** The name of the check of the job: the name of the job, or its id. */\n readonly name: string;\n /** The reusable workflow that the job calls. */\n readonly uses?: string | undefined;\n /** The inputs of the reusable workflow. */\n readonly with?: Readonly<Record<string, unknown>> | undefined;\n readonly needs: readonly string[];\n readonly steps: readonly Step[];\n}\n\n/** A workflow file and its jobs. */\ninterface Workflow {\n readonly path: string;\n readonly jobs: readonly Job[];\n}\n\n/** This function reads the jobs of a workflow file. It gives a no read when the text is not a workflow. */\nfunction workflowOf(path: string, text: string): Workflow | NoRead {\n let document: unknown;\n try {\n document = parse(text) as unknown;\n } catch {\n return { no_read: `The workflow ${path} is not valid YAML.` };\n }\n const jobs = recordOf(document, \"jobs\");\n if (jobs === undefined) return { no_read: `The workflow ${path} has no jobs.` };\n return {\n path,\n jobs: Object.entries(jobs).map(([id, job]): Job => {\n const needs = isRecord(job) ? job[\"needs\"] : undefined;\n return {\n id,\n name: textOf(job, \"name\") ?? id,\n uses: textOf(job, \"uses\"),\n with: recordOf(job, \"with\"),\n needs: typeof needs === \"string\" ? [needs] : (arrayOf(job, \"needs\", readText) ?? []),\n steps: arrayOf(job, \"steps\", (step) => (isRecord(step) ? { uses: textOf(step, \"uses\"), run: textOf(step, \"run\"), with: recordOf(step, \"with\") } : undefined)) ?? [],\n };\n }),\n };\n}\n\n/** This function tells if a job uses the reusable workflow `file` of the template, or the copy of the template itself. */\nfunction callsTemplate(job: Job, file: string): boolean {\n const uses = job.uses ?? \"\";\n return (uses.startsWith(\"mark1russell7/template/\") || uses.startsWith(\"./\")) && new RegExp(`(^|/)\\\\.github/workflows/${file.replaceAll(\".\", \"\\\\.\")}(@|$)`).test(uses);\n}\n\n/** The paths of the action `gate-summary`: in the template, and in the copy of the template itself. */\nconst GATE_SUMMARY = [\"mark1russell7/template/.github/actions/gate-summary\", \"./.github/actions/gate-summary\"];\n\n/** This function tells if a step uses the action `gate-summary` of the template, at a commit or with no ref. */\nfunction usesGateSummary(step: Step): boolean {\n const uses = step.uses ?? \"\";\n const at = uses.indexOf(\"@\");\n return GATE_SUMMARY.includes(at === -1 ? uses : uses.slice(0, at));\n}\n\n/**\n * This function gives the kind of gate that the job marks: the input `gate` of its step `gate-summary` of the\n * template. A job with no marker, or with a word that is not a gate, gives undefined.\n */\nfunction markedGate(job: { readonly steps: readonly Step[] }): GateName | undefined {\n for (const step of job.steps) {\n const gate = usesGateSummary(step) ? step.with?.[\"gate\"] : undefined;\n const kind = GATE_NAMES.find((name) => name === gate);\n if (kind !== undefined) return kind;\n }\n return undefined;\n}\n\n/** A command that starts the tests of a package. */\nconst TEST_COMMAND = /\\b(vitest|(pnpm|npm|yarn)(\\s+-r|\\s+--recursive)?\\s+(run\\s+)?test)\\b/;\n\n/** A command or a step that starts a bench of `@mark1russell7/rigor-bench`. */\nconst BENCH_COMMAND = /\\b(rigor-gate-line|rigor-stamp|bench(mark)?)\\b/i;\n\n/** This function gives the checks of the jobs `seeds` and of each job that needs them, also through other jobs. */\nfunction checksOf(workflow: Workflow, seeds: readonly Job[]): readonly string[] {\n const ids = new Set(seeds.map((job) => job.id));\n let grew = ids.size > 0;\n while (grew) {\n grew = false;\n for (const job of workflow.jobs) {\n if (!ids.has(job.id) && job.needs.some((need) => ids.has(need))) {\n ids.add(job.id);\n grew = true;\n }\n }\n }\n return workflow.jobs.filter((job) => ids.has(job.id)).map((job) => (job.uses === undefined ? job.name : `${job.name} / *`));\n}\n\n/**\n * This function tells if the check `pattern` of a gate gives the check `name`. A `*` and each expression `${{ }}` match\n * any text. A job of a matrix with no name gives its values after its name, in parentheses.\n */\nexport function checkMatches(pattern: string, name: string): boolean {\n if (pattern.length > MAX_CHECK_TEXT || name.length > MAX_CHECK_TEXT) return false;\n const parts = literalParts(pattern);\n if (globMatches(parts, name)) return true;\n if (!name.endsWith(\")\")) return false;\n // A job of a matrix: the name, a space and its values in parentheses.\n for (let at = name.indexOf(\" (\"); at !== -1; at = name.indexOf(\" (\", at + 1)) if (globMatches(parts, name.slice(0, at))) return true;\n return false;\n}\n\n/** The longest check name or pattern that `checkMatches` reads. A longer text matches nothing. */\nconst MAX_CHECK_TEXT = 512;\n\n/**\n * This function gives the literal parts of a check pattern. A `*` and each expression `${{ }}` separate the parts. An\n * expression with no end is literal text. The function uses no regular expression, so its time is linear.\n */\nfunction literalParts(pattern: string): string[] {\n const parts: string[] = [];\n let part = \"\";\n for (let at = 0; at < pattern.length; ) {\n if (pattern[at] === \"*\") {\n parts.push(part);\n part = \"\";\n at++;\n continue;\n }\n const end = pattern.startsWith(\"${{\", at) ? pattern.indexOf(\"}}\", at + 3) : -1;\n if (end !== -1) {\n parts.push(part);\n part = \"\";\n at = end + 2;\n continue;\n }\n part += pattern[at] ?? \"\";\n at++;\n }\n parts.push(part);\n return parts;\n}\n\n/**\n * This function tells if `name` is the literal parts `parts` with any text between each two. The first part starts the\n * name, and the last part ends it. Each middle part takes its first place after the part before it.\n */\nfunction globMatches(parts: readonly string[], name: string): boolean {\n const first = parts[0] ?? \"\";\n if (parts.length === 1) return name === first;\n const last = parts.at(-1) ?? \"\";\n if (!name.startsWith(first) || name.length < first.length + last.length || !name.endsWith(last)) return false;\n const end = name.length - last.length;\n let at = first.length;\n for (const part of parts.slice(1, -1)) {\n const found = name.indexOf(part, at);\n if (found === -1 || found + part.length > end) return false;\n at = found + part.length;\n }\n return true;\n}\n\n/** The jobs of the workflows that `pick` selects, with the files of their workflows and their checks. */\ninterface Picked {\n readonly files: readonly string[];\n readonly checks: readonly string[];\n readonly jobs: readonly Job[];\n}\n\n/** This function gives the path of the workflow of the same repository that the job calls (`uses: ./path`), or undefined. */\nfunction localCallOf(job: Job): string | undefined {\n return job.uses?.startsWith(\"./\") === true ? job.uses.slice(2) : undefined;\n}\n\n/**\n * This function selects the jobs of each workflow with `pick`, and gives their files and their checks. A job that calls a\n * workflow of the same repository with a selected job is a selected job of its own workflow too. So a check that needs\n * the call (`CI OK` of `pull-request.yml`, for example) holds the gate.\n */\nfunction pickJobs(workflows: readonly Workflow[], pick: (job: Job) => boolean): Picked {\n const jobs = workflows.flatMap((workflow) => workflow.jobs.filter(pick));\n const selected = new Set<Job>(jobs);\n const called = new Set<string>();\n let grew = true;\n while (grew) {\n grew = false;\n for (const workflow of workflows) {\n if (!called.has(workflow.path) && workflow.jobs.some((job) => selected.has(job))) {\n called.add(workflow.path);\n grew = true;\n }\n for (const job of workflow.jobs) {\n const call = localCallOf(job);\n if (!selected.has(job) && call !== undefined && called.has(call)) {\n selected.add(job);\n grew = true;\n }\n }\n }\n }\n const files: string[] = [];\n const checks = new Set<string>();\n for (const workflow of workflows) {\n const seeds = workflow.jobs.filter((job) => selected.has(job));\n if (seeds.length === 0) continue;\n files.push(workflow.path);\n for (const check of checksOf(workflow, seeds)) checks.add(check);\n }\n return { files, checks: [...checks].sort(), jobs };\n}\n\n/** The dependencies of a package file. */\ninterface PackageFile {\n readonly path: string;\n readonly dependencies: ReadonlySet<string>;\n}\n\n/** This function reads the names of the dependencies of each kind from the text of a package file. */\nfunction packageOf(path: string, text: string): PackageFile | NoRead {\n const manifest = jsonOf(text);\n if (!isRecord(manifest)) return { no_read: `The package file ${path} is not a JSON object.` };\n const names = [\"dependencies\", \"devDependencies\", \"optionalDependencies\", \"peerDependencies\"].flatMap((field) => Object.keys(recordOf(manifest, field) ?? {}));\n return { path, dependencies: new Set(names) };\n}\n\n/** The facts of a gate from a list of parts. Each part has a text for `missing`, and the files that show it. */\nfunction factOf(parts: readonly { readonly missing: string; readonly files: readonly string[] }[], checks: readonly string[], rules: { readonly checks: readonly string[] } | NoRead): GateFact {\n const files = [...new Set(parts.flatMap((part) => part.files))].sort();\n const missing = parts.filter((part) => part.files.length === 0).map((part) => part.missing);\n if (missing.length > 0) return { exists: false, ...(files.length > 0 ? { files } : {}), missing };\n if (\"no_read\" in rules) return { exists: true, files, checks, no_read: rules.no_read };\n return { exists: true, necessary: checks.some((check) => rules.checks.some((name) => checkMatches(check, name))), files, checks };\n}\n\n/**\n * This function gives the fact of each test gate from a tree, the answers for its files and the rules of the branch. It\n * reads nothing itself.\n *\n * - mutation: a lane file (`mutation.json`, or the input `lane` of the caller) and a job that calls `reusable-mutation.yml`.\n * - property: a package file that names `fast-check` or `@mark1russell7/rigor-testkit`. Its checks are the checks of\n * each job that calls `reusable-ci.yml` or starts the tests, and of each job that needs such a job.\n * - speed: a package file that names `@mark1russell7/rigor-bench`, and a job that starts a bench. A summary job with\n * `gate: speed` (the marker of `gate-summary`) gives the bench jobs. With no marker in the repository, the read uses\n * a word rule. Then a bench job uses the action `stamp-gate`, a bin of the bench or a command with the word `bench`.\n * The bins are `rigor-gate-line` and `rigor-stamp`.\n * - rigs: the file `docs/rigs.json` and a job that calls `reusable-rigs.yml`.\n *\n * A file with no answer, or a file that the read cannot parse, gives a no read for each gate that needs it.\n */\nexport function gatesOf(tree: Tree, answers: ReadonlyMap<string, HomeAnswer | undefined>, rules: { readonly checks: readonly string[] } | NoRead): Readonly<Record<GateName, GateFact>> {\n const workflows: Workflow[] = [];\n const packages: PackageFile[] = [];\n let workflowFault: string | undefined;\n let packageFault: string | undefined;\n for (const path of filesToRead(tree)) {\n const read = textOrReason(answers.get(path), `the file ${path}`);\n const parsed = \"no_read\" in read ? read : isWorkflowPath(path) ? workflowOf(path, read.text) : packageOf(path, read.text);\n if (\"no_read\" in parsed) {\n if (isWorkflowPath(path)) workflowFault ??= parsed.no_read;\n else packageFault ??= parsed.no_read;\n } else if (\"jobs\" in parsed) workflows.push(parsed);\n else packages.push(parsed);\n }\n const naming = (names: readonly string[]): readonly string[] => packages.filter((file) => names.some((name) => file.dependencies.has(name))).map((file) => file.path);\n const has = (path: string): readonly string[] => (tree.files.has(path) ? [path] : []);\n\n const mutationJobs = pickJobs(workflows, (job) => callsTemplate(job, \"reusable-mutation.yml\"));\n const lanes = mutationJobs.jobs.map((job) => (typeof job.with?.[\"lane\"] === \"string\" ? job.with[\"lane\"] : MUTATION_LANE));\n const lane = lanes.find((path) => tree.files.has(path)) ?? lanes[0] ?? MUTATION_LANE;\n const mutation: GateFact =\n workflowFault !== undefined\n ? { no_read: workflowFault }\n : factOf(\n [\n { missing: `the lane file \\`${lane}\\``, files: has(lane) },\n { missing: \"a job that calls `reusable-mutation.yml` of `mark1russell7/template`\", files: mutationJobs.files },\n ],\n mutationJobs.checks,\n rules,\n );\n\n const propertyFiles = naming(PROPERTY_PACKAGES);\n const testJobs = pickJobs(workflows, (job) => callsTemplate(job, \"reusable-ci.yml\") || job.steps.some((step) => TEST_COMMAND.test(step.run ?? \"\")));\n const propertyPart = { missing: \"a package file that names `fast-check` or `@mark1russell7/rigor-testkit` in its dependencies\", files: propertyFiles };\n const property: GateFact =\n packageFault !== undefined\n ? { no_read: packageFault }\n : propertyFiles.length > 0 && workflowFault !== undefined\n ? { exists: true, files: propertyFiles, no_read: workflowFault }\n : factOf([propertyPart], testJobs.checks, rules);\n\n // The marker is exact, so a repository with a marked summary job does not use the word rule (C41).\n const marked = workflows.some((workflow) => workflow.jobs.some((job) => markedGate(job) === \"speed\"));\n const benchJobs = pickJobs(workflows, (job) =>\n marked ? markedGate(job) === \"speed\" : job.steps.some((step) => (step.uses ?? \"\").includes(\"/.github/actions/stamp-gate\") || BENCH_COMMAND.test(step.run ?? \"\")),\n );\n const speed: GateFact =\n (packageFault ?? workflowFault) !== undefined\n ? { no_read: packageFault ?? workflowFault ?? \"\" }\n : factOf(\n [\n { missing: `a package file that names \\`${BENCH_PACKAGE}\\` in its dependencies`, files: naming([BENCH_PACKAGE]) },\n { missing: \"a job that starts a bench: a summary job with `gate: speed`, the action `stamp-gate`, the bin `rigor-gate-line` or `rigor-stamp`, or a command `bench`\", files: benchJobs.files },\n ],\n benchJobs.checks,\n rules,\n );\n\n const rigsJobs = pickJobs(workflows, (job) => callsTemplate(job, \"reusable-rigs.yml\"));\n const rigs: GateFact =\n workflowFault !== undefined\n ? { no_read: workflowFault }\n : factOf(\n [\n { missing: `the file \\`${RIGS_FILE}\\``, files: has(RIGS_FILE) },\n { missing: \"a job that calls `reusable-rigs.yml` of `mark1russell7/template`\", files: rigsJobs.files },\n ],\n rigsJobs.checks,\n rules,\n );\n\n return { mutation, property, speed, rigs };\n}\n\n/** This function gives the time of a read in the form of the records: UTC, to the second (RFC 3339). */\nfunction timeText(ms: number): string {\n const text = utcText(ms);\n if (text === undefined) throw new RangeError(`The time ${String(ms)} of the read is not an instant in the years 1 to 9999.`);\n return text;\n}\n\n/** This function gives a no read for each gate. */\nfunction noReadOfEach(reason: string): Readonly<Record<GateName, GateFact>> {\n return { mutation: { no_read: reason }, property: { no_read: reason }, speed: { no_read: reason }, rigs: { no_read: reason } };\n}\n\n/**\n * This function reads the test gates of each repository. The default fetch is `politeFetch` with no token, so each\n * request goes at the pace of its host. The read makes two rounds of requests:\n *\n * 1. the tree, the rules and the classic protection of the branch of each repository, from the API of GitHub,\n * 2. each workflow file and each package file of each tree, from the host of raw files. Two files with the same content\n * id give one request.\n *\n * A repository whose tree has no read gives a no read for each gate. The read does not throw for one repository.\n */\nexport async function readTestGates(repositories: readonly GateRepository[], fetch: UrlFetch = politeFetch(), now: () => number = Date.now): Promise<ReadonlyMap<string, TestGates>> {\n const first = await fetch(repositories.flatMap((repository) => [treeUrl(repository), rulesUrl(repository), branchUrl(repository)]));\n const trees = repositories.map((repository) => ({\n repository,\n tree: treeOf(first.get(treeUrl(repository))),\n rules: branchChecksOf(necessaryChecksOf(first.get(rulesUrl(repository))), classicChecksOf(first.get(branchUrl(repository)))),\n }));\n const urlOfContent = new Map<string, string>();\n for (const { repository, tree } of trees) {\n if (\"no_read\" in tree) continue;\n for (const path of filesToRead(tree)) {\n const sha = tree.files.get(path) ?? \"\";\n if (!urlOfContent.has(sha)) urlOfContent.set(sha, fileUrl(repository, path));\n }\n }\n const second = await fetch([...new Set(urlOfContent.values())]);\n const readAt = timeText(now());\n const result = new Map<string, TestGates>();\n for (const { repository, tree, rules } of trees) {\n const answers = new Map<string, HomeAnswer | undefined>();\n if (!(\"no_read\" in tree)) for (const path of filesToRead(tree)) answers.set(path, second.get(urlOfContent.get(tree.files.get(path) ?? \"\") ?? \"\"));\n const gates = \"no_read\" in tree ? noReadOfEach(tree.no_read) : gatesOf(tree, answers, rules);\n result.set(repositoryId(repository.owner, repository.name), { read_at: readAt, branch: repository.branch, ...(\"no_read\" in rules ? {} : { necessary_checks: rules.checks }), gates });\n }\n return result;\n}\n\n/**\n * This function gives the home repositories that the read examines. Each is a record of kind repository that exists\n * and is the home of an area. The lists of GitHub give its default branch. A repository with no known default branch\n * is not in the list.\n */\nexport function gateRepositoriesOf(records: readonly EntityRecord[], repositories: readonly PublicRepository[]): readonly GateRepository[] {\n const branches = new Map(repositories.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository.defaultBranch]));\n const list: GateRepository[] = [];\n for (const record of records) {\n if (record.kind !== \"repository\" || record.attrs[\"exists\"] !== true || !(record.edges ?? []).some((edge) => edge.type === \"home-of\")) continue;\n const owner = String(record.attrs[\"owner\"]);\n const name = String(record.attrs[\"name\"]);\n const branch = branches.get(`${owner}/${name}`.toLowerCase());\n if (branch !== undefined && branch !== \"\") list.push({ owner, name, branch });\n }\n return list;\n}\n\n/** This function gives the text of the facts of a read with no time, to compare two reads. */\nfunction factText(gates: unknown): string {\n if (!isRecord(gates)) return \"\";\n const { read_at: _time, ...facts } = gates;\n return JSON.stringify(facts);\n}\n\n/**\n * This function adds the test gates of each repository to its record as the attribute `test_gates`. When the earlier\n * record of a repository has the same facts, the new record keeps the earlier time. Thus a read with no change writes\n * no file.\n */\nexport function withTestGates(records: readonly EntityRecord[], gates: ReadonlyMap<string, TestGates>, earlier: readonly LoadedRecord[] = []): readonly EntityRecord[] {\n const old = new Map(earlier.map(({ record }) => [record.id, record.attrs[\"test_gates\"]]));\n return records.map((record) => {\n const read = gates.get(record.id);\n if (read === undefined || record.kind !== \"repository\") return record;\n const before = old.get(record.id);\n const time = isRecord(before) && factText(before) === factText(read) ? textOf(before, \"read_at\") : undefined;\n return { ...record, attrs: { ...record.attrs, test_gates: time === undefined ? read : { ...read, read_at: time } } };\n });\n}\n","// The write of records to their files, and the drift between the files and the records that a program makes.\nimport { mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { pathOfId } from \"./ids.ts\";\nimport type { EntityRecord, LoadedRecord } from \"./types.ts\";\n\n/** This function gives the text of the file of a record: JSON with two spaces and a last line end. */\nexport function recordText(record: EntityRecord): string {\n return `${JSON.stringify(record, null, 2)}\\n`;\n}\n\n/** The changes of the files that make the files agree with a set of records. */\nexport interface WritePlan {\n /** The text of each file to write, by its path relative to the root. */\n readonly write: ReadonlyMap<string, string>;\n /** The files to remove: each file that a program made before, with no record in the new set. */\n readonly remove: readonly string[];\n /** The files that the plan does not write, because a person wrote their record. The program does not own them. */\n readonly keep: readonly string[];\n}\n\n/**\n * This function plans the changes that make the files agree with the records `records`. The program that made the\n * records owns each existing record for which `owns` is true. A file of such a record with no new record is removed.\n * The plan writes only the files whose text changes. It does not write over a record that the program does not own.\n */\nexport function planWrite(root: string, records: readonly EntityRecord[], existing: readonly LoadedRecord[], owns: (record: EntityRecord) => boolean): WritePlan {\n const write = new Map<string, string>();\n const others = new Set(existing.filter(({ record }) => !owns(record)).map(({ path }) => path));\n const keep: string[] = [];\n for (const record of records) {\n const path = pathOfId(record.id);\n if (others.has(path)) {\n keep.push(path);\n continue;\n }\n const text = recordText(record);\n let old: string | undefined;\n try {\n old = readFileSync(join(root, path), \"utf8\");\n } catch {\n old = undefined;\n }\n if (old?.replace(/\\r\\n/g, \"\\n\") !== text) write.set(path, text);\n }\n const kept = new Set(records.map((record) => pathOfId(record.id)));\n const remove = existing.filter(({ path, record }) => owns(record) && !kept.has(path)).map(({ path }) => path);\n return { write, remove, keep };\n}\n\n/** This function tells if a plan changes no file. */\nexport function isEmptyPlan(plan: WritePlan): boolean {\n return plan.write.size === 0 && plan.remove.length === 0;\n}\n\n/** This function applies a plan: it writes each file, with its folder, and removes each file of `remove`. */\nexport function applyPlan(root: string, plan: WritePlan): void {\n for (const [path, text] of plan.write) {\n mkdirSync(dirname(join(root, path)), { recursive: true });\n writeFileSync(join(root, path), text);\n }\n for (const path of plan.remove) rmSync(join(root, path));\n}\n","// The command line of the ontology: check the data, give the targets, and import the map of homes.\nimport { dirname, join } from \"node:path\";\nimport { HOMES } from \"@mark1russell7/conventions\";\nimport { findUp } from \"@mark1russell7/files\";\nimport { staleGenerated, writeGenerated } from \"@mark1russell7/ontology/node\";\nimport type { Printer } from \"@mark1russell7/text/print\";\nimport { ATLAS_SOURCE_ID, ATLAS_URL, readAtlas, recordsFromAtlas } from \"./atlas.ts\";\nimport { applyBoard, type BoardAction, BOARD_LIMIT, claimCommandOf, decideClaim, isExpired, type IssueApi, planBoard, targetOfIssue } from \"./board.ts\";\nimport { checkOntology } from \"./check.ts\";\nimport { CLONE_FLOOR, cloneGroups, cloneReport } from \"./clones.ts\";\nimport { ENGINE_FOLDER, ENGINE_GENERATE_OPTIONS, engineRegistry, loadIntoEngine } from \"./engine.ts\";\nimport { readHomeFacts } from \"./facts.ts\";\nimport { politeFetch, type UrlFetch } from \"./polite.ts\";\nimport { IMPORT_SOURCE_IDS, recordsFromHomes } from \"./homes.ts\";\nimport { GRAMMAR_FILE } from \"./ids.ts\";\nimport { readOntology } from \"./load.ts\";\nimport { PICK_TRIES, pickCandidates, pickTarget } from \"./pick.ts\";\nimport { claimFails, resultClaimsOf } from \"./results.ts\";\nimport { ONTOLOGY_REPOSITORY, targetsOf } from \"./targets.ts\";\nimport { gateRepositoriesOf, readTestGates, withTestGates } from \"./test-gates.ts\";\nimport type { EntityRecord, Ontology } from \"./types.ts\";\nimport { applyPlan, isEmptyPlan, planWrite, type WritePlan } from \"./write.ts\";\n\n/** The help text of the command line. */\nexport const USAGE: string = `Usage: canon <command> [--root <folder>]\n\nCommands:\n check Check the grammar and each record. Exit code 1 when there is a problem.\n targets Show the targets of the target query, the claimable targets first.\n targets --json Give the targets as JSON.\n targets --write Write the targets to ontology/target/.\n targets --check Exit code 1 when the files of ontology/target/ do not agree with the query.\n targets --pick [--seed <text>] [--json]\n Give one random claimable target of size XS or S, with no claim and no open pull request.\n The same seed gives the same target. Exit code 1 when no target is free.\n results Show each claim that needs a result record, and its state: checked, partial or not checked.\n results --json Give the claims as JSON.\n results --check Exit code 1 when a claim is not checked, or a status claim is partial.\n engine Load each record into the ontology engine, and check the files of schema/engine/.\n engine --write Write the files that the engine makes from the grammar to schema/engine/.\n import Read the map of homes and the live facts, and write the records of the map.\n board Show the changes that make the target board agree with the target query.\n board --apply Make the changes: open, change and close the issues of the board.\n claim --issue <number> --user <login> --comment <text>\n Decide a comment /claim or /unclaim on an issue of the board, and write the answer.\n clones [--floor <n>]\n Read the duplication atlas, and show the cloned code that no home covers, as Markdown.\n The report keeps a class with n or more copied syntax nodes (default ${String(CLONE_FLOOR)}).\n\nThe commands board, claim and targets --pick read the token of GitHub from GITHUB_TOKEN. The commands import and clones\nsend it to the API of GitHub when it is set. They make each request at the pace of its host.\n\nThe root is the folder of ${GRAMMAR_FILE}: the current folder or a parent of it.`;\n\n/** This function finds the root of the repository: the folder whose `schema` folder has the grammar. */\nexport function findRoot(from: string): string | undefined {\n const grammar = findUp(GRAMMAR_FILE, from);\n return grammar === null ? undefined : dirname(dirname(grammar));\n}\n\n/** This function tells if a record is one of the sources `sources`, or comes from one of them. */\nfunction fromSources(record: EntityRecord, sources: readonly string[]): boolean {\n return sources.includes(record.id) || (record.envelope?.source_ids ?? []).some((id) => sources.includes(id));\n}\n\n/** This function writes the changes of a plan as lines. */\nfunction showPlan(printer: Printer, plan: WritePlan): void {\n for (const path of plan.write.keys()) printer.line(`write ${path}`);\n for (const path of plan.remove) printer.line(`remove ${path}`);\n for (const path of plan.keep) printer.warn(`A person wrote ${path}, so the program keeps it.`);\n}\n\n/** This function writes the problems of the check. It gives the exit code: 0 with no problem, else 1. */\nfunction check(printer: Printer, ontology: Ontology): number {\n const problems = checkOntology(ontology);\n for (const problem of problems) printer.status(\"fail\", `${problem.path}: ${problem.message}`);\n if (problems.length > 0) return 1;\n printer.status(\"ok\", `${String(ontology.records.length)} records agree with the grammar.`);\n return 0;\n}\n\n/**\n * This function does the command `engine` (roadmap C18). It loads each record into the ontology engine, and it compares the\n * files of the engine with a new generation. It gives the exit code: 0 when the engine keeps each value and the files agree.\n */\nasync function engine(printer: Printer, root: string, ontology: Ontology, flags: ReadonlySet<string>): Promise<number> {\n const registry = engineRegistry(ontology.grammar);\n const folder = join(root, ENGINE_FOLDER);\n if (flags.has(\"--write\")) {\n for (const name of await writeGenerated(registry, folder, ENGINE_GENERATE_OPTIONS)) printer.line(`write ${ENGINE_FOLDER}/${name}`);\n }\n const load = loadIntoEngine(registry, ontology.records);\n for (const problem of load.problems) printer.status(\"fail\", problem);\n const stale = await staleGenerated(registry, folder, ENGINE_GENERATE_OPTIONS);\n for (const name of stale) {\n printer.status(\"fail\", `${ENGINE_FOLDER}/${name} does not agree with the grammar. Start \\`pnpm canon engine --write\\`, and commit the files.`);\n }\n if (load.problems.length > 0 || stale.length > 0) return 1;\n printer.status(\"ok\", `The engine keeps each value of ${String(load.entities.length)} records and ${String(load.edges.length)} relations.`);\n return 0;\n}\n\n/** This function runs the command `results`. It gives the exit code. */\nfunction results(printer: Printer, ontology: Ontology, flags: ReadonlySet<string>): number {\n const claims = resultClaimsOf(ontology);\n if (flags.has(\"--json\")) {\n printer.json(claims);\n return 0;\n }\n const open = claims.filter(claimFails);\n if (claims.length > 0) {\n printer.table(\n claims.map((claim) => [claim.state, claim.kind === \"status\" ? (claim.status ?? \"\") : `solved by ${claim.function ?? \"\"}`, claim.problem, claim.results.join(\", \")]),\n { head: [\"state\", \"claim\", \"problem\", \"results\"] },\n );\n }\n const total = `${String(claims.length - open.length)} of ${String(claims.length)} claims have a result record of the necessary scope.`;\n if (flags.has(\"--check\") && open.length > 0) {\n printer.status(\"fail\", `${total} Add a result for each claim that is not checked. A status claim needs a result with the scope of its problem.`);\n return 1;\n }\n printer.status(open.length === 0 ? \"ok\" : \"info\", total);\n return 0;\n}\n\n/** This function runs the command `targets`. It gives the exit code. */\nfunction targets(printer: Printer, root: string, ontology: Ontology, flags: ReadonlySet<string>): number {\n const list = targetsOf(ontology);\n if (flags.has(\"--json\")) {\n printer.json(list);\n return 0;\n }\n if (flags.has(\"--write\") || flags.has(\"--check\")) {\n const plan = planWrite(root, list, ontology.records, (record) => record.kind === \"target\");\n if (flags.has(\"--write\")) {\n applyPlan(root, plan);\n showPlan(printer, plan);\n printer.status(\"ok\", `${String(list.length)} targets.`);\n return 0;\n }\n if (isEmptyPlan(plan)) {\n printer.status(\"ok\", `The ${String(list.length)} files of ontology/target/ agree with the target query.`);\n return 0;\n }\n showPlan(printer, plan);\n printer.status(\"fail\", \"The files of ontology/target/ do not agree with the target query. Start `pnpm canon targets --write`, and commit the files.\");\n return 1;\n }\n printer.table(\n list.map((target) => [target.attrs.claimable ? \"yes\" : \"no\", target.attrs.size, target.attrs.home, target.attrs.title]),\n { head: [\"claimable\", \"size\", \"repository\", \"title\"] },\n );\n printer.line(`${String(list.filter((target) => target.attrs.claimable).length)} of ${String(list.length)} targets are claimable.`);\n return 0;\n}\n\n/**\n * This function runs the command `import`. It gives the exit code. When the read of the duplication atlas fails, the\n * import does not own the records of the atlas, so the old candidates stay.\n */\nasync function importHomes(printer: Printer, root: string, ontology: Ontology, options: CliOptions): Promise<number> {\n const fetch = options.fetch ?? politeFetch();\n const facts = await readHomeFacts(HOMES, fetch);\n const result = recordsFromHomes(HOMES, facts);\n const gates = await readTestGates(gateRepositoriesOf(result.records, facts.repositories), fetch, options.now);\n const homes = withTestGates(result.records, gates, ontology.records);\n const atlas = facts.atlas !== undefined && \"atlas\" in facts.atlas ? recordsFromAtlas(facts.atlas.atlas, facts.repositories, result.records) : undefined;\n const sources = atlas === undefined ? IMPORT_SOURCE_IDS : [...IMPORT_SOURCE_IDS, ATLAS_SOURCE_ID];\n const records = [...homes, ...(atlas?.records ?? [])];\n const plan = planWrite(root, records, ontology.records, (record) => fromSources(record, sources));\n applyPlan(root, plan);\n showPlan(printer, plan);\n for (const text of [...result.skipped, ...(atlas?.skipped ?? [])]) printer.warn(text);\n for (const [id, read] of gates) {\n const reasons = [...new Set(Object.values(read.gates).flatMap((gate) => (gate.no_read === undefined ? [] : [gate.no_read])))];\n if (reasons.length > 0) printer.warn(`The test gates of ${id} have no full read. ${reasons.join(\" \")}`);\n }\n if (facts.atlas !== undefined && \"error\" in facts.atlas) printer.warn(`The import keeps the old candidates. ${facts.atlas.error}`);\n printer.status(\"ok\", `${String(records.length)} records of the map of homes, of the lists of GitHub and of the duplication atlas.`);\n return 0;\n}\n\n/** The services of the commands that read or change GitHub. A test gives fakes. */\nexport interface CliOptions {\n /** This function gives the API of the issues of the board. It throws when there is no token. */\n readonly issues?: (() => IssueApi) | undefined;\n /** This function gives the current time, in milliseconds since 1970. The default is `Date.now`. */\n readonly now?: (() => number) | undefined;\n /** This function reads the URLs of the commands `import` and `clones`. The default is `politeFetch` with no token. */\n readonly fetch?: UrlFetch | undefined;\n}\n\n/** This function gives the value after the option `name`, or undefined. */\nfunction valueOf(args: readonly string[], name: string): string | undefined {\n const index = args.indexOf(name);\n return index < 0 ? undefined : args[index + 1];\n}\n\n/** This function writes a step of the board as a line. */\nfunction actionLine(action: BoardAction): string {\n if (action.kind === \"create\") return `open ${action.target}`;\n if (action.kind === \"update\") return `${action.reopen ? \"reopen \" : \"change \"} #${String(action.number)} ${action.target}`;\n if (action.kind === \"close\") return `close #${String(action.number)} ${action.target} (${action.reason})`;\n return `release #${String(action.number)} ${action.target} (${action.users.join(\", \")})`;\n}\n\n/** This function runs the command `clones`. It gives the exit code: 1 when the read of the atlas fails. */\nasync function clones(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const floorText = valueOf(args, \"--floor\");\n const floor = floorText === undefined ? CLONE_FLOOR : Number(floorText);\n if (!Number.isInteger(floor) || floor < 0) {\n printer.status(\"fail\", `The floor ${floorText ?? \"\"} is not a whole number of 0 or more.`);\n return 2;\n }\n const read = readAtlas((await (options.fetch ?? politeFetch())([ATLAS_URL])).get(ATLAS_URL));\n if (\"error\" in read) {\n printer.status(\"fail\", read.error);\n return 1;\n }\n const records = ontology.records.map((loaded) => loaded.record);\n printer.line(cloneReport(cloneGroups(read.atlas, records, floor), records, floor));\n return 0;\n}\n\n/** This function gives the API of the issues, or writes why there is none. */\nfunction issueApi(printer: Printer, options: CliOptions): IssueApi | undefined {\n if (options.issues === undefined) {\n printer.status(\"fail\", \"This command needs the API of GitHub. Set GITHUB_TOKEN.\");\n return undefined;\n }\n return options.issues();\n}\n\n/** This function runs the command `board`. It gives the exit code. */\nasync function board(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const limitText = valueOf(args, \"--limit\");\n const limit = limitText === undefined ? BOARD_LIMIT : Number(limitText);\n if (!Number.isSafeInteger(limit) || limit < 0) {\n printer.status(\"fail\", `The limit ${String(limitText)} is not a whole number of 0 or more.`);\n return 2;\n }\n const api = issueApi(printer, options);\n if (api === undefined) return 2;\n const now = (options.now ?? Date.now)();\n const issues = await api.issues();\n const pulls = new Set<string>();\n for (const issue of issues.filter((candidate) => candidate.state === \"open\" && isExpired(candidate, now))) {\n const id = targetOfIssue(issue.body);\n if (id !== undefined && (await api.hasOpenPull(id))) pulls.add(id);\n }\n const actions = planBoard({ targets: targetsOf(ontology), issues, now, pulls, limit });\n for (const action of actions) printer.line(actionLine(action));\n if (!args.includes(\"--apply\")) {\n printer.status(\"info\", `${String(actions.length)} changes. Give --apply to make them.`);\n return 0;\n }\n const created = await applyBoard(api, actions);\n printer.status(\"ok\", `${String(actions.length)} changes, ${String(created.length)} new issues.`);\n return 0;\n}\n\n/**\n * This function does the command `targets --pick` (roadmap C71). It gives the exit code: 1 when no target is free. With\n * no token, the pick reads only the list, and it tells the agent to look for a claim before the work.\n */\nasync function pick(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const now = (options.now ?? Date.now)();\n const seed = valueOf(args, \"--seed\") ?? String(now);\n const api = options.issues?.();\n const issues = api === undefined ? [] : await api.issues();\n const candidates = pickCandidates(targetsOf(ontology), issues, now);\n const result = await pickTarget(candidates, issues, seed, (id) => (api === undefined ? Promise.resolve(false) : api.hasOpenPull(id)));\n const { target, issue } = result;\n if (args.includes(\"--json\")) {\n const picked = target === undefined ? null : { id: target.id, title: target.attrs.title, size: target.attrs.size, home: target.attrs.home };\n printer.json({ seed, claimsRead: api !== undefined, candidates: result.candidates, skipped: result.skipped, target: picked, issue: issue ?? null });\n return target === undefined ? 1 : 0;\n }\n if (api === undefined) printer.warn(\"GITHUB_TOKEN is not set, so the pick did not read the claims and the pull requests. Do section 2 of AGENTS.md before the work.\");\n for (const id of result.skipped) printer.status(\"info\", `An open pull request names ${id}.`);\n if (target === undefined) {\n const tried = Math.min(PICK_TRIES, result.candidates);\n printer.status(\"fail\", `No target of size XS or S is free: ${String(tried)} tried of ${String(result.candidates)}. Start \\`pnpm canon targets\\`, and choose one.`);\n return 1;\n }\n printer.line(target.id);\n printer.line(target.attrs.title);\n printer.line(`size ${target.attrs.size}, home ${target.attrs.home}`);\n printer.line(issue === undefined ? \"No issue: the pull request is the claim.\" : `Claim issue #${String(issue)}: https://github.com/${ONTOLOGY_REPOSITORY}/issues/${String(issue)}`);\n printer.status(\"ok\", `One of ${String(result.candidates)} free targets, from the seed ${seed}. Give --seed ${seed} to get it again.`);\n return 0;\n}\n\n/** This function runs the command `claim`. It gives the exit code. */\nasync function claim(printer: Printer, ontology: Ontology, args: readonly string[], options: CliOptions): Promise<number> {\n const number = Number(valueOf(args, \"--issue\"));\n const user = valueOf(args, \"--user\") ?? \"\";\n const command = claimCommandOf(valueOf(args, \"--comment\") ?? \"\");\n if (!Number.isSafeInteger(number) || number < 1 || user === \"\") {\n printer.status(\"fail\", \"Give --issue <number>, --user <login> and --comment <text>.\");\n return 2;\n }\n if (command === undefined) {\n printer.status(\"info\", \"The comment is not /claim or /unclaim. No change.\");\n return 0;\n }\n const api = issueApi(printer, options);\n if (api === undefined) return 2;\n const issues = await api.issues();\n const issue = issues.find((candidate) => candidate.number === number);\n if (issue === undefined) {\n printer.status(\"info\", `The issue #${String(number)} is not an issue of the board. No change.`);\n return 0;\n }\n const id = targetOfIssue(issue.body);\n const target = targetsOf(ontology).find((candidate) => candidate.id === id);\n const decision = decideClaim({ command, user, issue, target, issues, now: (options.now ?? Date.now)() });\n if (decision.kind === \"set\") {\n const after = await api.update(number, { assignees: decision.assignees });\n if (command === \"claim\" && !after.assignees.includes(user)) {\n await api.comment(number, `GitHub did not assign \\`${user}\\`, so the claim did not start. Write the comment \\`/claim\\` again.`);\n printer.status(\"fail\", `GitHub did not assign ${user} to #${String(number)}.`);\n return 1;\n }\n }\n await api.comment(number, decision.comment);\n printer.status(decision.kind === \"set\" ? \"ok\" : \"info\", decision.comment);\n return 0;\n}\n\n/**\n * This function runs the command line with the arguments `args`, and gives the exit code. It writes only to `printer`.\n * The folder `cwd` is the start of the search for the root. The commands `board` and `claim` use `options.issues`.\n */\nexport async function runCli(args: readonly string[], printer: Printer, cwd: string, options: CliOptions = {}): Promise<number> {\n const rootIndex = args.indexOf(\"--root\");\n const rootArg = rootIndex < 0 ? undefined : args[rootIndex + 1];\n const rest = rootIndex < 0 ? args : [...args.slice(0, rootIndex), ...args.slice(rootIndex + 2)];\n const [command, ...flagList] = rest;\n const flags = new Set(flagList);\n if (command === undefined || command === \"--help\" || command === \"help\") {\n printer.line(USAGE);\n return command === undefined ? 2 : 0;\n }\n const root = rootArg ?? findRoot(cwd);\n if (root === undefined) {\n 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>.`);\n return 2;\n }\n try {\n const ontology = readOntology(root);\n if (command === \"check\") return check(printer, ontology);\n if (command === \"targets\" && flags.has(\"--pick\")) return await pick(printer, ontology, flagList, options);\n if (command === \"targets\") return targets(printer, root, ontology, flags);\n if (command === \"results\") return results(printer, ontology, flags);\n if (command === \"engine\") return await engine(printer, root, ontology, flags);\n if (command === \"import\") return await importHomes(printer, root, ontology, options);\n if (command === \"board\") return await board(printer, ontology, flagList, options);\n if (command === \"claim\") return await claim(printer, ontology, flagList, options);\n if (command === \"clones\") return await clones(printer, ontology, flagList, options);\n } catch (error) {\n printer.error(error);\n return 1;\n }\n printer.status(\"fail\", `The command ${command} is not a command of canon.`);\n printer.line(USAGE);\n return 2;\n}\n","// The API of the issues of a GitHub repository, for the target board. It sends each request through a REST client of\n// @procedures/gh, which holds the limits of GitHub.\nimport { arrayOf, numberOf, readArray, recordOf, textOf, timeOf } from \"@mark1russell7/optional/read\";\nimport type { RestAnswer, RestClient, RestRequest } from \"@procedures/gh\";\nimport { type BoardIssue, type IssueApi, type IssueChange, type IssueText, TARGET_LABEL } from \"./board.ts\";\n\n/** The most items of one page of a list. */\nconst PAGE = 100;\n\n/** The most pages of the list of issues: 1,000 issues. */\nconst MAX_PAGES = 10;\n\n/** The colors of the labels of the board, by the start of their names. */\nconst LABEL_COLOR = { target: \"0e8a16\", gap: \"c5def5\" } as const;\n\n/** This error tells that GitHub refused a request of the board. Its text has no token and no body of an answer. */\nexport class IssueApiError extends Error {\n override readonly name = \"IssueApiError\";\n /** This number is the status of the answer of GitHub. */\n readonly status: number;\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n\n/** This function gives the issue of an item of the REST API, or undefined for a pull request or an item that is not an issue. */\nexport function issueOfItem(item: unknown): BoardIssue | undefined {\n const number = numberOf(item, \"number\");\n const title = textOf(item, \"title\");\n const state = textOf(item, \"state\");\n if (number === undefined || title === undefined || (state !== \"open\" && state !== \"closed\")) return undefined;\n if (recordOf(item, \"pull_request\") !== undefined) return undefined;\n return {\n number,\n title,\n body: textOf(item, \"body\") ?? \"\",\n state,\n labels: arrayOf(item, \"labels\", (label) => textOf(label, \"name\")) ?? [],\n assignees: arrayOf(item, \"assignees\", (user) => textOf(user, \"login\")) ?? [],\n };\n}\n\n/** This function gives the time of the last event that assigned one of the assignees, or undefined when there is none. */\nexport function claimTimeOf(events: unknown, assignees: readonly string[]): number | undefined {\n let last: number | undefined;\n for (const event of readArray(events, (value) => value) ?? []) {\n const at = timeOf(event, \"created_at\");\n const login = textOf(recordOf(event, \"assignee\"), \"login\");\n if (textOf(event, \"event\") === \"assigned\" && at !== undefined && login !== undefined && assignees.includes(login)) last = Math.max(last ?? at, at);\n }\n return last;\n}\n\n/** The body of a PATCH of an issue for a change. */\nfunction patchOf(change: IssueChange): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (change.title !== undefined) body[\"title\"] = change.title;\n if (change.body !== undefined) body[\"body\"] = change.body;\n if (change.labels !== undefined) body[\"labels\"] = change.labels;\n if (change.state !== undefined) body[\"state\"] = change.state;\n if (change.stateReason !== undefined) body[\"state_reason\"] = change.stateReason;\n if (change.assignees !== undefined) body[\"assignees\"] = change.assignees;\n return body;\n}\n\n/**\n * This function gives the API of the issues of the repository `owner/name` through a REST client of GitHub. Each\n * request stops at `signal`. A status of 400 or more throws an `IssueApiError`.\n */\nexport function githubIssueApi(client: Pick<RestClient, \"request\">, repository: string, signal: AbortSignal): IssueApi {\n const base = `/repos/${repository}`;\n const send = async (request: RestRequest, what: string): Promise<RestAnswer> => {\n const answer = await client.request(request, signal);\n if (answer.status >= 400) throw new IssueApiError(`GitHub refused ${what} of ${repository} with the status ${String(answer.status)}.`, answer.status);\n return answer;\n };\n const issueAnswer = (answer: RestAnswer, what: string): BoardIssue => {\n const issue = issueOfItem(answer.body);\n if (issue === undefined) throw new IssueApiError(`GitHub gave no issue for ${what} of ${repository}.`, answer.status);\n return issue;\n };\n return {\n async issues() {\n const issues: BoardIssue[] = [];\n for (let page = 1; page <= MAX_PAGES; page += 1) {\n const query = { labels: TARGET_LABEL, state: \"all\", per_page: String(PAGE), page: String(page) };\n const items = readArray((await send({ method: \"GET\", path: `${base}/issues`, query }, \"the list of issues\")).body, (item) => item) ?? [];\n issues.push(...items.flatMap((item) => issueOfItem(item) ?? []));\n if (items.length < PAGE) break;\n }\n const claimed: BoardIssue[] = [];\n for (const issue of issues) {\n if (issue.state !== \"open\" || issue.assignees.length === 0) {\n claimed.push(issue);\n continue;\n }\n const events = await send({ method: \"GET\", path: `${base}/issues/${String(issue.number)}/events`, query: { per_page: String(PAGE) } }, \"the events of an issue\");\n claimed.push({ ...issue, claimedAt: claimTimeOf(events.body, issue.assignees) });\n }\n return claimed;\n },\n async hasOpenPull(targetId) {\n const answer = await send({ method: \"GET\", path: \"/search/issues\", query: { q: `\"${targetId}\" type:pr state:open`, per_page: String(PAGE) } }, \"a search of pull requests\");\n const items = arrayOf(answer.body, \"items\", (item) => textOf(item, \"body\")) ?? [];\n return items.some((body) => body.includes(targetId));\n },\n async ensureLabels(names) {\n const answer = await send({ method: \"GET\", path: `${base}/labels`, query: { per_page: String(PAGE) } }, \"the list of labels\");\n const have = new Set(readArray(answer.body, (label) => textOf(label, \"name\")) ?? []);\n for (const name of names.filter((label) => !have.has(label))) {\n const color = name === TARGET_LABEL ? LABEL_COLOR.target : LABEL_COLOR.gap;\n await send({ method: \"POST\", path: `${base}/labels`, body: { name, color } }, \"a new label\");\n }\n },\n async create(text: IssueText) {\n const answer = await send({ method: \"POST\", path: `${base}/issues`, body: { title: text.title, body: text.body, labels: text.labels } }, \"a new issue\");\n return issueAnswer(answer, \"a new issue\").number;\n },\n async update(number, change) {\n return issueAnswer(await send({ method: \"PATCH\", path: `${base}/issues/${String(number)}`, body: patchOf(change) }, \"a change of an issue\"), \"a change of an issue\");\n },\n async comment(number, text) {\n await send({ method: \"POST\", path: `${base}/issues/${String(number)}/comments`, body: { body: text } }, \"a comment\");\n },\n };\n}\n"],"ignoreList":[8],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAa,YAAY;;AAGzB,MAAa,kBAAkB;;AAG/B,MAAa,eAAe;;AAG5B,MAAa,cAAsB;AAiDnC,MAAM,SAAS;;;;;AAMf,SAAS,OAAO,OAAgB,YAAY,OAA8B;CACxE,MAAM,OAAO,OAAO,OAAO,MAAM;CACjC,MAAM,OAAO,OAAO,OAAO,MAAM;CACjC,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,MAAM,OAAO,OAAO,OAAO,MAAM;CACjC,IAAI,SAAS,KAAA,KAAa,SAAS,KAAA,KAAa,SAAS,KAAA,KAAa,SAAS,KAAA,GAAW,OAAO,KAAA;CACjG,IAAI,UAAU,OAAO,MAAM,MAAM,SAAS,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,SAAS,IAAI,OAAO,KAAA;CACrG,IAAI,KAAK,WAAW,GAAG,MAAM,CAAC,aAAa,SAAS,gBAAgB,OAAO,KAAA;CAC3E,OAAO;EAAE;EAAM;EAAM;EAAM;CAAK;AAClC;;AAGA,SAAS,QAAQ,OAAwC;CACvD,MAAM,QAAQ,SAAS,OAAO,OAAO;CACrC,IAAI,UAAU,KAAA,KAAa,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,OAAO,KAAA;CACzE,OAAO;EAAE;EAAO,OAAO,QAAQ,OAAO,SAAS,QAAQ,KAAK,CAAC;EAAG,SAAS,QAAQ,OAAO,YAAY,WAAW,O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