@ontrails/warden 1.0.0-beta.24 → 1.0.0-beta.29

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 (61) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/README.md +35 -1
  3. package/package.json +10 -9
  4. package/src/ast.ts +109 -0
  5. package/src/cli.ts +44 -4
  6. package/src/command.ts +24 -34
  7. package/src/drift.ts +24 -8
  8. package/src/index.ts +9 -0
  9. package/src/project-rules.ts +290 -0
  10. package/src/resolve.ts +8 -7
  11. package/src/rules/ast.ts +837 -6
  12. package/src/rules/cli-command-route-coherence.ts +177 -0
  13. package/src/rules/composes-declarations.ts +210 -77
  14. package/src/rules/context-no-surface-types.ts +15 -12
  15. package/src/rules/contour-exists.ts +7 -7
  16. package/src/rules/dead-internal-trail.ts +11 -4
  17. package/src/rules/dead-public-trail.ts +258 -0
  18. package/src/rules/duplicate-public-contract.ts +91 -0
  19. package/src/rules/error-mapping-completeness.ts +5 -3
  20. package/src/rules/example-valid.ts +6 -12
  21. package/src/rules/fires-declarations.ts +41 -64
  22. package/src/rules/implementation-returns-result.ts +208 -76
  23. package/src/rules/incomplete-crud.ts +20 -19
  24. package/src/rules/index.ts +15 -0
  25. package/src/rules/layer-field-name-drift.ts +12 -6
  26. package/src/rules/library-projection-coherence.ts +100 -0
  27. package/src/rules/metadata.ts +102 -1
  28. package/src/rules/no-destructured-compose.ts +16 -14
  29. package/src/rules/no-native-error-result.ts +15 -8
  30. package/src/rules/no-redundant-result-error-wrap.ts +82 -29
  31. package/src/rules/no-sync-result-assumption.ts +70 -68
  32. package/src/rules/no-top-level-surface.ts +46 -64
  33. package/src/rules/on-references-exist.ts +1 -1
  34. package/src/rules/owner-projection-parity.ts +10 -13
  35. package/src/rules/public-export-example-coverage.ts +29 -20
  36. package/src/rules/public-internal-deep-imports.ts +2 -2
  37. package/src/rules/read-intent-fires.ts +8 -8
  38. package/src/rules/registry-names.ts +10 -0
  39. package/src/rules/resource-declarations.ts +20 -31
  40. package/src/rules/resource-exists.ts +2 -2
  41. package/src/rules/resource-id-grammar.ts +2 -2
  42. package/src/rules/resource-mock-coverage.ts +2 -2
  43. package/src/rules/static-resource-accessor-preference.ts +26 -34
  44. package/src/rules/surface-facet-coherence.ts +21 -29
  45. package/src/rules/trail-fork-coaching.ts +616 -0
  46. package/src/rules/trail-versioning-source.ts +56 -78
  47. package/src/rules/types.ts +2 -0
  48. package/src/rules/unreachable-detour-shadowing.ts +16 -21
  49. package/src/rules/valid-describe-refs.ts +14 -12
  50. package/src/rules/warden-export-symmetry.ts +42 -35
  51. package/src/rules/warden-rules-use-ast.ts +168 -50
  52. package/src/trails/cli-command-route-coherence.trail.ts +47 -0
  53. package/src/trails/dead-public-trail.trail.ts +31 -0
  54. package/src/trails/duplicate-public-contract.trail.ts +47 -0
  55. package/src/trails/error-mapping-completeness.trail.ts +1 -0
  56. package/src/trails/index.ts +5 -0
  57. package/src/trails/library-projection-coherence.trail.ts +43 -0
  58. package/src/trails/schema.ts +4 -0
  59. package/src/trails/trail-fork-coaching.trail.ts +42 -0
  60. package/src/trails/warden-rules-use-ast.trail.ts +19 -0
  61. package/src/trails/wrap-rule.ts +1 -0
