@ontrails/warden 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/CHANGELOG.md +1556 -0
  2. package/README.md +200 -0
  3. package/bin/warden.ts +51 -0
  4. package/package.json +51 -0
  5. package/src/adapter-check.ts +136 -0
  6. package/src/cli.ts +2159 -0
  7. package/src/command.ts +1167 -0
  8. package/src/config.ts +193 -0
  9. package/src/draft.ts +22 -0
  10. package/src/drift.ts +260 -0
  11. package/src/fix.ts +126 -0
  12. package/src/formatters.ts +178 -0
  13. package/src/guide.ts +245 -0
  14. package/src/index.ts +295 -0
  15. package/src/project-context.ts +446 -0
  16. package/src/project-rules.ts +290 -0
  17. package/src/regrade-history.ts +188 -0
  18. package/src/regrade-receipt.ts +484 -0
  19. package/src/resolve.ts +531 -0
  20. package/src/rules/activation-orphan.ts +97 -0
  21. package/src/rules/captured-kernel.ts +375 -0
  22. package/src/rules/circular-refs.ts +150 -0
  23. package/src/rules/cli-command-route-coherence.ts +177 -0
  24. package/src/rules/composes-declarations.ts +839 -0
  25. package/src/rules/context-no-surface-types.ts +214 -0
  26. package/src/rules/dead-internal-trail.ts +161 -0
  27. package/src/rules/dead-public-trail.ts +258 -0
  28. package/src/rules/draft-file-marking.ts +155 -0
  29. package/src/rules/draft-visible-debt.ts +83 -0
  30. package/src/rules/duplicate-exported-symbol.ts +172 -0
  31. package/src/rules/duplicate-public-contract.ts +137 -0
  32. package/src/rules/entity-exists.ts +254 -0
  33. package/src/rules/entity-ids.ts +15 -0
  34. package/src/rules/error-mapping-completeness.ts +290 -0
  35. package/src/rules/example-valid.ts +395 -0
  36. package/src/rules/fires-declarations.ts +740 -0
  37. package/src/rules/governed-symbol-residue.ts +535 -0
  38. package/src/rules/governed-vocabulary-permutation-watch.ts +77 -0
  39. package/src/rules/implementation-returns-result.ts +1733 -0
  40. package/src/rules/incomplete-accessor-for-standard-op.ts +272 -0
  41. package/src/rules/incomplete-crud.ts +583 -0
  42. package/src/rules/index.ts +328 -0
  43. package/src/rules/intent-propagation.ts +125 -0
  44. package/src/rules/layer-field-name-drift.ts +102 -0
  45. package/src/rules/library-render-coherence.ts +97 -0
  46. package/src/rules/metadata.ts +929 -0
  47. package/src/rules/missing-reconcile.ts +97 -0
  48. package/src/rules/missing-visibility.ts +111 -0
  49. package/src/rules/no-destructured-compose.ts +196 -0
  50. package/src/rules/no-dev-permit-in-source.ts +99 -0
  51. package/src/rules/no-direct-implementation-call.ts +52 -0
  52. package/src/rules/no-legacy-cli-alias-export.ts +247 -0
  53. package/src/rules/no-legacy-layer-imports.ts +211 -0
  54. package/src/rules/no-native-error-result.ts +118 -0
  55. package/src/rules/no-redundant-result-error-wrap.ts +382 -0
  56. package/src/rules/no-retired-cross-vocabulary.ts +203 -0
  57. package/src/rules/no-sync-result-assumption.ts +1199 -0
  58. package/src/rules/no-throw-in-detour-recover.ts +225 -0
  59. package/src/rules/no-throw-in-implementation.ts +48 -0
  60. package/src/rules/no-top-level-surface.ts +371 -0
  61. package/src/rules/on-references-exist.ts +194 -0
  62. package/src/rules/orphaned-signal.ts +149 -0
  63. package/src/rules/owner-render-parity.ts +143 -0
  64. package/src/rules/permit-governance.ts +25 -0
  65. package/src/rules/prefer-schema-inference.ts +141 -0
  66. package/src/rules/public-export-example-coverage.ts +561 -0
  67. package/src/rules/public-internal-deep-imports.ts +454 -0
  68. package/src/rules/public-output-schema.ts +29 -0
  69. package/src/rules/public-union-output-discriminants.ts +150 -0
  70. package/src/rules/read-intent-fires.ts +188 -0
  71. package/src/rules/reference-exists.ts +97 -0
  72. package/src/rules/registry-names.ts +171 -0
  73. package/src/rules/resolved-import-boundary.ts +146 -0
  74. package/src/rules/resource-declarations.ts +697 -0
  75. package/src/rules/resource-exists.ts +181 -0
  76. package/src/rules/resource-id-grammar.ts +65 -0
  77. package/src/rules/resource-mock-coverage.ts +115 -0
  78. package/src/rules/retired-vocabulary.ts +1407 -0
  79. package/src/rules/scan.ts +59 -0
  80. package/src/rules/scheduled-destroy-intent.ts +44 -0
  81. package/src/rules/signal-graph-coaching.ts +220 -0
  82. package/src/rules/source/composition.ts +165 -0
  83. package/src/rules/source/drafts.ts +164 -0
  84. package/src/rules/source/entities.ts +618 -0
  85. package/src/rules/source/pragmas.ts +45 -0
  86. package/src/rules/source/resources.ts +64 -0
  87. package/src/rules/source/signals.ts +397 -0
  88. package/src/rules/source/stores.ts +310 -0
  89. package/src/rules/specs.ts +388 -0
  90. package/src/rules/static-resource-accessor-preference.ts +654 -0
  91. package/src/rules/structure.ts +234 -0
  92. package/src/rules/surface-overlay-coherence.ts +262 -0
  93. package/src/rules/surface-trailhead-coherence.ts +366 -0
  94. package/src/rules/trail-fork-coaching.ts +625 -0
  95. package/src/rules/trail-versioning-source.ts +1076 -0
  96. package/src/rules/trail-versioning-topo.ts +172 -0
  97. package/src/rules/trailhead-override-divergence.ts +356 -0
  98. package/src/rules/types.ts +464 -0
  99. package/src/rules/unmaterialized-activation-source.ts +85 -0
  100. package/src/rules/unreachable-detour-shadowing.ts +343 -0
  101. package/src/rules/valid-describe-refs.ts +224 -0
  102. package/src/rules/valid-detour-contract.ts +78 -0
  103. package/src/rules/warden-export-symmetry.ts +540 -0
  104. package/src/rules/warden-rules-use-ast.ts +1109 -0
  105. package/src/rules/webhook-route-collision.ts +306 -0
  106. package/src/rules/workspace-lock-ownership.ts +34 -0
  107. package/src/trails/activation-orphan.trail.ts +84 -0
  108. package/src/trails/captured-kernel.trail.ts +108 -0
  109. package/src/trails/circular-refs.trail.ts +29 -0
  110. package/src/trails/cli-command-route-coherence.trail.ts +47 -0
  111. package/src/trails/composes-declarations.trail.ts +22 -0
  112. package/src/trails/context-no-surface-types.trail.ts +21 -0
  113. package/src/trails/dead-internal-trail.trail.ts +26 -0
  114. package/src/trails/dead-public-trail.trail.ts +31 -0
  115. package/src/trails/deprecation-without-guidance.trail.ts +21 -0
  116. package/src/trails/draft-file-marking.trail.ts +16 -0
  117. package/src/trails/draft-visible-debt.trail.ts +16 -0
  118. package/src/trails/duplicate-exported-symbol.trail.ts +48 -0
  119. package/src/trails/duplicate-public-contract.trail.ts +47 -0
  120. package/src/trails/entity-exists.trail.ts +21 -0
  121. package/src/trails/error-mapping-completeness.trail.ts +30 -0
  122. package/src/trails/example-valid.trail.ts +25 -0
  123. package/src/trails/fires-declarations.trail.ts +23 -0
  124. package/src/trails/fork-without-preserved-implementation.trail.ts +31 -0
  125. package/src/trails/governed-symbol-residue.trail.ts +24 -0
  126. package/src/trails/governed-vocabulary-permutation-watch.trail.ts +16 -0
  127. package/src/trails/implementation-returns-result.trail.ts +20 -0
  128. package/src/trails/incomplete-accessor-for-standard-op.trail.ts +76 -0
  129. package/src/trails/incomplete-crud.trail.ts +39 -0
  130. package/src/trails/index.ts +91 -0
  131. package/src/trails/intent-propagation.trail.ts +30 -0
  132. package/src/trails/layer-field-name-drift.trail.ts +39 -0
  133. package/src/trails/library-render-coherence.trail.ts +43 -0
  134. package/src/trails/marker-schema-unsupported.trail.ts +23 -0
  135. package/src/trails/missing-reconcile.trail.ts +33 -0
  136. package/src/trails/missing-visibility.trail.ts +22 -0
  137. package/src/trails/no-destructured-compose.trail.ts +44 -0
  138. package/src/trails/no-dev-permit-in-source.trail.ts +16 -0
  139. package/src/trails/no-direct-implementation-call.trail.ts +16 -0
  140. package/src/trails/no-legacy-cli-alias-export.trail.ts +41 -0
  141. package/src/trails/no-legacy-layer-imports.trail.ts +41 -0
  142. package/src/trails/no-native-error-result.trail.ts +18 -0
  143. package/src/trails/no-redundant-result-error-wrap.trail.ts +55 -0
  144. package/src/trails/no-retired-cross-vocabulary.trail.ts +42 -0
  145. package/src/trails/no-sync-result-assumption.trail.ts +19 -0
  146. package/src/trails/no-throw-in-detour-recover.trail.ts +24 -0
  147. package/src/trails/no-throw-in-implementation.trail.ts +20 -0
  148. package/src/trails/no-top-level-surface.trail.ts +43 -0
  149. package/src/trails/on-references-exist.trail.ts +21 -0
  150. package/src/trails/orphaned-signal.trail.ts +36 -0
  151. package/src/trails/owner-render-parity.trail.ts +26 -0
  152. package/src/trails/pending-force.trail.ts +21 -0
  153. package/src/trails/permit-governance.trail.ts +51 -0
  154. package/src/trails/prefer-schema-inference.trail.ts +21 -0
  155. package/src/trails/public-export-example-coverage.trail.ts +16 -0
  156. package/src/trails/public-internal-deep-imports.trail.ts +94 -0
  157. package/src/trails/public-output-schema.trail.ts +55 -0
  158. package/src/trails/public-union-output-discriminants.trail.ts +33 -0
  159. package/src/trails/read-intent-fires.trail.ts +20 -0
  160. package/src/trails/reference-exists.trail.ts +25 -0
  161. package/src/trails/resolved-import-boundary.trail.ts +109 -0
  162. package/src/trails/resource-declarations.trail.ts +25 -0
  163. package/src/trails/resource-exists.trail.ts +27 -0
  164. package/src/trails/resource-id-grammar.trail.ts +39 -0
  165. package/src/trails/resource-mock-coverage.trail.ts +40 -0
  166. package/src/trails/run.ts +205 -0
  167. package/src/trails/scheduled-destroy-intent.trail.ts +56 -0
  168. package/src/trails/schema.ts +295 -0
  169. package/src/trails/signal-graph-coaching.trail.ts +77 -0
  170. package/src/trails/static-resource-accessor-preference.trail.ts +25 -0
  171. package/src/trails/surface-overlay-coherence.trail.ts +24 -0
  172. package/src/trails/surface-trailhead-coherence.trail.ts +25 -0
  173. package/src/trails/topo.ts +6 -0
  174. package/src/trails/trail-fork-coaching.trail.ts +42 -0
  175. package/src/trails/trailhead-override-divergence.trail.ts +47 -0
  176. package/src/trails/unmaterialized-activation-source.trail.ts +72 -0
  177. package/src/trails/unreachable-detour-shadowing.trail.ts +45 -0
  178. package/src/trails/valid-describe-refs.trail.ts +18 -0
  179. package/src/trails/valid-detour-contract.trail.ts +71 -0
  180. package/src/trails/version-gap.trail.ts +35 -0
  181. package/src/trails/version-pinned-compose.trail.ts +23 -0
  182. package/src/trails/version-without-examples.trail.ts +38 -0
  183. package/src/trails/warden-export-symmetry.trail.ts +16 -0
  184. package/src/trails/warden-rules-use-ast.trail.ts +64 -0
  185. package/src/trails/webhook-route-collision.trail.ts +50 -0
  186. package/src/trails/workspace-lock-ownership.trail.ts +16 -0
  187. package/src/trails/wrap-rule.ts +269 -0
  188. package/src/workspaces.ts +264 -0
