@intentius/chant 0.124.14 → 0.124.16

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.
Files changed (178) hide show
  1. package/dist/build.d.ts +6 -0
  2. package/dist/build.d.ts.map +1 -1
  3. package/dist/build.js +1 -0
  4. package/dist/change-set.d.ts +24 -2
  5. package/dist/change-set.d.ts.map +1 -1
  6. package/dist/change-set.js +50 -1
  7. package/dist/ci-jobs.d.ts +227 -0
  8. package/dist/ci-jobs.d.ts.map +1 -0
  9. package/dist/ci-jobs.js +448 -0
  10. package/dist/cli/flush.d.ts +16 -0
  11. package/dist/cli/flush.d.ts.map +1 -0
  12. package/dist/cli/flush.js +42 -0
  13. package/dist/cli/handlers/approve.d.ts +98 -0
  14. package/dist/cli/handlers/approve.d.ts.map +1 -0
  15. package/dist/cli/handlers/approve.js +495 -0
  16. package/dist/cli/handlers/operator.d.ts +1 -95
  17. package/dist/cli/handlers/operator.d.ts.map +1 -1
  18. package/dist/cli/handlers/operator.js +4 -488
  19. package/dist/cli/handlers/override-approve.js +1 -1
  20. package/dist/cli/main.d.ts +4 -15
  21. package/dist/cli/main.d.ts.map +1 -1
  22. package/dist/cli/main.js +4 -1062
  23. package/dist/cli/parse-args.d.ts +6 -0
  24. package/dist/cli/parse-args.d.ts.map +1 -0
  25. package/dist/cli/parse-args.js +1028 -0
  26. package/dist/components/fan-out-record.d.ts +1 -1
  27. package/dist/components/fan-out-record.d.ts.map +1 -1
  28. package/dist/components/fan-out-record.js +3 -7
  29. package/dist/components/fan-out-run.d.ts +5 -3
  30. package/dist/components/fan-out-run.d.ts.map +1 -1
  31. package/dist/components/fan-out-run.js +7 -5
  32. package/dist/components/pr-pipeline.d.ts.map +1 -1
  33. package/dist/components/pr-pipeline.js +3 -2
  34. package/dist/composite.d.ts +10 -2
  35. package/dist/composite.d.ts.map +1 -1
  36. package/dist/composite.js +8 -0
  37. package/dist/discovery/collect.d.ts +2 -1
  38. package/dist/discovery/collect.d.ts.map +1 -1
  39. package/dist/discovery/collect.js +16 -1
  40. package/dist/discovery/fold-import.d.ts.map +1 -1
  41. package/dist/discovery/fold-import.js +2 -107
  42. package/dist/discovery/host-composite.d.ts +35 -0
  43. package/dist/discovery/host-composite.d.ts.map +1 -0
  44. package/dist/discovery/host-composite.js +93 -0
  45. package/dist/discovery/index.d.ts +9 -0
  46. package/dist/discovery/index.d.ts.map +1 -1
  47. package/dist/discovery/index.js +1 -1
  48. package/dist/gate-decision.d.ts +20 -9
  49. package/dist/gate-decision.d.ts.map +1 -1
  50. package/dist/gate-decision.js +72 -19
  51. package/dist/gated-waves.d.ts +25 -6
  52. package/dist/gated-waves.d.ts.map +1 -1
  53. package/dist/gated-waves.js +21 -6
  54. package/dist/lifecycle/gate-audit.d.ts +69 -2
  55. package/dist/lifecycle/gate-audit.d.ts.map +1 -1
  56. package/dist/lifecycle/gate-audit.js +76 -2
  57. package/dist/lifecycle/gate-ledger.d.ts +24 -0
  58. package/dist/lifecycle/gate-ledger.d.ts.map +1 -1
  59. package/dist/lifecycle/gate-ledger.js +9 -1
  60. package/dist/op/activities/activity-contracts.d.ts +5 -5
  61. package/dist/op/activities/activity-contracts.js +1 -1
  62. package/dist/op/activities/change-set.d.ts +8 -3
  63. package/dist/op/activities/change-set.d.ts.map +1 -1
  64. package/dist/op/activities/change-set.js +5 -2
  65. package/dist/op/activities/reconcile.d.ts +28 -16
  66. package/dist/op/activities/reconcile.d.ts.map +1 -1
  67. package/dist/op/activities/reconcile.js +34 -20
  68. package/dist/op/builders.d.ts +1 -1
  69. package/dist/op/builders.d.ts.map +1 -1
  70. package/dist/op/builders.js +1 -1
  71. package/dist/op/op-waves-run.d.ts +2 -2
  72. package/dist/op/op-waves-run.d.ts.map +1 -1
  73. package/dist/op/op-waves-run.js +8 -9
  74. package/dist/op/op-waves.d.ts.map +1 -1
  75. package/dist/op/op-waves.js +4 -8
  76. package/dist/package-version.d.ts +2 -0
  77. package/dist/package-version.d.ts.map +1 -0
  78. package/dist/package-version.js +10 -0
  79. package/dist/wave-engine.d.ts +62 -0
  80. package/dist/wave-engine.d.ts.map +1 -0
  81. package/dist/wave-engine.js +59 -0
  82. package/dist/wave-layout.d.ts +29 -0
  83. package/dist/wave-layout.d.ts.map +1 -0
  84. package/dist/wave-layout.js +41 -0
  85. package/dist/wave-runtime.d.ts +29 -0
  86. package/dist/wave-runtime.d.ts.map +1 -0
  87. package/dist/wave-runtime.js +103 -0
  88. package/dist/wave-runtime.mjs +331 -0
  89. package/dist/workspace/__fixtures__/contract-repo.d.ts +7 -0
  90. package/dist/workspace/__fixtures__/contract-repo.d.ts.map +1 -1
  91. package/dist/workspace/__fixtures__/contract-repo.js +17 -1
  92. package/dist/workspace/__fixtures__/sessions.d.ts +1 -1
  93. package/dist/workspace/__fixtures__/sessions.d.ts.map +1 -1
  94. package/dist/workspace/__fixtures__/sessions.js +3 -3
  95. package/dist/workspace/ajv2020.d.ts +5 -0
  96. package/dist/workspace/ajv2020.d.ts.map +1 -0
  97. package/dist/workspace/ajv2020.js +14 -0
  98. package/dist/workspace/change-set.schema.json +5 -3
  99. package/dist/workspace/ci-green-workflow.d.ts +3 -1
  100. package/dist/workspace/ci-green-workflow.d.ts.map +1 -1
  101. package/dist/workspace/ci-green-workflow.js +5 -2
  102. package/dist/workspace/class-data.d.ts +84 -0
  103. package/dist/workspace/class-data.d.ts.map +1 -0
  104. package/dist/workspace/class-data.js +238 -0
  105. package/dist/workspace/declaration.d.ts.map +1 -1
  106. package/dist/workspace/declaration.js +4 -8
  107. package/dist/workspace/kinds.d.ts +3 -7
  108. package/dist/workspace/kinds.d.ts.map +1 -1
  109. package/dist/workspace/kinds.js +8 -45
  110. package/dist/workspace/points.d.ts.map +1 -1
  111. package/dist/workspace/points.js +2 -5
  112. package/dist/workspace/principal-classes.d.ts +4 -11
  113. package/dist/workspace/principal-classes.d.ts.map +1 -1
  114. package/dist/workspace/principal-classes.js +13 -99
  115. package/package.json +5 -3
  116. package/src/build.ts +8 -0
  117. package/src/change-set.test.ts +48 -0
  118. package/src/change-set.ts +52 -2
  119. package/src/ci-jobs.test.ts +49 -0
  120. package/src/ci-jobs.ts +515 -0
  121. package/src/cli/flush.ts +44 -0
  122. package/src/cli/handlers/approve.ts +618 -0
  123. package/src/cli/handlers/operator.ts +10 -608
  124. package/src/cli/handlers/override-approve.test.ts +1 -1
  125. package/src/cli/handlers/override-approve.ts +1 -1
  126. package/src/cli/main.ts +5 -816
  127. package/src/cli/parse-args.ts +781 -0
  128. package/src/components/fan-out-record.ts +3 -7
  129. package/src/components/fan-out-run.ts +7 -5
  130. package/src/components/pr-pipeline.ts +3 -2
  131. package/src/composite.ts +15 -3
  132. package/src/discovery/collect.ts +15 -1
  133. package/src/discovery/fold-build-parity.test.ts +71 -0
  134. package/src/discovery/fold-import.ts +2 -113
  135. package/src/discovery/fold-project-provenance.test.ts +21 -4
  136. package/src/discovery/host-composite.ts +101 -0
  137. package/src/discovery/index.ts +11 -1
  138. package/src/gate-decision-bundle.test.ts +6 -4
  139. package/src/gate-decision-identity.test.ts +59 -6
  140. package/src/gate-decision.ts +81 -21
  141. package/src/gated-waves.ts +28 -6
  142. package/src/lifecycle/gate-audit.test.ts +55 -1
  143. package/src/lifecycle/gate-audit.ts +116 -3
  144. package/src/lifecycle/gate-ledger.test.ts +20 -1
  145. package/src/lifecycle/gate-ledger.ts +33 -1
  146. package/src/op/activities/activity-contracts.ts +1 -1
  147. package/src/op/activities/change-set.ts +11 -3
  148. package/src/op/activities/lexicon-upgrade.test.ts +2 -0
  149. package/src/op/activities/reconcile.test.ts +62 -2
  150. package/src/op/activities/reconcile.ts +46 -22
  151. package/src/op/builders.ts +1 -1
  152. package/src/op/op-waves-run.ts +9 -9
  153. package/src/op/op-waves.test.ts +2 -0
  154. package/src/op/op-waves.ts +4 -8
  155. package/src/op/work-lease-run.test.ts +12 -4
  156. package/src/package-version.ts +11 -0
  157. package/src/wave-engine.test.ts +107 -0
  158. package/src/wave-engine.ts +98 -0
  159. package/src/wave-layout.ts +44 -0
  160. package/src/wave-runtime-bundle.test.ts +70 -0
  161. package/src/wave-runtime.e2e.test.ts +177 -0
  162. package/src/wave-runtime.ts +104 -0
  163. package/src/workspace/__fixtures__/contract-repo.ts +17 -1
  164. package/src/workspace/__fixtures__/sessions.ts +3 -3
  165. package/src/workspace/ajv2020.ts +17 -0
  166. package/src/workspace/change-set.schema.json +5 -3
  167. package/src/workspace/ci-green-workflow.test.ts +4 -4
  168. package/src/workspace/ci-green-workflow.ts +5 -2
  169. package/src/workspace/class-data.test.ts +64 -0
  170. package/src/workspace/class-data.ts +236 -0
  171. package/src/workspace/declaration.ts +4 -10
  172. package/src/workspace/kinds.ts +8 -40
  173. package/src/workspace/points.ts +2 -5
  174. package/src/workspace/principal-classes.ts +13 -99
  175. package/src/workspace/records-formats.test.ts +7 -2
  176. package/src/workspace/records-sessions-write.test.ts +3 -3
  177. package/src/workspace/status-contract.e2e.test.ts +37 -0
  178. package/src/workspace/status-contract.test.ts +23 -21