package/src/index.ts CHANGED
@@ -119,6 +119,10 @@ export {
119
119
  export type { DriftResult } from './drift.js';
120
120
  export { checkDrift } from './drift.js';
121
121
 
122
+ // Project-local rule loading
123
+ export type { ProjectWardenRules } from './project-rules.js';
124
+ export { loadProjectWardenRules } from './project-rules.js';
125
+
122
126
  // Guide projection
123
127
  export type {
124
128
  WardenGuideFormat,
@@ -161,13 +165,16 @@ export { wardenTopo } from './trails/topo.js';
161
165
  export { runTopoAwareWardenTrails, runWardenTrails } from './trails/run.js';
162
166
  export {
163
167
  activationOrphanTrail,
168
+ cliCommandRouteCoherenceTrail,
164
169
  circularRefsTrail,
165
170
  contourExistsTrail,
166
171
  contextNoSurfaceTypesTrail,
167
172
  composesDeclarationsTrail,
168
173
  deadInternalTrailTrail,
174
+ deadPublicTrailTrail,
169
175
  deprecationWithoutGuidanceTrail,
170
176
  diagnosticSchema,
177
+ duplicatePublicContractTrail,
171
178
  draftFileMarkingTrail,
172
179
  draftVisibleDebtTrail,
173
180
  errorMappingCompletenessTrail,
@@ -179,6 +186,7 @@ export {
179
186
  incompleteCrudTrail,
180
187
  intentPropagationTrail,
181
188
  layerFieldNameDriftTrail,
189
+ libraryProjectionCoherenceTrail,
182
190
  markerSchemaUnsupportedTrail,
183
191
  missingVisibilityTrail,
184
192
  missingReconcileTrail,
@@ -217,6 +225,7 @@ export {
217
225
  signalGraphCoachingTrail,
218
226
  staticResourceAccessorPreferenceTrail,
219
227
  surfaceFacetCoherenceTrail,
228
+ trailForkCoachingTrail,
220
229
  unmaterializedActivationSourceTrail,
221
230
  topoAwareRuleInput,
222
231
  unreachableDetourShadowingTrail,
@@ -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
+ };
package/src/resolve.ts CHANGED
@@ -12,6 +12,10 @@ import { ResolverFactory } from 'oxc-resolver';
12
12
  import type { NapiResolveOptions, ResolveResult } from 'oxc-resolver';
13
13
 
14
14
  import {
15
+ getNodeArguments,
16
+ getNodeCallee,
17
+ getNodeName,
18
+ getNodeSource,
15
19
  getStringValue,
16
20
  isStringLiteral,
17
21
  offsetToLine,
@@ -404,7 +408,7 @@ const buildResolution = ({
404
408
  };
405
409
 
406
410
  const getModuleSourceNode = (node: AstNode): AstNode | undefined =>
407
- (node as unknown as { source?: AstNode }).source;
411
+ getNodeSource(node);
408
412
 
409
413
  const isStaticImportNode = (node: AstNode): boolean =>
410
414
  node.type === 'ImportDeclaration' ||
@@ -421,15 +425,12 @@ const isRequireCallExpression = (node: AstNode): boolean => {
421
425
  if (node.type !== 'CallExpression') {
422
426
  return false;
423
427
  }
424
- const { callee } = node as unknown as { callee?: AstNode };
425
- return (
426
- callee?.type === 'Identifier' &&
427
- (callee as unknown as { name?: string }).name === 'require'
428
- );
428
+ const callee = getNodeCallee(node);
429
+ return callee?.type === 'Identifier' && getNodeName(callee) === 'require';
429
430
  };
430
431
 
431
432
  const getRequireSourceNode = (node: AstNode): AstNode | undefined =>
432
- (node as unknown as { arguments?: readonly AstNode[] }).arguments?.[0];
433
+ getNodeArguments(node)?.[0];
433
434
 
434
435
  export const collectImportSpecifiers = (
435
436
  filePath: string,