@@ -0,0 +1,290 @@
1
+ import { statSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ import type {
6
+ ProjectAwareWardenRule,
7
+ TopoAwareWardenRule,
8
+ WardenDiagnostic,
9
+ WardenRuleMetadata,
10
+ WardenRule,
11
+ } from './rules/types.js';
12
+
13
+ const PROJECT_WARDEN_RULES_FILE = '.trails/rules.ts';
14
+ const PROJECT_WARDEN_RULES_DIR = '.trails/rules';
15
+ const LEGACY_PROJECT_WARDEN_RULES_DIR = 'trails/warden/rules';
16
+
17
+ export interface ProjectWardenRules {
18
+ readonly diagnostics: readonly WardenDiagnostic[];
19
+ readonly sourceRules: readonly WardenRule[];
20
+ readonly topoRules: readonly TopoAwareWardenRule[];
21
+ }
22
+
23
+ interface RuleModule {
24
+ readonly default?: unknown;
25
+ readonly rule?: unknown;
26
+ readonly rules?: unknown;
27
+ readonly sourceRule?: unknown;
28
+ readonly sourceRules?: unknown;
29
+ readonly topoRule?: unknown;
30
+ readonly topoRules?: unknown;
31
+ }
32
+
33
+ interface ProjectRuleModulePaths {
34
+ readonly diagnostics: readonly WardenDiagnostic[];
35
+ readonly files: readonly string[];
36
+ }
37
+
38
+ interface LoadedRuleFile extends ProjectWardenRules {
39
+ readonly filePath: string;
40
+ }
41
+
42
+ const diagnostic = (message: string, filePath: string): WardenDiagnostic => ({
43
+ filePath,
44
+ line: 1,
45
+ message,
46
+ rule: 'project-warden-rules',
47
+ severity: 'error',
48
+ });
49
+
50
+ const asArray = (value: unknown): readonly unknown[] => {
51
+ if (value === undefined) {
52
+ return [];
53
+ }
54
+ return Array.isArray(value) ? value : [value];
55
+ };
56
+
57
+ const isSourceRule = (value: unknown): value is WardenRule => {
58
+ if (typeof value !== 'object' || value === null) {
59
+ return false;
60
+ }
61
+ const maybe = value as Partial<WardenRule>;
62
+ return (
63
+ typeof maybe.name === 'string' &&
64
+ typeof maybe.description === 'string' &&
65
+ (maybe.severity === 'error' || maybe.severity === 'warn') &&
66
+ typeof maybe.check === 'function'
67
+ );
68
+ };
69
+
70
+ const isTopoRule = (value: unknown): value is TopoAwareWardenRule => {
71
+ if (typeof value !== 'object' || value === null) {
72
+ return false;
73
+ }
74
+ const maybe = value as Partial<TopoAwareWardenRule>;
75
+ return (
76
+ typeof maybe.name === 'string' &&
77
+ typeof maybe.description === 'string' &&
78
+ (maybe.severity === 'error' || maybe.severity === 'warn') &&
79
+ typeof maybe.checkTopo === 'function'
80
+ );
81
+ };
82
+
83
+ const defaultProjectRuleDepth = (
84
+ tier: WardenRuleMetadata['tier']
85
+ ): WardenRuleMetadata['depth'] => {
86
+ if (tier === 'topo-aware') {
87
+ return 'topo';
88
+ }
89
+ if (tier === 'project-static') {
90
+ return 'project';
91
+ }
92
+ return 'source';
93
+ };
94
+
95
+ const defaultProjectRuleMetadata = (
96
+ rule: { readonly description: string },
97
+ tier: WardenRuleMetadata['tier']
98
+ ): WardenRuleMetadata => ({
99
+ concern: 'general',
100
+ depth: defaultProjectRuleDepth(tier),
101
+ invariant: rule.description,
102
+ lifecycle: { state: 'durable' },
103
+ scope: 'repo-local',
104
+ tier,
105
+ });
106
+
107
+ const isProjectAwareSourceRule = (
108
+ rule: WardenRule
109
+ ): rule is ProjectAwareWardenRule =>
110
+ 'checkWithContext' in rule && typeof rule.checkWithContext === 'function';
111
+
112
+ const withSourceRuleMetadata = (rule: WardenRule): WardenRule => ({
113
+ ...rule,
114
+ metadata:
115
+ rule.metadata ??
116
+ defaultProjectRuleMetadata(
117
+ rule,
118
+ isProjectAwareSourceRule(rule) ? 'project-static' : 'source-static'
119
+ ),
120
+ });
121
+
122
+ const withTopoRuleMetadata = (
123
+ rule: TopoAwareWardenRule
124
+ ): TopoAwareWardenRule => ({
125
+ ...rule,
126
+ metadata: rule.metadata ?? defaultProjectRuleMetadata(rule, 'topo-aware'),
127
+ });
128
+
129
+ const ruleCandidatesFromModule = (module: RuleModule): readonly unknown[] => [
130
+ ...asArray(module.default),
131
+ ...asArray(module.rule),
132
+ ...asArray(module.rules),
133
+ ...asArray(module.sourceRule),
134
+ ...asArray(module.sourceRules),
135
+ ];
136
+
137
+ const topoRuleCandidatesFromModule = (
138
+ module: RuleModule
139
+ ): readonly unknown[] => [
140
+ ...asArray(module.topoRule),
141
+ ...asArray(module.topoRules),
142
+ ];
143
+
144
+ const isFile = (path: string): boolean => {
145
+ try {
146
+ return statSync(path).isFile();
147
+ } catch {
148
+ return false;
149
+ }
150
+ };
151
+
152
+ const isDirectory = (path: string): boolean => {
153
+ try {
154
+ return statSync(path).isDirectory();
155
+ } catch {
156
+ return false;
157
+ }
158
+ };
159
+
160
+ const collectProjectRuleFiles = (rootDir: string): readonly string[] => {
161
+ const files: string[] = [];
162
+ const rulesFile = join(rootDir, PROJECT_WARDEN_RULES_FILE);
163
+ const rulesDir = join(rootDir, PROJECT_WARDEN_RULES_DIR);
164
+
165
+ if (isFile(rulesFile)) {
166
+ files.push(rulesFile);
167
+ }
168
+
169
+ if (!isDirectory(rulesDir)) {
170
+ return files;
171
+ }
172
+
173
+ const glob = new Bun.Glob('*.ts');
174
+ files.push(
175
+ ...[...glob.scanSync({ cwd: rulesDir, onlyFiles: true })]
176
+ .filter(
177
+ (entry) =>
178
+ !entry.endsWith('.test.ts') && !basename(entry).startsWith('_')
179
+ )
180
+ .map((entry) => join(rulesDir, entry))
181
+ );
182
+ return files.toSorted((left, right) => left.localeCompare(right));
183
+ };
184
+
185
+ const collectProjectRuleModulePaths = (
186
+ rootDir: string
187
+ ): ProjectRuleModulePaths => {
188
+ const diagnostics: WardenDiagnostic[] = [];
189
+ const legacyRulesDir = join(rootDir, LEGACY_PROJECT_WARDEN_RULES_DIR);
190
+
191
+ if (isDirectory(legacyRulesDir)) {
192
+ diagnostics.push(
193
+ diagnostic(
194
+ 'Project Warden rules moved from trails/warden/rules to .trails/rules.ts or direct .trails/rules/*.ts files.',
195
+ legacyRulesDir
196
+ )
197
+ );
198
+ }
199
+
200
+ return {
201
+ diagnostics,
202
+ files: collectProjectRuleFiles(rootDir),
203
+ };
204
+ };
205
+
206
+ const loadRuleFile = async (filePath: string): Promise<LoadedRuleFile> => {
207
+ let module: RuleModule;
208
+ try {
209
+ module = (await import(pathToFileURL(filePath).href)) as RuleModule;
210
+ } catch (error) {
211
+ return {
212
+ diagnostics: [
213
+ diagnostic(
214
+ error instanceof Error
215
+ ? `Failed to load project Warden rule module: ${error.message}`
216
+ : 'Failed to load project Warden rule module.',
217
+ filePath
218
+ ),
219
+ ],
220
+ filePath,
221
+ sourceRules: [],
222
+ topoRules: [],
223
+ };
224
+ }
225
+
226
+ const sourceRules = ruleCandidatesFromModule(module)
227
+ .filter(isSourceRule)
228
+ .map(withSourceRuleMetadata);
229
+ const topoRules = topoRuleCandidatesFromModule(module)
230
+ .filter(isTopoRule)
231
+ .map(withTopoRuleMetadata);
232
+ if (sourceRules.length === 0 && topoRules.length === 0) {
233
+ return {
234
+ diagnostics: [
235
+ diagnostic(
236
+ 'Project Warden rule module must export a WardenRule or TopoAwareWardenRule.',
237
+ filePath
238
+ ),
239
+ ],
240
+ filePath,
241
+ sourceRules: [],
242
+ topoRules: [],
243
+ };
244
+ }
245
+
246
+ return { diagnostics: [], filePath, sourceRules, topoRules };
247
+ };
248
+
249
+ const duplicateRuleDiagnostics = (
250
+ loaded: readonly LoadedRuleFile[]
251
+ ): readonly WardenDiagnostic[] => {
252
+ const seen = new Map<string, string>();
253
+ const diagnostics: WardenDiagnostic[] = [];
254
+
255
+ for (const result of loaded) {
256
+ for (const rule of [...result.sourceRules, ...result.topoRules]) {
257
+ const previousFilePath = seen.get(rule.name);
258
+ if (previousFilePath === undefined) {
259
+ seen.set(rule.name, result.filePath);
260
+ continue;
261
+ }
262
+ diagnostics.push(
263
+ diagnostic(
264
+ `Duplicate project Warden rule id "${rule.name}" also exported from "${previousFilePath}". Project-local rule ids must be unique.`,
265
+ result.filePath
266
+ )
267
+ );
268
+ }
269
+ }
270
+
271
+ return diagnostics;
272
+ };
273
+
274
+ export const loadProjectWardenRules = async (
275
+ rootDir: string
276
+ ): Promise<ProjectWardenRules> => {
277
+ const collected = collectProjectRuleModulePaths(rootDir);
278
+ const { files } = collected;
279
+ const loaded = await Promise.all(files.map(loadRuleFile));
280
+
281
+ return {
282
+ diagnostics: [
283
+ ...collected.diagnostics,
284
+ ...loaded.flatMap((result) => result.diagnostics),
285
+ ...duplicateRuleDiagnostics(loaded),
286
+ ],
287
+ sourceRules: loaded.flatMap((result) => result.sourceRules),
288
+ topoRules: loaded.flatMap((result) => result.topoRules),
289
+ };
290
+ };
@@ -0,0 +1,188 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+
4
+ import {
5
+ getGovernedVocabularyTransition,
6
+ listGovernedVocabularyTransitions,
7
+ } from './rules/retired-vocabulary.js';
8
+ import { resolveReceiptForWarden } from './regrade-receipt.js';
9
+ import type {
10
+ GovernedVocabularyHistoryEvidence,
11
+ GovernedVocabularyHistoryIssue,
12
+ } from './rules/types.js';
13
+
14
+ export interface GovernedVocabularyHistoryIndex {
15
+ readonly byTransitionId: ReadonlyMap<
16
+ string,
17
+ GovernedVocabularyHistoryEvidence
18
+ >;
19
+ readonly issues: readonly GovernedVocabularyHistoryIssue[];
20
+ }
21
+
22
+ const normalizePath = (value: string): string => value.replaceAll('\\', '/');
23
+
24
+ type HistoryFileResult =
25
+ | {
26
+ readonly kind: 'evidence';
27
+ readonly value: GovernedVocabularyHistoryEvidence;
28
+ }
29
+ | { readonly kind: 'ignore' }
30
+ | { readonly kind: 'issue'; readonly value: GovernedVocabularyHistoryIssue };
31
+
32
+ const historyIssue = (
33
+ path: string,
34
+ message: string,
35
+ transitionId?: string
36
+ ): HistoryFileResult => ({
37
+ kind: 'issue',
38
+ value: {
39
+ message,
40
+ path,
41
+ ...(transitionId === undefined ? {} : { transitionId }),
42
+ },
43
+ });
44
+
45
+ type GovernedReceiptPlan =
46
+ | { readonly kind: 'class' }
47
+ | {
48
+ readonly from: string;
49
+ readonly id?: string | undefined;
50
+ readonly kind: 'vocabulary';
51
+ readonly to: string;
52
+ };
53
+
54
+ const governedTransitionForPlan = (
55
+ plan: GovernedReceiptPlan,
56
+ transitionIds: readonly (string | undefined)[] = []
57
+ ) => {
58
+ if (plan.kind !== 'vocabulary') {
59
+ return;
60
+ }
61
+ for (const transitionId of [plan.id, ...transitionIds]) {
62
+ if (transitionId === undefined) {
63
+ continue;
64
+ }
65
+ const transition = getGovernedVocabularyTransition(transitionId);
66
+ if (transition !== undefined) {
67
+ return transition;
68
+ }
69
+ }
70
+ return listGovernedVocabularyTransitions().find(
71
+ (transition) =>
72
+ transition.from === plan.from &&
73
+ (transition.target.kind === 'single'
74
+ ? transition.target.to === plan.to
75
+ : transition.target.options.some((option) => option.to === plan.to))
76
+ );
77
+ };
78
+
79
+ const loadReceiptHistoryFile = (
80
+ json: unknown,
81
+ observedPath: string
82
+ ): HistoryFileResult => {
83
+ const resolved = resolveReceiptForWarden(json);
84
+ if (resolved.value === undefined) {
85
+ return historyIssue(
86
+ observedPath,
87
+ `Committed Regrade receipt has invalid deterministic evidence (${resolved.error ?? 'unknown error'}).`
88
+ );
89
+ }
90
+ const { artifact, runs } = resolved.value;
91
+ if (normalizePath(artifact.path) !== observedPath) {
92
+ return historyIssue(
93
+ observedPath,
94
+ 'Committed Regrade history path does not match its observed file.'
95
+ );
96
+ }
97
+ const latest = runs.at(-1);
98
+ const transition =
99
+ latest === undefined
100
+ ? undefined
101
+ : governedTransitionForPlan(latest.plan, [artifact.id]);
102
+ if (transition === undefined) {
103
+ return { kind: 'ignore' };
104
+ }
105
+ const allRunsMatchTransition = runs.every(({ plan }) => {
106
+ if (
107
+ plan.kind !== 'vocabulary' ||
108
+ governedTransitionForPlan(plan, [artifact.id])?.id !== transition.id ||
109
+ plan.from !== transition.from
110
+ ) {
111
+ return false;
112
+ }
113
+ return transition.target.kind === 'single'
114
+ ? transition.target.to === plan.to
115
+ : transition.target.options.some((option) => option.to === plan.to);
116
+ });
117
+ if (!allRunsMatchTransition) {
118
+ return historyIssue(
119
+ observedPath,
120
+ 'Committed Regrade history does not match its governed registry transition.',
121
+ transition.id
122
+ );
123
+ }
124
+ return {
125
+ kind: 'evidence',
126
+ value: {
127
+ caseSensitive: latest?.caseSensitive ?? false,
128
+ id: artifact.id,
129
+ latestFormJudgments: latest?.forms ?? [],
130
+ path: artifact.path,
131
+ runCount: runs.length,
132
+ transitionId: transition.id,
133
+ },
134
+ };
135
+ };
136
+
137
+ const loadHistoryFile = (rootDir: string, name: string): HistoryFileResult => {
138
+ const absolutePath = join(rootDir, '.trails', 'regrade', 'history', name);
139
+ const observedPath = normalizePath(relative(rootDir, absolutePath));
140
+ let json: unknown;
141
+ try {
142
+ json = JSON.parse(readFileSync(absolutePath, 'utf8'));
143
+ } catch {
144
+ return historyIssue(
145
+ observedPath,
146
+ 'Committed Regrade history is not valid JSON.'
147
+ );
148
+ }
149
+ return loadReceiptHistoryFile(json, observedPath);
150
+ };
151
+
152
+ export const loadGovernedVocabularyHistory = (
153
+ rootDir: string
154
+ ): GovernedVocabularyHistoryIndex => {
155
+ const directory = join(rootDir, '.trails', 'regrade', 'history');
156
+ if (!existsSync(directory)) {
157
+ return { byTransitionId: new Map(), issues: [] };
158
+ }
159
+
160
+ const byTransitionId = new Map<string, GovernedVocabularyHistoryEvidence>();
161
+ const issues: GovernedVocabularyHistoryIssue[] = [];
162
+ const files = readdirSync(directory)
163
+ .filter((name) => name.endsWith('.json'))
164
+ .toSorted();
165
+
166
+ for (const name of files) {
167
+ const result = loadHistoryFile(rootDir, name);
168
+ if (result.kind === 'ignore') {
169
+ continue;
170
+ }
171
+ if (result.kind === 'issue') {
172
+ issues.push(result.value);
173
+ continue;
174
+ }
175
+ if (byTransitionId.has(result.value.transitionId)) {
176
+ issues.push({
177
+ message:
178
+ 'Multiple committed Regrade histories claim the same governed transition.',
179
+ path: result.value.path,
180
+ transitionId: result.value.transitionId,
181
+ });
182
+ continue;
183
+ }
184
+ byTransitionId.set(result.value.transitionId, result.value);
185
+ }
186
+
187
+ return { byTransitionId, issues };
188
+ };