@@ -0,0 +1,64 @@
1
+ /**
2
+ * #3888: the principals file read by hand, for the gate-decision bundle,
3
+ * accepts and refuses what chant's ajv-checked `parseClassData` does.
4
+ */
5
+
6
+ import { describe, expect, test } from "vitest";
7
+ import { classDataShapeProblems, parseClassDataByHand } from "./class-data";
8
+ import { parseClassData } from "./principal-classes";
9
+
10
+ const ok = { name: "operator", description: "people who apply infrastructure", role: "ops" };
11
+
12
+ const FILES: unknown[] = [
13
+ { schema: 1, classes: [ok] },
14
+ { $schema: "x", $comment: "y", "x-note": 3, schema: 1, classes: [{ ...ok, "x-extra": true }] },
15
+ { schema: 1, classes: [ok, { name: "reviewer", description: "r", role: "reviewer" }] },
16
+ { schema: 1, classes: [ok, { ...ok, role: "other" }] },
17
+ { schema: 1, classes: [{ ...ok, name: "agent" }] },
18
+ { schema: 1, classes: [{ ...ok, role: "runner" }] },
19
+ { schema: 1, classes: [ok, { ...ok, name: "other" }] },
20
+ { schema: 2, classes: [ok] },
21
+ { schema: "1", classes: [ok] },
22
+ { classes: [ok] },
23
+ { schema: 1 },
24
+ { schema: 1, classes: [] },
25
+ { schema: 1, classes: {} },
26
+ { schema: 1, classes: [ok], extra: 1 },
27
+ { $schema: 3, schema: 1, classes: [ok] },
28
+ { $comment: null, schema: 1, classes: [ok] },
29
+ { schema: 1, classes: [{ ...ok, other: 1 }] },
30
+ { schema: 1, classes: [{ name: ok.name, role: ok.role }] },
31
+ { schema: 1, classes: [{ name: ok.name, description: ok.description }] },
32
+ { schema: 1, classes: [{ description: ok.description, role: ok.role }] },
33
+ { schema: 1, classes: [{ ...ok, name: "Operator" }] },
34
+ { schema: 1, classes: [{ ...ok, name: "x-operator" }] },
35
+ { schema: 1, classes: [{ ...ok, name: "a".repeat(40) }] },
36
+ { schema: 1, classes: [{ ...ok, name: "a".repeat(41) }] },
37
+ { schema: 1, classes: [{ ...ok, name: "1op" }] },
38
+ { schema: 1, classes: [{ ...ok, name: 7 }] },
39
+ { schema: 1, classes: [{ ...ok, description: "" }] },
40
+ { schema: 1, classes: [{ ...ok, description: 1 }] },
41
+ { schema: 1, classes: [{ ...ok, role: "Ops" }] },
42
+ { schema: 1, classes: [{ ...ok, role: "ops role" }] },
43
+ { schema: 1, classes: [{ ...ok, role: "op-s2" }] },
44
+ { schema: 1, classes: [null] },
45
+ { schema: 1, classes: ["operator"] },
46
+ [],
47
+ null,
48
+ "text",
49
+ ];
50
+
51
+ describe("the principals file read without ajv", () => {
52
+ test.each(FILES.map((f) => [JSON.stringify(f), f]))("%s reads to the classes ajv's check gives", (_, file) => {
53
+ const text = JSON.stringify(file);
54
+ const byAjv = parseClassData(text, "@acme/p");
55
+ const byHand = parseClassDataByHand(text, "@acme/p");
56
+ expect(byHand.classes).toEqual(byAjv.classes);
57
+ expect(byHand.problems.length > 0).toBe(byAjv.problems.length > 0);
58
+ expect(classDataShapeProblems(file, "@acme/p").length === 0).toBe(byAjv.classes.length > 0 || byAjv.problems.every((p) => /core|twice|another class/.test(p)));
59
+ });
60
+
61
+ test("text that is not JSON", () => {
62
+ expect(parseClassDataByHand("{", "@acme/p")).toEqual(parseClassData("{", "@acme/p"));
63
+ });
64
+ });
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Reading the principal classes a pinned package supplies, without ajv or
3
+ * any package code (#3888).
4
+ *
5
+ * `./principal-classes.ts` reads a package's `./workspace-principals` file
6
+ * for chant, validating it with ajv against
7
+ * `workspace-principals.schema.json`. `@intentius/chant/gate-decision` reads
8
+ * the same files from a bare clone and must bundle without ajv, so the rules
9
+ * both share live here: where a package's export points, where an installed
10
+ * package is, what a file must hold beyond its schema, and how classes from
11
+ * several pins merge. {@link classDataShapeProblems} is the schema written
12
+ * out by hand for the bundle; `class-data.test.ts` holds it to ajv's answer.
13
+ *
14
+ * The module imports node:fs and node:path and nothing else.
15
+ */
16
+
17
+ import { existsSync, readFileSync, statSync } from "node:fs";
18
+ import { dirname, join, posix, resolve } from "node:path";
19
+ import { CORE_CLASSES, CORE_PRINCIPAL_CLASSES, type PrincipalClass } from "./identity-gate-rule";
20
+
21
+ /** The subpath a package publishes its principal classes at. */
22
+ export const PRINCIPALS_SUBPATH = "./workspace-principals";
23
+
24
+ export interface ClassData {
25
+ classes: PrincipalClass[];
26
+ /** Why some of the data can't be used, one line each. Empty when all of it can. */
27
+ problems: string[];
28
+ }
29
+
30
+ /** A package's files, by a `/`-separated path inside it, or undefined when one is not there. */
31
+ export type PackageFiles = (path: string) => string | undefined;
32
+
33
+ /** A package directory on disk. */
34
+ export function diskFiles(dir: string): PackageFiles {
35
+ return (path) => {
36
+ try {
37
+ return readFileSync(join(dir, ...path.split("/")), "utf-8");
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ };
42
+ }
43
+
44
+ /**
45
+ * The directory of an installed package `name`, found the way Node finds a
46
+ * bare import: `node_modules/<name>` in `fromDir` and each directory above it.
47
+ * It looks for the directory, not for an entry point, so it works for a
48
+ * package whose `exports` don't expose `package.json`.
49
+ */
50
+ export function findInstalledPackage(name: string, fromDir: string): string | undefined {
51
+ for (let dir = resolve(fromDir); ; dir = dirname(dir)) {
52
+ const candidate = join(dir, "node_modules", ...name.split("/"));
53
+ try {
54
+ if (statSync(candidate).isDirectory() && existsSync(join(candidate, "package.json"))) return candidate;
55
+ } catch {
56
+ // Not here; keep walking.
57
+ }
58
+ if (dirname(dir) === dir) return undefined;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * The file a package's `exports[subpath]` names: undefined when it names
64
+ * none, a problem when it is not one `.json` file inside the package.
65
+ */
66
+ export function dataExportTarget(pkg: Record<string, unknown>, subpath: string): string | undefined | { problem: string } {
67
+ const exports = pkg.exports;
68
+ if (!exports || typeof exports !== "object" || Array.isArray(exports)) return undefined;
69
+ const entry = (exports as Record<string, unknown>)[subpath];
70
+ if (entry === undefined) return undefined;
71
+ let target: unknown = entry;
72
+ if (target && typeof target === "object" && !Array.isArray(target)) {
73
+ const conditions = target as Record<string, unknown>;
74
+ target = conditions.default ?? conditions.import ?? conditions.require;
75
+ }
76
+ if (typeof target !== "string") {
77
+ return { problem: `exports["${subpath}"] must name one file, as a string or a "default" condition` };
78
+ }
79
+ if (!target.startsWith("./") || !target.endsWith(".json")) {
80
+ return { problem: `exports["${subpath}"] is ${target}; it must name a .json file inside the package, since chant reads plugin data as data and never runs a package's code` };
81
+ }
82
+ return target;
83
+ }
84
+
85
+ // ── The file ─────────────────────────────────────────────────────────────────
86
+
87
+ const NAME = /^(?!x-)[a-z][a-z0-9-]{0,39}$/u;
88
+ const ROLE = /^[a-z][a-z0-9-]*$/u;
89
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
90
+ const extra = (key: string, known: readonly string[]) => !known.includes(key) && !key.startsWith("x-");
91
+
92
+ /**
93
+ * What `workspace-principals.schema.json` refuses in `raw`, one line each,
94
+ * written out by hand so the gate-decision bundle needs no ajv. Empty when
95
+ * the schema accepts it.
96
+ */
97
+ export function classDataShapeProblems(raw: unknown, source: string): string[] {
98
+ const p: string[] = [];
99
+ const say = (where: string, what: string) => p.push(`${source}: ${where || "the principals file"} ${what}`);
100
+ if (!isObject(raw)) {
101
+ say("", "must be object");
102
+ return p;
103
+ }
104
+ for (const key of Object.keys(raw)) if (extra(key, ["$schema", "$comment", "schema", "classes"])) say("", `must NOT have additional property ${key}`);
105
+ for (const key of ["$schema", "$comment"]) if (key in raw && typeof raw[key] !== "string") say(`/${key}`, "must be string");
106
+ if (!("schema" in raw)) say("", "must have required property 'schema'");
107
+ else if (raw.schema !== 1) say("/schema", "must be equal to constant 1");
108
+ if (!("classes" in raw)) say("", "must have required property 'classes'");
109
+ else if (!Array.isArray(raw.classes)) say("/classes", "must be array");
110
+ else {
111
+ if (raw.classes.length < 1) say("/classes", "must NOT have fewer than 1 items");
112
+ raw.classes.forEach((c: unknown, i: number) => {
113
+ const at = `/classes/${i}`;
114
+ if (!isObject(c)) return say(at, "must be object");
115
+ for (const key of Object.keys(c)) if (extra(key, ["name", "description", "role"])) say(at, `must NOT have additional property ${key}`);
116
+ for (const key of ["name", "description", "role"]) if (!(key in c)) say(at, `must have required property '${key}'`);
117
+ if ("name" in c && (typeof c.name !== "string" || !NAME.test(c.name))) say(`${at}/name`, "must be a class name");
118
+ if ("description" in c && (typeof c.description !== "string" || [...c.description].length < 1)) say(`${at}/description`, "must be a non-empty string");
119
+ if ("role" in c && (typeof c.role !== "string" || !ROLE.test(c.role))) say(`${at}/role`, "must be a role name");
120
+ });
121
+ }
122
+ return [...new Set(p)];
123
+ }
124
+
125
+ const CORE_ROLES = new Set(CORE_CLASSES.map((c) => c.role).filter((r): r is string => r !== null));
126
+
127
+ /**
128
+ * The classes in a principals file the schema accepts, under the rules the
129
+ * schema can't say: no core name or core role, and no name or role twice.
130
+ * `source` names the pin in the classes and in the messages.
131
+ */
132
+ export function checkClassData(valid: { classes: { name: string; description: string; role: string }[] }, source: string): ClassData {
133
+ const problems: string[] = [];
134
+ const classes: PrincipalClass[] = [];
135
+ const names = new Set<string>();
136
+ const roles = new Set<string>();
137
+ for (const c of valid.classes) {
138
+ if ((CORE_PRINCIPAL_CLASSES as readonly string[]).includes(c.name)) {
139
+ problems.push(`${source}: class ${c.name} is a core class and can't be supplied by a package`);
140
+ continue;
141
+ }
142
+ if (CORE_ROLES.has(c.role)) {
143
+ problems.push(`${source}: class ${c.name} names the role ${c.role}, which puts a principal in the core ${c.role} class`);
144
+ continue;
145
+ }
146
+ if (names.has(c.name)) {
147
+ problems.push(`${source}: class ${c.name} is listed twice`);
148
+ continue;
149
+ }
150
+ if (roles.has(c.role)) {
151
+ problems.push(`${source}: class ${c.name} names the role ${c.role}, which another class in the file names; a role puts a principal in one class`);
152
+ continue;
153
+ }
154
+ names.add(c.name);
155
+ roles.add(c.role);
156
+ classes.push({ name: c.name, description: c.description, role: c.role, source });
157
+ }
158
+ return { classes, problems };
159
+ }
160
+
161
+ /** A principals file's text read with {@link classDataShapeProblems} for the schema: what chant's ajv-checked `parseClassData` reads, by the same rules. */
162
+ export function parseClassDataByHand(text: string, source: string): ClassData {
163
+ let raw: unknown;
164
+ try {
165
+ raw = JSON.parse(text);
166
+ } catch (err) {
167
+ return { classes: [], problems: [`${source}: the principals file is not JSON (${(err as Error).message})`] };
168
+ }
169
+ const problems = classDataShapeProblems(raw, source);
170
+ return problems.length > 0 ? { classes: [], problems } : checkClassData(raw as Parameters<typeof checkClassData>[0], source);
171
+ }
172
+
173
+ /** Read the classes a package publishes at `./workspace-principals` through `files`, checking the file with `parse`. Imports nothing. A package that publishes none supplies none. */
174
+ export function readClassFiles(files: PackageFiles, source: string, parse: (text: string, source: string) => ClassData): ClassData {
175
+ const manifest = files("package.json");
176
+ if (manifest === undefined) return { classes: [], problems: [`${source}: no readable package.json`] };
177
+ let pkg: Record<string, unknown>;
178
+ try {
179
+ pkg = JSON.parse(manifest) as Record<string, unknown>;
180
+ } catch {
181
+ return { classes: [], problems: [`${source}: package.json is not JSON`] };
182
+ }
183
+ const target = dataExportTarget(pkg, PRINCIPALS_SUBPATH);
184
+ if (target === undefined) return { classes: [], problems: [] };
185
+ if (typeof target !== "string") return { classes: [], problems: [`${source}: ${target.problem}`] };
186
+ const inside = posix.normalize(target.slice(2));
187
+ if (inside.startsWith("../") || inside === "..") return { classes: [], problems: [`${source}: exports["${PRINCIPALS_SUBPATH}"] points outside the package`] };
188
+ const text = files(inside);
189
+ if (text === undefined) return { classes: [], problems: [`${source}: exports["${PRINCIPALS_SUBPATH}"] names ${target}, which does not exist`] };
190
+ return parse(text, source);
191
+ }
192
+
193
+ /** One pin's classes, as read. */
194
+ export interface PinClassRead {
195
+ /** The pin's index in the declaration's `pins`. */
196
+ pin: number;
197
+ source: string;
198
+ read: ClassData;
199
+ }
200
+
201
+ /**
202
+ * The domain classes of every pin, in pin order and file order. A class
203
+ * name, or a role, two pins both supply is a problem, and every class
204
+ * involved is left out, so a rule naming it reads it as unknown and fails
205
+ * closed.
206
+ */
207
+ export function mergePinClasses(reads: readonly PinClassRead[]): { classes: PrincipalClass[]; problems: { pin: number; message: string }[] } {
208
+ const problems: { pin: number; message: string }[] = [];
209
+ const extra: PrincipalClass[] = [];
210
+ const byName = new Map<string, string>();
211
+ const byRole = new Map<string, string>();
212
+ const clashing = new Set<string>();
213
+ for (const { pin: i, source, read } of reads) {
214
+ for (const p of read.problems) problems.push({ pin: i, message: p });
215
+ for (const c of read.classes) {
216
+ const named = byName.get(c.name);
217
+ const roled = byRole.get(c.role!);
218
+ if (named !== undefined || roled !== undefined) {
219
+ clashing.add(c.name);
220
+ if (named !== undefined) {
221
+ problems.push({ pin: i, message: `class ${c.name} is supplied by both ${named} and ${source}; a class name has one source` });
222
+ } else {
223
+ const other = extra.find((e) => e.role === c.role)!;
224
+ clashing.add(other.name);
225
+ problems.push({ pin: i, message: `class ${c.name} (${source}) names the role ${c.role}, which class ${other.name} (${roled}) names; a role puts a principal in one class` });
226
+ }
227
+ continue;
228
+ }
229
+ byName.set(c.name, source);
230
+ byRole.set(c.role!, source);
231
+ extra.push(c);
232
+ }
233
+ }
234
+ // A name or role two pins both supply is left out altogether: neither reading is safe.
235
+ return { classes: extra.filter((c) => !clashing.has(c.name)), problems };
236
+ }
@@ -16,15 +16,14 @@
16
16
  * runs. The level-0 goldens (#2526) fail if a level-0 command loads it.
17
17
  */
18
18
 
19
- import { readFileSync } from "node:fs";
20
- import { createRequire } from "node:module";
21
- import { fileURLToPath } from "node:url";
22
19
  import schema from "./declaration.schema.json" with { type: "json" };
23
20
  import { expandGlob } from "./glob";
24
21
  import { EXAMPLES_KIND, holdsChantProject } from "./kinds";
25
22
  import { parseJsonText, pointerToken, type TextLocation } from "./jsonc";
26
23
  import type { ReasonCode } from "./reason-codes";
27
24
  import { joinPath, type WorkspaceTree } from "./tree";
25
+ import { loadAjv2020 } from "./ajv2020";
26
+ import { readChantPackageVersion } from "../package-version";
28
27
 
29
28
  export const DECLARATION_SCHEMA_ID = schema.$id;
30
29
  export const DECLARATION_FILES = ["chant.workspace.json", "chant.workspace.jsonc"] as const;
@@ -601,9 +600,7 @@ let readerVersionCache: string | undefined;
601
600
  * well under a millisecond.
602
601
  */
603
602
  export function readerVersion(): string {
604
- readerVersionCache ??= (
605
- JSON.parse(readFileSync(fileURLToPath(new URL("../../package.json", import.meta.url)), "utf-8")) as { version: string }
606
- ).version;
603
+ readerVersionCache ??= readChantPackageVersion();
607
604
  return readerVersionCache;
608
605
  }
609
606
 
@@ -638,10 +635,7 @@ type Validate = ((data: unknown) => boolean) & { errors?: AjvError[] | null };
638
635
  let compiled: Validate | undefined;
639
636
  function validator(): Validate {
640
637
  if (compiled) return compiled;
641
- const require = createRequire(import.meta.url);
642
- // ajv is CommonJS; its class is the default export, or that export's own default.
643
- const mod = require("ajv/dist/2020") as { default?: unknown };
644
- const Ajv = (mod.default ?? mod) as new (opts: object) => { compile(s: object): Validate };
638
+ const Ajv = loadAjv2020() as new (opts: object) => { compile(s: object): Validate };
645
639
  compiled = new Ajv({ allErrors: true, strict: true }).compile(schema);
646
640
  return compiled;
647
641
  }
@@ -17,13 +17,14 @@
17
17
  * fails ({@link resolveKind}).
18
18
  */
19
19
 
20
- import { existsSync, readFileSync, statSync } from "node:fs";
21
- import { createRequire } from "node:module";
22
- import { dirname, isAbsolute, join, relative, resolve } from "node:path";
20
+ import { readFileSync } from "node:fs";
21
+ import { isAbsolute, join, relative, resolve } from "node:path";
23
22
  import schema from "./workspace-kinds.schema.json" with { type: "json" };
24
23
  import type { WorkspaceTree } from "./tree";
25
24
  import { joinPath, skippedDir } from "./tree";
26
25
  import { checkPinIntegrity } from "./pin-integrity";
26
+ import { dataExportTarget, findInstalledPackage } from "./class-data";
27
+ import { loadAjv2020 } from "./ajv2020";
27
28
 
28
29
  export const KINDS_SCHEMA_ID = schema.$id;
29
30
 
@@ -352,10 +353,7 @@ type Validate = ((data: unknown) => boolean) & { errors?: AjvError[] | null };
352
353
  let compiled: Validate | undefined;
353
354
  function validator(): Validate {
354
355
  if (compiled) return compiled;
355
- const require = createRequire(import.meta.url);
356
- // ajv is CommonJS; its class is the default export, or that export's own default.
357
- const mod = require("ajv/dist/2020") as { default?: unknown };
358
- const Ajv = (mod.default ?? mod) as new (opts: object) => { compile(s: object): Validate };
356
+ const Ajv = loadAjv2020() as new (opts: object) => { compile(s: object): Validate };
359
357
  compiled = new Ajv({ allErrors: true, strict: true }).compile(schema);
360
358
  return compiled;
361
359
  }
@@ -428,22 +426,7 @@ export interface PackageKinds extends KindData {
428
426
  * subpath to code, which chant never runs for plugin data.
429
427
  */
430
428
  export function kindsExportTarget(pkg: Record<string, unknown>, subpath: string = KINDS_SUBPATH): string | undefined | { problem: string } {
431
- const exports = pkg.exports;
432
- if (!exports || typeof exports !== "object" || Array.isArray(exports)) return undefined;
433
- const entry = (exports as Record<string, unknown>)[subpath];
434
- if (entry === undefined) return undefined;
435
- let target: unknown = entry;
436
- if (target && typeof target === "object" && !Array.isArray(target)) {
437
- const conditions = target as Record<string, unknown>;
438
- target = conditions.default ?? conditions.import ?? conditions.require;
439
- }
440
- if (typeof target !== "string") {
441
- return { problem: `exports["${subpath}"] must name one file, as a string or a "default" condition` };
442
- }
443
- if (!target.startsWith("./") || !target.endsWith(".json")) {
444
- return { problem: `exports["${subpath}"] is ${target}; it must name a .json file inside the package, since chant reads plugin data as data and never runs a package's code` };
445
- }
446
- return target;
429
+ return dataExportTarget(pkg, subpath);
447
430
  }
448
431
 
449
432
  /** Read the kinds a package directory publishes. Reads files only; imports nothing. */
@@ -515,23 +498,8 @@ export function substituteGraphConfig(config: Record<string, unknown>, at: Graph
515
498
  return walk(config) as Record<string, unknown>;
516
499
  }
517
500
 
518
- /**
519
- * The directory of an installed package `name`, found the way Node finds a
520
- * bare import: `node_modules/<name>` in `fromDir` and each directory above it.
521
- * It looks for the directory, not for an entry point, so it works for a
522
- * package whose `exports` don't expose `package.json`.
523
- */
524
- export function findInstalledPackage(name: string, fromDir: string): string | undefined {
525
- for (let dir = resolve(fromDir); ; dir = dirname(dir)) {
526
- const candidate = join(dir, "node_modules", ...name.split("/"));
527
- try {
528
- if (statSync(candidate).isDirectory() && existsSync(join(candidate, "package.json"))) return candidate;
529
- } catch {
530
- // Not here; keep walking.
531
- }
532
- if (dirname(dir) === dir) return undefined;
533
- }
534
- }
501
+ /** Where an installed package is, as Node finds a bare import (`./class-data.ts`, so the gate-decision bundle shares it). */
502
+ export { findInstalledPackage };
535
503
 
536
504
  export interface PinLike {
537
505
  package: string | null;
@@ -33,12 +33,12 @@
33
33
  */
34
34
 
35
35
  import { createHash } from "node:crypto";
36
- import { createRequire } from "node:module";
37
36
  import { dirname, posix, relative, resolve, sep } from "node:path";
38
37
  import schema from "./decision-points.schema.json" with { type: "json" };
39
38
  import type { ReasonCode } from "./reason-codes";
40
39
  import type { RecordSource } from "./record-source";
41
40
  import type { LoadedRecordKind, ReadRecordsOptions, RecordEntry } from "./records";
41
+ import { loadAjv2020 } from "./ajv2020";
42
42
 
43
43
  export const DECISION_POINTS_SCHEMA_ID = schema.$id;
44
44
 
@@ -200,10 +200,7 @@ type Validate = ((data: unknown) => boolean) & { errors?: AjvError[] | null };
200
200
  let compiled: Validate | undefined;
201
201
  function validator(): Validate {
202
202
  if (compiled) return compiled;
203
- const require = createRequire(import.meta.url);
204
- // ajv is CommonJS; its class is the default export, or that export's own default.
205
- const mod = require("ajv/dist/2020") as { default?: unknown };
206
- const Ajv = (mod.default ?? mod) as new (opts: object) => { compile(s: object): Validate };
203
+ const Ajv = loadAjv2020() as new (opts: object) => { compile(s: object): Validate };
207
204
  compiled = new Ajv({ allErrors: true, strict: false }).compile(schema);
208
205
  return compiled;
209
206
  }
@@ -22,19 +22,17 @@
22
22
  * installed package, which must be at the version the base pins.
23
23
  */
24
24
 
25
- import { readFileSync } from "node:fs";
26
- import { createRequire } from "node:module";
27
- import { join, posix } from "node:path";
28
- import { kindsExportTarget, pinnedPackageDir, type KindLoadProblem, type PinLike } from "./kinds";
25
+ import { checkClassData, diskFiles, mergePinClasses, readClassFiles, type ClassData, type PackageFiles, type PinClassRead } from "./class-data";
26
+ import { pinnedPackageDir, type KindLoadProblem, type PinLike } from "./kinds";
29
27
  import schema from "./workspace-principals.schema.json" with { type: "json" };
30
28
  import type { TrustPolicy } from "./trust/policy";
31
29
  import { joinPath, type WorkspaceTree } from "./tree";
32
30
  import { CORE_CLASSES, CORE_PRINCIPAL_CLASSES, grantedClasses, type PrincipalClass } from "./identity-gate-rule";
31
+ import { loadAjv2020 } from "./ajv2020";
33
32
 
34
33
  export const PRINCIPALS_SCHEMA_ID = schema.$id;
35
34
 
36
- /** The subpath a package publishes its principal classes at. */
37
- export const PRINCIPALS_SUBPATH = "./workspace-principals";
35
+ export { PRINCIPALS_SUBPATH } from "./class-data";
38
36
 
39
37
  export { CORE_CLASSES, CORE_PRINCIPAL_CLASSES, type CorePrincipalClass, type PrincipalClass } from "./identity-gate-rule";
40
38
 
@@ -44,8 +42,6 @@ export type PrincipalClassName = string;
44
42
  /** The grammar of a class name, as `workspace-principals.schema.json` and the declaration's writeScope keys say it. */
45
43
  export const CLASS_NAME = /^(?!x-)[a-z][a-z0-9-]{0,39}$/;
46
44
 
47
- const CORE_ROLES = new Set(CORE_CLASSES.map((c) => c.role).filter((r): r is string => r !== null));
48
-
49
45
  export interface ClassRegistry {
50
46
  get(name: string): PrincipalClass | undefined;
51
47
  /** Every class name, core first, for "unknown class" messages. */
@@ -103,19 +99,13 @@ type Validate = ((data: unknown) => boolean) & { errors?: AjvError[] | null };
103
99
  let compiled: Validate | undefined;
104
100
  function validator(): Validate {
105
101
  if (compiled) return compiled;
106
- const require = createRequire(import.meta.url);
107
- // ajv is CommonJS; its class is the default export, or that export's own default.
108
- const mod = require("ajv/dist/2020") as { default?: unknown };
109
- const Ajv = (mod.default ?? mod) as new (opts: object) => { compile(s: object): Validate };
102
+ const Ajv = loadAjv2020() as new (opts: object) => { compile(s: object): Validate };
110
103
  compiled = new Ajv({ allErrors: true, strict: true }).compile(schema);
111
104
  return compiled;
112
105
  }
113
106
 
114
- export interface ClassData {
115
- classes: PrincipalClass[];
116
- /** Why some of the data can't be used, one line each. Empty when all of it can. */
117
- problems: string[];
118
- }
107
+ export type { ClassData, PackageFiles } from "./class-data";
108
+ export { diskFiles } from "./class-data";
119
109
 
120
110
  /**
121
111
  * Check the text of a principals file against
@@ -135,46 +125,7 @@ export function parseClassData(text: string, source: string): ClassData {
135
125
  const problems = (validate.errors ?? []).map((e) => `${source}: ${e.instancePath || "the principals file"} ${e.message ?? "is invalid"}`);
136
126
  return { classes: [], problems: [...new Set(problems)] };
137
127
  }
138
- const problems: string[] = [];
139
- const classes: PrincipalClass[] = [];
140
- const names = new Set<string>();
141
- const roles = new Set<string>();
142
- for (const c of (raw as { classes: { name: string; description: string; role: string }[] }).classes) {
143
- if ((CORE_PRINCIPAL_CLASSES as readonly string[]).includes(c.name)) {
144
- problems.push(`${source}: class ${c.name} is a core class and can't be supplied by a package`);
145
- continue;
146
- }
147
- if (CORE_ROLES.has(c.role)) {
148
- problems.push(`${source}: class ${c.name} names the role ${c.role}, which puts a principal in the core ${c.role} class`);
149
- continue;
150
- }
151
- if (names.has(c.name)) {
152
- problems.push(`${source}: class ${c.name} is listed twice`);
153
- continue;
154
- }
155
- if (roles.has(c.role)) {
156
- problems.push(`${source}: class ${c.name} names the role ${c.role}, which another class in the file names; a role puts a principal in one class`);
157
- continue;
158
- }
159
- names.add(c.name);
160
- roles.add(c.role);
161
- classes.push({ name: c.name, description: c.description, role: c.role, source });
162
- }
163
- return { classes, problems };
164
- }
165
-
166
- /** A package's files, by a `/`-separated path inside it, or undefined when one is not there. */
167
- export type PackageFiles = (path: string) => string | undefined;
168
-
169
- /** A package directory on disk. */
170
- export function diskFiles(dir: string): PackageFiles {
171
- return (path) => {
172
- try {
173
- return readFileSync(join(dir, ...path.split("/")), "utf-8");
174
- } catch {
175
- return undefined;
176
- }
177
- };
128
+ return checkClassData(raw as Parameters<typeof checkClassData>[0], source);
178
129
  }
179
130
 
180
131
  /** A package directory at `dir` in `tree`, such as the workspace at the base revision. */
@@ -192,22 +143,7 @@ export function treeFiles(tree: WorkspaceTree, dir: string): PackageFiles {
192
143
 
193
144
  /** Read the classes a package publishes at `./workspace-principals`. Reads files only; imports nothing. A package that publishes none supplies none. */
194
145
  export function readPackageClasses(files: PackageFiles, source: string): ClassData {
195
- const manifest = files("package.json");
196
- if (manifest === undefined) return { classes: [], problems: [`${source}: no readable package.json`] };
197
- let pkg: Record<string, unknown>;
198
- try {
199
- pkg = JSON.parse(manifest) as Record<string, unknown>;
200
- } catch {
201
- return { classes: [], problems: [`${source}: package.json is not JSON`] };
202
- }
203
- const target = kindsExportTarget(pkg, PRINCIPALS_SUBPATH);
204
- if (target === undefined) return { classes: [], problems: [] };
205
- if (typeof target !== "string") return { classes: [], problems: [`${source}: ${target.problem}`] };
206
- const inside = posix.normalize(target.slice(2));
207
- if (inside.startsWith("../") || inside === "..") return { classes: [], problems: [`${source}: exports["${PRINCIPALS_SUBPATH}"] points outside the package`] };
208
- const text = files(inside);
209
- if (text === undefined) return { classes: [], problems: [`${source}: exports["${PRINCIPALS_SUBPATH}"] names ${target}, which does not exist`] };
210
- return parseClassData(text, source);
146
+ return readClassFiles(files, source, parseClassData);
211
147
  }
212
148
 
213
149
  export interface LoadedClasses {
@@ -227,10 +163,7 @@ export interface LoadedClasses {
227
163
  */
228
164
  export function loadClassRegistry(pins: readonly PinLike[], workspaceRoot: string, opts: { tree?: WorkspaceTree } = {}): LoadedClasses {
229
165
  const problems: KindLoadProblem[] = [];
230
- const extra: PrincipalClass[] = [];
231
- const byName = new Map<string, string>();
232
- const byRole = new Map<string, string>();
233
- const clashing = new Set<string>();
166
+ const reads: PinClassRead[] = [];
234
167
  pins.forEach((pin, i) => {
235
168
  let files: PackageFiles;
236
169
  let source: string;
@@ -247,29 +180,10 @@ export function loadClassRegistry(pins: readonly PinLike[], workspaceRoot: strin
247
180
  files = diskFiles(found.dir);
248
181
  source = found.source;
249
182
  }
250
- const read = readPackageClasses(files, source);
251
- for (const p of read.problems) problems.push({ pin: i, message: p });
252
- for (const c of read.classes) {
253
- const named = byName.get(c.name);
254
- const roled = byRole.get(c.role!);
255
- if (named !== undefined || roled !== undefined) {
256
- clashing.add(c.name);
257
- if (named !== undefined) {
258
- problems.push({ pin: i, message: `class ${c.name} is supplied by both ${named} and ${source}; a class name has one source` });
259
- } else {
260
- const other = extra.find((e) => e.role === c.role)!;
261
- clashing.add(other.name);
262
- problems.push({ pin: i, message: `class ${c.name} (${source}) names the role ${c.role}, which class ${other.name} (${roled}) names; a role puts a principal in one class` });
263
- }
264
- continue;
265
- }
266
- byName.set(c.name, source);
267
- byRole.set(c.role!, source);
268
- extra.push(c);
269
- }
183
+ reads.push({ pin: i, source, read: readPackageClasses(files, source) });
270
184
  });
271
- // A name or role two pins both supply is left out altogether: neither reading is safe.
272
- return { registry: createClassRegistry(extra.filter((c) => !clashing.has(c.name))), problems };
185
+ const merged = mergePinClasses(reads);
186
+ return { registry: createClassRegistry(merged.classes), problems: [...problems, ...merged.problems].sort((a, b) => a.pin - b.pin) };
273
187
  }
274
188
 
275
189
  /**
@@ -12,7 +12,7 @@
12
12
 
13
13
  import { execFileSync } from "node:child_process";
14
14
  import { createHash } from "node:crypto";
15
- import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
15
+ import { cpSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
16
16
  import { tmpdir } from "node:os";
17
17
  import { dirname, join } from "node:path";
18
18
  import Ajv2020 from "ajv/dist/2020";
@@ -472,7 +472,12 @@ describe("the write commands through a declared kind (#2680)", () => {
472
472
 
473
473
  describe("the decision kind", () => {
474
474
  test("still reads as markdown front matter, and says so", async () => {
475
- const doc = await queryRecords({ kind: "docs/design/decisions/decision.kind.mjs", cwd: REPO });
475
+ // The repository's own decision records, copied into a one-commit repository:
476
+ // a read in the real checkout asks git for the history of every pinned path
477
+ // across thousands of commits, which took 12 s alone and 20+ s under load.
478
+ cpSync(join(REPO, "docs", "design", "decisions"), join(root, "docs", "design", "decisions"), { recursive: true });
479
+ commit();
480
+ const doc = await queryRecords({ kind: "docs/design/decisions/decision.kind.mjs", cwd: root });
476
481
  expect(validateOutput(doc)).toBe(true);
477
482
  if ("error" in doc) throw new Error(doc.error.message);
478
483
  expect(doc.kind.format).toBe("markdown-front-matter");