@ontrails/warden 1.0.0-beta.3 → 1.0.0-beta.30

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 (260) hide show
  1. package/CHANGELOG.md +625 -9
  2. package/README.md +111 -26
  3. package/bin/warden.ts +50 -0
  4. package/package.json +28 -5
  5. package/src/adapter-check.ts +136 -0
  6. package/src/ast.ts +137 -0
  7. package/src/cli.ts +1415 -104
  8. package/src/command.ts +943 -0
  9. package/src/config.ts +184 -0
  10. package/src/draft.ts +22 -0
  11. package/src/drift.ts +122 -22
  12. package/src/fix.ts +120 -0
  13. package/src/formatters.ts +79 -9
  14. package/src/guide.ts +245 -0
  15. package/src/index.ts +215 -14
  16. package/src/project-context.ts +163 -0
  17. package/src/project-rules.ts +290 -0
  18. package/src/resolve.ts +531 -0
  19. package/src/rules/activation-orphan.ts +97 -0
  20. package/src/rules/ast.ts +4008 -86
  21. package/src/rules/circular-refs.ts +154 -0
  22. package/src/rules/cli-command-route-coherence.ts +177 -0
  23. package/src/rules/composes-declarations.ts +837 -0
  24. package/src/rules/context-no-surface-types.ts +78 -15
  25. package/src/rules/contour-exists.ts +251 -0
  26. package/src/rules/contour-ids.ts +15 -0
  27. package/src/rules/dead-internal-trail.ts +161 -0
  28. package/src/rules/dead-public-trail.ts +258 -0
  29. package/src/rules/draft-file-marking.ts +160 -0
  30. package/src/rules/draft-visible-debt.ts +87 -0
  31. package/src/rules/duplicate-public-contract.ts +91 -0
  32. package/src/rules/error-mapping-completeness.ts +290 -0
  33. package/src/rules/example-valid.ts +395 -0
  34. package/src/rules/fires-declarations.ts +735 -0
  35. package/src/rules/implementation-returns-result.ts +1411 -166
  36. package/src/rules/incomplete-accessor-for-standard-op.ts +272 -0
  37. package/src/rules/incomplete-crud.ts +581 -0
  38. package/src/rules/index.ts +234 -18
  39. package/src/rules/intent-propagation.ts +127 -0
  40. package/src/rules/layer-field-name-drift.ts +102 -0
  41. package/src/rules/library-projection-coherence.ts +100 -0
  42. package/src/rules/metadata.ts +755 -0
  43. package/src/rules/missing-reconcile.ts +98 -0
  44. package/src/rules/missing-visibility.ts +110 -0
  45. package/src/rules/no-destructured-compose.ts +194 -0
  46. package/src/rules/no-dev-permit-in-source.ts +99 -0
  47. package/src/rules/no-direct-implementation-call.ts +7 -7
  48. package/src/rules/no-legacy-layer-imports.ts +211 -0
  49. package/src/rules/no-native-error-result.ts +118 -0
  50. package/src/rules/no-redundant-result-error-wrap.ts +384 -0
  51. package/src/rules/no-retired-cross-vocabulary.ts +194 -0
  52. package/src/rules/no-sync-result-assumption.ts +1135 -98
  53. package/src/rules/no-throw-in-detour-recover.ts +225 -0
  54. package/src/rules/no-throw-in-implementation.ts +10 -9
  55. package/src/rules/no-top-level-surface.ts +371 -0
  56. package/src/rules/on-references-exist.ts +194 -0
  57. package/src/rules/orphaned-signal.ts +150 -0
  58. package/src/rules/owner-projection-parity.ts +143 -0
  59. package/src/rules/permit-governance.ts +25 -0
  60. package/src/rules/public-export-example-coverage.ts +562 -0
  61. package/src/rules/public-internal-deep-imports.ts +517 -0
  62. package/src/rules/public-output-schema.ts +29 -0
  63. package/src/rules/public-union-output-discriminants.ts +150 -0
  64. package/src/rules/read-intent-fires.ts +187 -0
  65. package/src/rules/reference-exists.ts +98 -0
  66. package/src/rules/registry-names.ts +155 -0
  67. package/src/rules/resolved-import-boundary.ts +146 -0
  68. package/src/rules/resource-declarations.ts +693 -0
  69. package/src/rules/resource-exists.ts +179 -0
  70. package/src/rules/resource-id-grammar.ts +65 -0
  71. package/src/rules/resource-mock-coverage.ts +115 -0
  72. package/src/rules/scan.ts +38 -25
  73. package/src/rules/scheduled-destroy-intent.ts +44 -0
  74. package/src/rules/signal-graph-coaching.ts +191 -0
  75. package/src/rules/specs.ts +9 -5
  76. package/src/rules/static-resource-accessor-preference.ts +649 -0
  77. package/src/rules/surface-facet-coherence.ts +362 -0
  78. package/src/rules/trail-fork-coaching.ts +616 -0
  79. package/src/rules/trail-versioning-source.ts +1072 -0
  80. package/src/rules/trail-versioning-topo.ts +172 -0
  81. package/src/rules/types.ts +272 -6
  82. package/src/rules/unmaterialized-activation-source.ts +84 -0
  83. package/src/rules/unreachable-detour-shadowing.ts +339 -0
  84. package/src/rules/valid-describe-refs.ts +162 -32
  85. package/src/rules/valid-detour-contract.ts +78 -0
  86. package/src/rules/warden-export-symmetry.ts +540 -0
  87. package/src/rules/warden-rules-use-ast.ts +1114 -0
  88. package/src/rules/webhook-route-collision.ts +243 -0
  89. package/src/trails/activation-orphan.trail.ts +84 -0
  90. package/src/trails/circular-refs.trail.ts +29 -0
  91. package/src/trails/cli-command-route-coherence.trail.ts +47 -0
  92. package/src/trails/composes-declarations.trail.ts +22 -0
  93. package/src/trails/context-no-surface-types.trail.ts +21 -0
  94. package/src/trails/contour-exists.trail.ts +21 -0
  95. package/src/trails/dead-internal-trail.trail.ts +26 -0
  96. package/src/trails/dead-public-trail.trail.ts +31 -0
  97. package/src/trails/deprecation-without-guidance.trail.ts +21 -0
  98. package/src/trails/draft-file-marking.trail.ts +16 -0
  99. package/src/trails/draft-visible-debt.trail.ts +16 -0
  100. package/src/trails/duplicate-public-contract.trail.ts +47 -0
  101. package/src/trails/error-mapping-completeness.trail.ts +30 -0
  102. package/src/trails/example-valid.trail.ts +25 -0
  103. package/src/trails/fires-declarations.trail.ts +23 -0
  104. package/src/trails/fork-without-preserved-blaze.trail.ts +31 -0
  105. package/src/trails/implementation-returns-result.trail.ts +20 -0
  106. package/src/trails/incomplete-accessor-for-standard-op.trail.ts +76 -0
  107. package/src/trails/incomplete-crud.trail.ts +39 -0
  108. package/src/trails/index.ts +83 -0
  109. package/src/trails/intent-propagation.trail.ts +30 -0
  110. package/src/trails/layer-field-name-drift.trail.ts +39 -0
  111. package/src/trails/library-projection-coherence.trail.ts +43 -0
  112. package/src/trails/marker-schema-unsupported.trail.ts +23 -0
  113. package/src/trails/missing-reconcile.trail.ts +33 -0
  114. package/src/trails/missing-visibility.trail.ts +22 -0
  115. package/src/trails/no-destructured-compose.trail.ts +44 -0
  116. package/src/trails/no-dev-permit-in-source.trail.ts +16 -0
  117. package/src/trails/no-direct-implementation-call.trail.ts +16 -0
  118. package/src/trails/no-legacy-layer-imports.trail.ts +41 -0
  119. package/src/trails/no-native-error-result.trail.ts +18 -0
  120. package/src/trails/no-redundant-result-error-wrap.trail.ts +55 -0
  121. package/src/trails/no-retired-cross-vocabulary.trail.ts +42 -0
  122. package/src/trails/no-sync-result-assumption.trail.ts +19 -0
  123. package/src/trails/no-throw-in-detour-recover.trail.ts +24 -0
  124. package/src/trails/no-throw-in-implementation.trail.ts +20 -0
  125. package/src/trails/no-top-level-surface.trail.ts +43 -0
  126. package/src/trails/on-references-exist.trail.ts +21 -0
  127. package/src/trails/orphaned-signal.trail.ts +36 -0
  128. package/src/trails/owner-projection-parity.trail.ts +26 -0
  129. package/src/trails/pending-force.trail.ts +21 -0
  130. package/src/trails/permit-governance.trail.ts +51 -0
  131. package/src/trails/prefer-schema-inference.trail.ts +21 -0
  132. package/src/trails/public-export-example-coverage.trail.ts +16 -0
  133. package/src/trails/public-internal-deep-imports.trail.ts +94 -0
  134. package/src/trails/public-output-schema.trail.ts +55 -0
  135. package/src/trails/public-union-output-discriminants.trail.ts +33 -0
  136. package/src/trails/read-intent-fires.trail.ts +20 -0
  137. package/src/trails/reference-exists.trail.ts +25 -0
  138. package/src/trails/resolved-import-boundary.trail.ts +109 -0
  139. package/src/trails/resource-declarations.trail.ts +25 -0
  140. package/src/trails/resource-exists.trail.ts +27 -0
  141. package/src/trails/resource-id-grammar.trail.ts +39 -0
  142. package/src/trails/resource-mock-coverage.trail.ts +40 -0
  143. package/src/trails/run.ts +162 -0
  144. package/src/trails/scheduled-destroy-intent.trail.ts +56 -0
  145. package/src/trails/schema.ts +198 -0
  146. package/src/trails/signal-graph-coaching.trail.ts +77 -0
  147. package/src/trails/static-resource-accessor-preference.trail.ts +25 -0
  148. package/src/trails/surface-facet-coherence.trail.ts +25 -0
  149. package/src/trails/topo.ts +6 -0
  150. package/src/trails/trail-fork-coaching.trail.ts +42 -0
  151. package/src/trails/unmaterialized-activation-source.trail.ts +72 -0
  152. package/src/trails/unreachable-detour-shadowing.trail.ts +45 -0
  153. package/src/trails/valid-describe-refs.trail.ts +18 -0
  154. package/src/trails/valid-detour-contract.trail.ts +71 -0
  155. package/src/trails/version-gap.trail.ts +35 -0
  156. package/src/trails/version-pinned-compose.trail.ts +23 -0
  157. package/src/trails/version-without-examples.trail.ts +38 -0
  158. package/src/trails/warden-export-symmetry.trail.ts +16 -0
  159. package/src/trails/warden-rules-use-ast.trail.ts +64 -0
  160. package/src/trails/webhook-route-collision.trail.ts +50 -0
  161. package/src/trails/wrap-rule.ts +214 -0
  162. package/src/workspaces.ts +238 -0
  163. package/.turbo/turbo-build.log +0 -1
  164. package/.turbo/turbo-lint.log +0 -3
  165. package/.turbo/turbo-typecheck.log +0 -1
  166. package/dist/cli.d.ts +0 -46
  167. package/dist/cli.d.ts.map +0 -1
  168. package/dist/cli.js +0 -221
  169. package/dist/cli.js.map +0 -1
  170. package/dist/drift.d.ts +0 -26
  171. package/dist/drift.d.ts.map +0 -1
  172. package/dist/drift.js +0 -27
  173. package/dist/drift.js.map +0 -1
  174. package/dist/formatters.d.ts +0 -29
  175. package/dist/formatters.d.ts.map +0 -1
  176. package/dist/formatters.js +0 -87
  177. package/dist/formatters.js.map +0 -1
  178. package/dist/index.d.ts +0 -26
  179. package/dist/index.d.ts.map +0 -1
  180. package/dist/index.js +0 -26
  181. package/dist/index.js.map +0 -1
  182. package/dist/rules/ast.d.ts +0 -41
  183. package/dist/rules/ast.d.ts.map +0 -1
  184. package/dist/rules/ast.js +0 -163
  185. package/dist/rules/ast.js.map +0 -1
  186. package/dist/rules/context-no-surface-types.d.ts +0 -12
  187. package/dist/rules/context-no-surface-types.d.ts.map +0 -1
  188. package/dist/rules/context-no-surface-types.js +0 -96
  189. package/dist/rules/context-no-surface-types.js.map +0 -1
  190. package/dist/rules/implementation-returns-result.d.ts +0 -13
  191. package/dist/rules/implementation-returns-result.d.ts.map +0 -1
  192. package/dist/rules/implementation-returns-result.js +0 -277
  193. package/dist/rules/implementation-returns-result.js.map +0 -1
  194. package/dist/rules/index.d.ts +0 -22
  195. package/dist/rules/index.d.ts.map +0 -1
  196. package/dist/rules/index.js +0 -41
  197. package/dist/rules/index.js.map +0 -1
  198. package/dist/rules/no-direct-impl-in-route.d.ts +0 -12
  199. package/dist/rules/no-direct-impl-in-route.d.ts.map +0 -1
  200. package/dist/rules/no-direct-impl-in-route.js +0 -46
  201. package/dist/rules/no-direct-impl-in-route.js.map +0 -1
  202. package/dist/rules/no-direct-implementation-call.d.ts +0 -12
  203. package/dist/rules/no-direct-implementation-call.d.ts.map +0 -1
  204. package/dist/rules/no-direct-implementation-call.js +0 -39
  205. package/dist/rules/no-direct-implementation-call.js.map +0 -1
  206. package/dist/rules/no-sync-result-assumption.d.ts +0 -6
  207. package/dist/rules/no-sync-result-assumption.d.ts.map +0 -1
  208. package/dist/rules/no-sync-result-assumption.js +0 -98
  209. package/dist/rules/no-sync-result-assumption.js.map +0 -1
  210. package/dist/rules/no-throw-in-detour-target.d.ts +0 -12
  211. package/dist/rules/no-throw-in-detour-target.d.ts.map +0 -1
  212. package/dist/rules/no-throw-in-detour-target.js +0 -87
  213. package/dist/rules/no-throw-in-detour-target.js.map +0 -1
  214. package/dist/rules/no-throw-in-implementation.d.ts +0 -9
  215. package/dist/rules/no-throw-in-implementation.d.ts.map +0 -1
  216. package/dist/rules/no-throw-in-implementation.js +0 -34
  217. package/dist/rules/no-throw-in-implementation.js.map +0 -1
  218. package/dist/rules/prefer-schema-inference.d.ts +0 -7
  219. package/dist/rules/prefer-schema-inference.d.ts.map +0 -1
  220. package/dist/rules/prefer-schema-inference.js +0 -86
  221. package/dist/rules/prefer-schema-inference.js.map +0 -1
  222. package/dist/rules/scan.d.ts +0 -8
  223. package/dist/rules/scan.d.ts.map +0 -1
  224. package/dist/rules/scan.js +0 -32
  225. package/dist/rules/scan.js.map +0 -1
  226. package/dist/rules/specs.d.ts +0 -29
  227. package/dist/rules/specs.d.ts.map +0 -1
  228. package/dist/rules/specs.js +0 -192
  229. package/dist/rules/specs.js.map +0 -1
  230. package/dist/rules/structure.d.ts +0 -13
  231. package/dist/rules/structure.d.ts.map +0 -1
  232. package/dist/rules/structure.js +0 -142
  233. package/dist/rules/structure.js.map +0 -1
  234. package/dist/rules/types.d.ts +0 -52
  235. package/dist/rules/types.d.ts.map +0 -1
  236. package/dist/rules/types.js +0 -2
  237. package/dist/rules/types.js.map +0 -1
  238. package/dist/rules/valid-describe-refs.d.ts +0 -7
  239. package/dist/rules/valid-describe-refs.d.ts.map +0 -1
  240. package/dist/rules/valid-describe-refs.js +0 -51
  241. package/dist/rules/valid-describe-refs.js.map +0 -1
  242. package/dist/rules/valid-detour-refs.d.ts +0 -6
  243. package/dist/rules/valid-detour-refs.d.ts.map +0 -1
  244. package/dist/rules/valid-detour-refs.js +0 -116
  245. package/dist/rules/valid-detour-refs.js.map +0 -1
  246. package/src/__tests__/cli.test.ts +0 -198
  247. package/src/__tests__/drift.test.ts +0 -74
  248. package/src/__tests__/formatters.test.ts +0 -157
  249. package/src/__tests__/implementation-returns-result.test.ts +0 -128
  250. package/src/__tests__/no-direct-implementation-call.test.ts +0 -83
  251. package/src/__tests__/no-sync-result-assumption.test.ts +0 -85
  252. package/src/__tests__/no-throw-in-detour-target.test.ts +0 -78
  253. package/src/__tests__/prefer-schema-inference.test.ts +0 -84
  254. package/src/__tests__/rules.test.ts +0 -215
  255. package/src/__tests__/valid-describe-refs.test.ts +0 -60
  256. package/src/rules/no-direct-impl-in-route.ts +0 -77
  257. package/src/rules/no-throw-in-detour-target.ts +0 -150
  258. package/src/rules/valid-detour-refs.ts +0 -187
  259. package/tsconfig.json +0 -9
  260. package/tsconfig.tsbuildinfo +0 -1
package/src/cli.ts CHANGED
@@ -5,38 +5,184 @@
5
5
  * and returns a structured report.
6
6
  */
7
7
 
8
- import { resolve } from 'node:path';
8
+ import { isAbsolute, relative, resolve } from 'node:path';
9
9
 
10
+ import { resolveTrailsProjectRoot } from '@ontrails/config';
10
11
  import type { Topo } from '@ontrails/core';
12
+ import { deriveTopoGraph } from '@ontrails/topographer';
13
+ import type { TopoGraph } from '@ontrails/topographer';
14
+ import { getContourReferences } from '@ontrails/core';
11
15
 
16
+ import type {
17
+ EffectiveWardenConfig,
18
+ WardenConfigInput,
19
+ WardenConfigLayer,
20
+ WardenDepth,
21
+ WardenFailOn,
22
+ WardenFormat,
23
+ WardenLockMode,
24
+ } from './config.js';
25
+ import { runWardenAdapterChecks } from './adapter-check.js';
26
+ import { resolveWardenConfig } from './config.js';
27
+ import { isDraftMarkedFile } from './draft.js';
28
+ import { applySafeFixesToSource, hasSafeFixEdits } from './fix.js';
12
29
  import type { DriftResult } from './drift.js';
13
30
  import { checkDrift } from './drift.js';
31
+ import { loadProjectWardenRules } from './project-rules.js';
32
+ import type { ProjectWardenRules } from './project-rules.js';
33
+ import {
34
+ collectProjectDocumentationImportResolutions,
35
+ collectProjectImportResolutions,
36
+ collectPublicWorkspaces,
37
+ } from './project-context.js';
14
38
  import {
15
- findConfigProperty,
39
+ collectComposeTargetTrailIds,
40
+ collectContourDefinitionIds,
41
+ collectContourReferenceTargetsByName,
42
+ collectCrudTableIds as collectCrudTableIdsFromAst,
43
+ collectOnTargetSignalIds as collectOnTargetSignalIdsFromAst,
44
+ collectReconcileTableIds as collectReconcileTableIdsFromAst,
45
+ collectResourceDefinitionIds,
46
+ collectSignalDefinitionIds,
47
+ collectTrailIntentsById,
16
48
  findTrailDefinitions,
17
49
  parse,
18
- walk,
19
50
  } from './rules/ast.js';
20
- import { wardenRules } from './rules/index.js';
51
+ import { collectFileCrudCoverage } from './rules/incomplete-crud.js';
52
+ import { wardenRules, wardenTopoRules } from './rules/index.js';
53
+ import { getWardenRuleMetadata } from './rules/metadata.js';
54
+ import {
55
+ isWardenDevPermitTestScanTarget,
56
+ isWardenSourceScanTarget,
57
+ } from './rules/scan.js';
21
58
  import type {
22
59
  ProjectAwareWardenRule,
23
60
  ProjectContext,
61
+ TopoAwareWardenRule,
24
62
  WardenDiagnostic,
63
+ WardenGuidanceLink,
25
64
  WardenRule,
65
+ WardenRuleTier,
26
66
  } from './rules/types.js';
67
+ import type { WardenImportResolution } from './resolve.js';
68
+
69
+ /**
70
+ * Resolved topo input for Warden runs that govern multiple apps.
71
+ */
72
+ export interface WardenTopoTarget {
73
+ /** Optional precomputed topo graph, including graph-only audit annotations. */
74
+ readonly graph?: TopoGraph | undefined;
75
+ /** Stable app/topo label used to tag topo-aware diagnostics. */
76
+ readonly name?: string | undefined;
77
+ /** Resolved topo module to inspect. */
78
+ readonly topo: Topo;
79
+ }
27
80
 
28
81
  /**
29
- * Options for the warden CLI runner.
82
+ * Options for the shared Warden runner.
30
83
  */
31
- export interface WardenOptions {
84
+ export interface WardenRunOptions {
32
85
  /** Root directory to scan for TypeScript files. Defaults to cwd. */
33
86
  readonly rootDir?: string | undefined;
87
+ /** Warden config section from `trails.config.ts`, if already loaded. */
88
+ readonly config?: WardenConfigInput | undefined;
89
+ /** CLI/config-layer app names carried through shared resolution. */
90
+ readonly apps?: readonly string[] | undefined;
91
+ /** Include shared adapter authoring checks as Warden diagnostics. */
92
+ readonly adapterCheck?: boolean | undefined;
93
+ /** Cumulative analysis depth for the final M1 surfaces. */
94
+ readonly depth?: WardenDepth | undefined;
95
+ /** Draft-state handling mode for final M1 surfaces. */
96
+ readonly drafts?: EffectiveWardenConfig['drafts'] | undefined;
97
+ /** Failure threshold used to compute `report.passed`. */
98
+ readonly failOn?: WardenFailOn | undefined;
99
+ /**
100
+ * Apply safe source fixes among the run's diagnostics, writing changed files.
101
+ *
102
+ * Only `safety: 'safe'` fixes with concrete edits are applied; review-required,
103
+ * edit-less, and topo diagnostics stay reported but unapplied.
104
+ */
105
+ readonly fix?: boolean | undefined;
106
+ /** Output format requested by the caller. */
107
+ readonly format?: WardenFormat | undefined;
108
+ /** Lockfile mode requested by the caller. */
109
+ readonly lock?: WardenLockMode | undefined;
110
+ /** Suppress lockfile mutation for CI/pre-push callers. */
111
+ readonly noLockMutation?: boolean | undefined;
112
+ /** Environment layer for config resolution. Pass `process.env` at process boundaries. */
113
+ readonly env?: Record<string, string | undefined> | undefined;
34
114
  /** Only run lint rules, skip drift detection */
35
115
  readonly lintOnly?: boolean | undefined;
36
116
  /** Only run drift detection, skip lint rules */
37
117
  readonly driftOnly?: boolean | undefined;
38
- /** App topology for drift detection. When provided, enables real surface lock comparison. */
118
+ /**
119
+ * Run a single Warden tier. Defaults to all lint tiers plus drift.
120
+ *
121
+ * Selecting a non-drift tier skips drift detection; selecting `drift` skips
122
+ * lint rule dispatch. `lintOnly` and `driftOnly` remain compatibility shims.
123
+ */
124
+ readonly tier?: WardenRuleTier | undefined;
125
+ /**
126
+ * Load project-local Warden rules from `.trails/rules.ts` or `.trails/rules/`.
127
+ *
128
+ * Enabled by default for normal runs so a Trails app can carry migration or
129
+ * repo-local governance with the project instead of shipping it from
130
+ * `@ontrails/warden`. Set to `false` for narrow tests or embedders that need
131
+ * only built-in and explicitly provided rules.
132
+ */
133
+ readonly projectRules?: boolean | undefined;
134
+ /**
135
+ * App topology for drift detection. When provided, enables real topology
136
+ * drift comparison and unlocks the topo-aware rule dispatch path.
137
+ *
138
+ * @remarks
139
+ * Topo-aware rules (both built-in `wardenTopoRules` and `extraTopoRules`)
140
+ * only fire when a `Topo` is supplied. Runs without a topo silently skip
141
+ * topo-aware dispatch — callers that depend on a topo-aware rule firing
142
+ * must pass `topo` explicitly.
143
+ */
39
144
  readonly topo?: Topo | undefined;
145
+ /**
146
+ * Multiple resolved topos to govern in one invocation.
147
+ *
148
+ * Source/project rules run once; topo-aware rules run once per target.
149
+ */
150
+ readonly topos?: readonly WardenTopoTarget[] | undefined;
151
+ /**
152
+ * Extra topo-aware rules to run in addition to the built-in registry.
153
+ *
154
+ * Primarily a test hook — production callers should register rules via
155
+ * `wardenTopoRules` in `rules/index.ts`. These rules are only invoked
156
+ * when `topo` is also supplied (see `topo` remarks).
157
+ */
158
+ readonly extraTopoRules?: readonly TopoAwareWardenRule[] | undefined;
159
+ /**
160
+ * Extra source rules to run in addition to the built-in registry.
161
+ *
162
+ * Primarily a test hook — production callers should register durable rules
163
+ * via `wardenRules` in `rules/index.ts`.
164
+ */
165
+ readonly extraSourceRules?: readonly WardenRule[] | undefined;
166
+ }
167
+
168
+ /** Backwards-compatible name for older consumers. */
169
+ export type WardenOptions = WardenRunOptions;
170
+
171
+ /**
172
+ * Aggregate outcome of a `--fix` pass over a run's diagnostics.
173
+ */
174
+ export interface WardenFixSummary {
175
+ /** Diagnostics whose safe fix was applied to source. */
176
+ readonly applied: number;
177
+ /** Source files rewritten with patched content. */
178
+ readonly filesChanged: number;
179
+ /** Diagnostics carrying fix metadata left unapplied (review or edit-less). */
180
+ readonly skipped: number;
181
+ }
182
+
183
+ export interface WardenFixApplication extends WardenFixSummary {
184
+ /** Diagnostics removed from the final report because their safe fix applied. */
185
+ readonly appliedDiagnostics: readonly WardenDiagnostic[];
40
186
  }
41
187
 
42
188
  /**
@@ -53,33 +199,122 @@ export interface WardenReport {
53
199
  readonly drift: DriftResult | null;
54
200
  /** Whether the warden run passed (no errors, no drift) */
55
201
  readonly passed: boolean;
202
+ /** Effective shared config consumed by this run. */
203
+ readonly effectiveConfig?: EffectiveWardenConfig | undefined;
204
+ /** Resolved topo/app labels governed by this run. */
205
+ readonly topoNames?: readonly string[] | undefined;
206
+ /** Safe-fix application summary, present only when a `--fix` pass ran. */
207
+ readonly fixes?: WardenFixSummary | undefined;
56
208
  }
57
209
 
58
210
  /**
59
- * Collect all .ts files under a directory, excluding node_modules, dist, and .git.
211
+ * Collect Warden scan targets under a directory, excluding generated and test
212
+ * surfaces that should not contribute most committed-source diagnostics.
60
213
  */
61
- const isSourceFile = (match: string): boolean =>
62
- !match.endsWith('.d.ts') &&
63
- !match.startsWith('node_modules/') &&
64
- !match.startsWith('dist/') &&
65
- !match.startsWith('.git/') &&
66
- !match.includes('__tests__/') &&
67
- !match.includes('__test__/') &&
68
- !match.endsWith('.test.ts') &&
69
- !match.endsWith('.spec.ts');
70
-
71
- const collectTsFiles = (dir: string): readonly string[] => {
214
+ const collectFilesMatching = (
215
+ dir: string,
216
+ pattern: string,
217
+ dot = false
218
+ ): readonly string[] => {
219
+ const glob = new Bun.Glob(pattern);
220
+ let matches: IterableIterator<string>;
221
+ try {
222
+ matches = glob.scanSync({ cwd: dir, dot, onlyFiles: true });
223
+ } catch {
224
+ return [];
225
+ }
226
+
227
+ const files: string[] = [];
228
+ for (const match of matches) {
229
+ if (isWardenSourceScanTarget(match)) {
230
+ files.push(`${dir}/${match}`);
231
+ }
232
+ }
233
+ return files;
234
+ };
235
+
236
+ const collectTsFiles = (dir: string): readonly string[] =>
237
+ collectFilesMatching(dir, '**/*.ts');
238
+
239
+ const draftModeIncludesFile = (
240
+ filePath: string,
241
+ drafts: EffectiveWardenConfig['drafts']
242
+ ): boolean => {
243
+ const isDraftFile = isDraftMarkedFile(filePath);
244
+ if (drafts === 'exclude') {
245
+ return !isDraftFile;
246
+ }
247
+ if (drafts === 'only') {
248
+ return isDraftFile;
249
+ }
250
+ return true;
251
+ };
252
+
253
+ const filterSourceFilesByDraftMode = (
254
+ sourceFiles: readonly SourceFile[],
255
+ drafts: EffectiveWardenConfig['drafts']
256
+ ): readonly SourceFile[] =>
257
+ drafts === 'include'
258
+ ? sourceFiles
259
+ : sourceFiles.filter((sourceFile) =>
260
+ draftModeIncludesFile(sourceFile.filePath, drafts)
261
+ );
262
+
263
+ const collectDevPermitTestFiles = (dir: string): readonly string[] => {
72
264
  const glob = new Bun.Glob('**/*.ts');
73
265
  let matches: IterableIterator<string>;
74
266
  try {
75
- matches = glob.scanSync({ cwd: dir, dot: false, onlyFiles: true });
267
+ matches = glob.scanSync({ cwd: dir, onlyFiles: true });
268
+ } catch {
269
+ return [];
270
+ }
271
+
272
+ const files: string[] = [];
273
+ for (const match of matches) {
274
+ if (isWardenDevPermitTestScanTarget(match)) {
275
+ files.push(`${dir}/${match}`);
276
+ }
277
+ }
278
+ return files;
279
+ };
280
+
281
+ const collectTextScanFiles = (dir: string): readonly string[] => [
282
+ ...collectFilesMatching(dir, '**/*.sh', true),
283
+ ...collectFilesMatching(dir, '**/*.bash', true),
284
+ ...collectFilesMatching(dir, '**/*.zsh', true),
285
+ ...collectFilesMatching(dir, '**/*.yml', true),
286
+ ...collectFilesMatching(dir, '**/*.yaml', true),
287
+ ...collectFilesMatching(dir, '**/package.json', true),
288
+ ];
289
+
290
+ const isDocumentationScanTarget = (match: string): boolean => {
291
+ if (match === 'README.md') {
292
+ return true;
293
+ }
294
+ if (/^(?:packages|adapters|apps)\/[^/]+\/README\.md$/.test(match)) {
295
+ return true;
296
+ }
297
+ return (
298
+ match.startsWith('docs/') &&
299
+ !match.startsWith('docs/adr/') &&
300
+ !match.startsWith('docs/migration/') &&
301
+ !match.startsWith('docs/releases/') &&
302
+ match.endsWith('.md')
303
+ );
304
+ };
305
+
306
+ const collectDocumentationFiles = (dir: string): readonly string[] => {
307
+ const glob = new Bun.Glob('**/*.md');
308
+ let matches: IterableIterator<string>;
309
+ try {
310
+ matches = glob.scanSync({ cwd: dir, onlyFiles: true });
76
311
  } catch {
77
312
  return [];
78
313
  }
79
314
 
80
315
  const files: string[] = [];
81
316
  for (const match of matches) {
82
- if (isSourceFile(match)) {
317
+ if (isWardenSourceScanTarget(match) && isDocumentationScanTarget(match)) {
83
318
  files.push(`${dir}/${match}`);
84
319
  }
85
320
  }
@@ -88,9 +323,136 @@ const collectTsFiles = (dir: string): readonly string[] => {
88
323
 
89
324
  interface SourceFile {
90
325
  readonly filePath: string;
326
+ readonly kind: 'documentation' | 'text' | 'typescript';
91
327
  readonly sourceCode: string;
92
328
  }
93
329
 
330
+ interface MutableProjectContext {
331
+ contourReferencesByName: Map<string, Set<string>>;
332
+ crudTableIds: Set<string>;
333
+ composeTargetTrailIds: Set<string>;
334
+ crudCoverageByEntity: Map<string, Set<string>>;
335
+ knownContourIds: Set<string>;
336
+ knownResourceIds: Set<string>;
337
+ knownSignalIds: Set<string>;
338
+ knownTrailIds: Set<string>;
339
+ topoTrailIds: Set<string>;
340
+ importResolutionsByFile: Map<string, readonly WardenImportResolution[]>;
341
+ documentedImportResolutionsByFile: Map<
342
+ string,
343
+ readonly WardenImportResolution[]
344
+ >;
345
+ onTargetSignalIds: Set<string>;
346
+ publicWorkspaces: ReturnType<typeof collectPublicWorkspaces>;
347
+ reconcileTableIds: Set<string>;
348
+ trailIntentsById: Map<string, 'destroy' | 'read' | 'write'>;
349
+ }
350
+
351
+ const createMutableProjectContext = (): MutableProjectContext => ({
352
+ composeTargetTrailIds: new Set<string>(),
353
+ contourReferencesByName: new Map<string, Set<string>>(),
354
+ crudCoverageByEntity: new Map<string, Set<string>>(),
355
+ crudTableIds: new Set<string>(),
356
+ documentedImportResolutionsByFile: new Map<
357
+ string,
358
+ readonly WardenImportResolution[]
359
+ >(),
360
+ importResolutionsByFile: new Map<string, readonly WardenImportResolution[]>(),
361
+ knownContourIds: new Set<string>(),
362
+ knownResourceIds: new Set<string>(),
363
+ knownSignalIds: new Set<string>(),
364
+ knownTrailIds: new Set<string>(),
365
+ onTargetSignalIds: new Set<string>(),
366
+ publicWorkspaces: new Map(),
367
+ reconcileTableIds: new Set<string>(),
368
+ topoTrailIds: new Set<string>(),
369
+ trailIntentsById: new Map<string, 'destroy' | 'read' | 'write'>(),
370
+ });
371
+
372
+ const addContourReferenceTargets = (
373
+ context: MutableProjectContext,
374
+ contourName: string,
375
+ targets: readonly string[]
376
+ ): void => {
377
+ const existing = context.contourReferencesByName.get(contourName);
378
+ if (existing) {
379
+ for (const target of targets) {
380
+ existing.add(target);
381
+ }
382
+ return;
383
+ }
384
+
385
+ context.contourReferencesByName.set(contourName, new Set(targets));
386
+ };
387
+
388
+ const toProjectContext = (context: MutableProjectContext): ProjectContext => ({
389
+ ...(context.contourReferencesByName.size > 0
390
+ ? {
391
+ contourReferencesByName: new Map(
392
+ [...context.contourReferencesByName.entries()].map(
393
+ ([name, targets]) => [name, [...targets]]
394
+ )
395
+ ),
396
+ }
397
+ : {}),
398
+ ...(context.crudTableIds.size > 0
399
+ ? { crudTableIds: context.crudTableIds }
400
+ : {}),
401
+ ...(context.crudCoverageByEntity.size > 0
402
+ ? {
403
+ crudCoverageByEntity: new Map(
404
+ [...context.crudCoverageByEntity.entries()].map(
405
+ ([entityId, operations]) => [
406
+ entityId,
407
+ new Set(operations) as ReadonlySet<string>,
408
+ ]
409
+ )
410
+ ),
411
+ }
412
+ : {}),
413
+ composeTargetTrailIds: context.composeTargetTrailIds,
414
+ knownContourIds: context.knownContourIds,
415
+ knownResourceIds: context.knownResourceIds,
416
+ knownSignalIds: context.knownSignalIds,
417
+ knownTrailIds: context.knownTrailIds,
418
+ ...(context.topoTrailIds.size > 0
419
+ ? { topoTrailIds: context.topoTrailIds }
420
+ : {}),
421
+ ...(context.importResolutionsByFile.size > 0
422
+ ? { importResolutionsByFile: context.importResolutionsByFile }
423
+ : {}),
424
+ ...(context.documentedImportResolutionsByFile.size > 0
425
+ ? {
426
+ documentedImportResolutionsByFile:
427
+ context.documentedImportResolutionsByFile,
428
+ }
429
+ : {}),
430
+ ...(context.onTargetSignalIds.size > 0
431
+ ? { onTargetSignalIds: context.onTargetSignalIds }
432
+ : {}),
433
+ ...(context.publicWorkspaces.size > 0
434
+ ? { publicWorkspaces: context.publicWorkspaces }
435
+ : {}),
436
+ ...(context.reconcileTableIds.size > 0
437
+ ? { reconcileTableIds: context.reconcileTableIds }
438
+ : {}),
439
+ trailIntentsById: context.trailIntentsById,
440
+ });
441
+
442
+ const collectKnownContourIds = (
443
+ sourceCode: string,
444
+ filePath: string,
445
+ knownContourIds: Set<string>
446
+ ): void => {
447
+ const ast = parse(filePath, sourceCode);
448
+ if (!ast) {
449
+ return;
450
+ }
451
+ for (const id of collectContourDefinitionIds(ast)) {
452
+ knownContourIds.add(id);
453
+ }
454
+ };
455
+
94
456
  const collectKnownTrailIds = (
95
457
  sourceCode: string,
96
458
  filePath: string,
@@ -105,30 +467,122 @@ const collectKnownTrailIds = (
105
467
  }
106
468
  };
107
469
 
108
- const collectDetourTargetTrailIds = (
470
+ const collectComposedTrailIds = (
109
471
  sourceCode: string,
110
472
  filePath: string,
111
- detourTargetTrailIds: Set<string>
473
+ composeTargetTrailIds: Set<string>
112
474
  ): void => {
113
475
  const ast = parse(filePath, sourceCode);
114
476
  if (!ast) {
115
477
  return;
116
478
  }
117
- for (const def of findTrailDefinitions(ast)) {
118
- const detoursProp = findConfigProperty(def.config, 'detours');
119
- if (!detoursProp) {
120
- continue;
479
+ for (const id of collectComposeTargetTrailIds(ast, sourceCode)) {
480
+ composeTargetTrailIds.add(id);
481
+ }
482
+ };
483
+
484
+ const collectKnownResourceIds = (
485
+ sourceCode: string,
486
+ filePath: string,
487
+ knownResourceIds: Set<string>
488
+ ): void => {
489
+ const ast = parse(filePath, sourceCode);
490
+ if (!ast) {
491
+ return;
492
+ }
493
+ for (const id of collectResourceDefinitionIds(ast)) {
494
+ knownResourceIds.add(id);
495
+ }
496
+ };
497
+
498
+ const collectKnownSignalIds = (
499
+ sourceCode: string,
500
+ filePath: string,
501
+ knownSignalIds: Set<string>
502
+ ): void => {
503
+ const ast = parse(filePath, sourceCode);
504
+ if (!ast) {
505
+ return;
506
+ }
507
+ for (const id of collectSignalDefinitionIds(ast)) {
508
+ knownSignalIds.add(id);
509
+ }
510
+ };
511
+
512
+ const collectTrailIntents = (
513
+ sourceCode: string,
514
+ filePath: string,
515
+ trailIntentsById: Map<string, 'destroy' | 'read' | 'write'>
516
+ ): void => {
517
+ const ast = parse(filePath, sourceCode);
518
+ if (!ast) {
519
+ return;
520
+ }
521
+ for (const [id, intent] of collectTrailIntentsById(ast)) {
522
+ trailIntentsById.set(id, intent);
523
+ }
524
+ };
525
+
526
+ const collectCrudTableIds = (
527
+ sourceCode: string,
528
+ filePath: string,
529
+ crudTableIds: Set<string>
530
+ ): void => {
531
+ const ast = parse(filePath, sourceCode);
532
+ if (!ast) {
533
+ return;
534
+ }
535
+ for (const id of collectCrudTableIdsFromAst(ast)) {
536
+ crudTableIds.add(id);
537
+ }
538
+ };
539
+
540
+ const collectOnTargetSignalIds = (
541
+ sourceCode: string,
542
+ filePath: string,
543
+ onTargetSignalIds: Set<string>
544
+ ): void => {
545
+ const ast = parse(filePath, sourceCode);
546
+ if (!ast) {
547
+ return;
548
+ }
549
+ for (const id of collectOnTargetSignalIdsFromAst(ast, sourceCode)) {
550
+ onTargetSignalIds.add(id);
551
+ }
552
+ };
553
+
554
+ const collectCrudCoverageByEntity = (
555
+ sourceCode: string,
556
+ filePath: string,
557
+ coverageByEntity: Map<string, Set<string>>
558
+ ): void => {
559
+ const ast = parse(filePath, sourceCode);
560
+ if (!ast) {
561
+ return;
562
+ }
563
+ for (const [entityId, operations] of collectFileCrudCoverage(
564
+ ast,
565
+ sourceCode
566
+ )) {
567
+ const bucket = coverageByEntity.get(entityId) ?? new Set<string>();
568
+ for (const operation of operations) {
569
+ bucket.add(operation);
121
570
  }
122
- // Walk the detours value for string literals that look like trail IDs
123
- walk(detoursProp, (node) => {
124
- if (node.type !== 'Literal') {
125
- return;
126
- }
127
- const val = (node as unknown as { value?: string }).value;
128
- if (val && val.includes('.')) {
129
- detourTargetTrailIds.add(val);
130
- }
131
- });
571
+ coverageByEntity.set(entityId, bucket);
572
+ }
573
+ };
574
+
575
+ const collectReconcileTableIds = (
576
+ sourceCode: string,
577
+ filePath: string,
578
+ reconcileTableIds: Set<string>
579
+ ): void => {
580
+ const ast = parse(filePath, sourceCode);
581
+ if (!ast) {
582
+ return;
583
+ }
584
+ for (const id of collectReconcileTableIdsFromAst(ast)) {
585
+ reconcileTableIds.add(id);
132
586
  }
133
587
  };
134
588
 
@@ -141,6 +595,7 @@ const loadSourceFiles = async (
141
595
  try {
142
596
  sourceFiles.push({
143
597
  filePath,
598
+ kind: 'typescript',
144
599
  sourceCode: await Bun.file(filePath).text(),
145
600
  });
146
601
  } catch {
@@ -148,78 +603,479 @@ const loadSourceFiles = async (
148
603
  }
149
604
  }
150
605
 
151
- return sourceFiles;
152
- };
606
+ for (const filePath of collectTextScanFiles(rootDir)) {
607
+ try {
608
+ sourceFiles.push({
609
+ filePath,
610
+ kind: 'text',
611
+ sourceCode: await Bun.file(filePath).text(),
612
+ });
613
+ } catch {
614
+ continue;
615
+ }
616
+ }
153
617
 
154
- const buildProjectContextFromTopo = (appTopo: Topo): ProjectContext => {
155
- const knownTrailIds = new Set<string>([
156
- ...appTopo.trails.keys(),
157
- ...appTopo.hikes.keys(),
158
- ]);
618
+ for (const filePath of collectDocumentationFiles(rootDir)) {
619
+ try {
620
+ sourceFiles.push({
621
+ filePath,
622
+ kind: 'documentation',
623
+ sourceCode: await Bun.file(filePath).text(),
624
+ });
625
+ } catch {
626
+ continue;
627
+ }
628
+ }
159
629
 
160
- const detourTargetTrailIds = new Set<string>();
161
- for (const t of [...appTopo.trails.values(), ...appTopo.hikes.values()]) {
162
- const detours = (t as unknown as Record<string, unknown>)['detours'] as
163
- | Readonly<Record<string, readonly string[]>>
164
- | undefined;
165
- if (!detours) {
630
+ for (const filePath of collectDevPermitTestFiles(rootDir)) {
631
+ try {
632
+ sourceFiles.push({
633
+ filePath,
634
+ kind: 'text',
635
+ sourceCode: await Bun.file(filePath).text(),
636
+ });
637
+ } catch {
166
638
  continue;
167
639
  }
168
- for (const targets of Object.values(detours)) {
169
- for (const id of targets) {
170
- detourTargetTrailIds.add(id);
171
- }
640
+ }
641
+
642
+ return sourceFiles;
643
+ };
644
+
645
+ const collectTopoKnownIds = (
646
+ appTopo: Topo,
647
+ context: MutableProjectContext
648
+ ): void => {
649
+ for (const name of appTopo.contours.keys()) {
650
+ context.knownContourIds.add(name);
651
+ }
652
+
653
+ for (const id of appTopo.trails.keys()) {
654
+ context.knownTrailIds.add(id);
655
+ context.topoTrailIds.add(id);
656
+ }
657
+
658
+ for (const id of appTopo.resources.keys()) {
659
+ context.knownResourceIds.add(id);
660
+ }
661
+
662
+ for (const id of appTopo.signals.keys()) {
663
+ context.knownSignalIds.add(id);
664
+ }
665
+ };
666
+
667
+ const collectTopoComposesAndIntents = (
668
+ appTopo: Topo,
669
+ context: MutableProjectContext
670
+ ): void => {
671
+ for (const trail of appTopo.trails.values()) {
672
+ context.trailIntentsById.set(trail.id, trail.intent);
673
+ for (const composedTrailId of trail.composes) {
674
+ context.composeTargetTrailIds.add(composedTrailId);
172
675
  }
173
676
  }
677
+ };
174
678
 
175
- return { detourTargetTrailIds, knownTrailIds };
679
+ const collectTopoContourReferences = (
680
+ appTopo: Topo,
681
+ context: MutableProjectContext
682
+ ): void => {
683
+ for (const contour of appTopo.listContours()) {
684
+ addContourReferenceTargets(
685
+ context,
686
+ contour.name,
687
+ getContourReferences(contour).map((reference) => reference.contour)
688
+ );
689
+ }
176
690
  };
177
691
 
178
- const buildProjectContextFromFiles = (
179
- sourceFiles: readonly SourceFile[]
692
+ const collectTopoTrailContext = (
693
+ appTopo: Topo,
694
+ context: MutableProjectContext
695
+ ): void => {
696
+ collectTopoKnownIds(appTopo, context);
697
+ collectTopoComposesAndIntents(appTopo, context);
698
+ collectTopoContourReferences(appTopo, context);
699
+ };
700
+
701
+ const collectFileKnownIds = (
702
+ sourceFile: SourceFile,
703
+ context: MutableProjectContext
704
+ ): void => {
705
+ collectKnownContourIds(
706
+ sourceFile.sourceCode,
707
+ sourceFile.filePath,
708
+ context.knownContourIds
709
+ );
710
+ collectKnownTrailIds(
711
+ sourceFile.sourceCode,
712
+ sourceFile.filePath,
713
+ context.knownTrailIds
714
+ );
715
+ collectKnownResourceIds(
716
+ sourceFile.sourceCode,
717
+ sourceFile.filePath,
718
+ context.knownResourceIds
719
+ );
720
+ collectKnownSignalIds(
721
+ sourceFile.sourceCode,
722
+ sourceFile.filePath,
723
+ context.knownSignalIds
724
+ );
725
+ };
726
+
727
+ const collectFileTrailRelationships = (
728
+ sourceFile: SourceFile,
729
+ context: MutableProjectContext
730
+ ): void => {
731
+ collectComposedTrailIds(
732
+ sourceFile.sourceCode,
733
+ sourceFile.filePath,
734
+ context.composeTargetTrailIds
735
+ );
736
+ collectTrailIntents(
737
+ sourceFile.sourceCode,
738
+ sourceFile.filePath,
739
+ context.trailIntentsById
740
+ );
741
+ };
742
+
743
+ const collectFileSupplementalProjectContext = (
744
+ sourceFile: SourceFile,
745
+ context: MutableProjectContext
746
+ ): void => {
747
+ collectCrudTableIds(
748
+ sourceFile.sourceCode,
749
+ sourceFile.filePath,
750
+ context.crudTableIds
751
+ );
752
+ collectOnTargetSignalIds(
753
+ sourceFile.sourceCode,
754
+ sourceFile.filePath,
755
+ context.onTargetSignalIds
756
+ );
757
+ collectReconcileTableIds(
758
+ sourceFile.sourceCode,
759
+ sourceFile.filePath,
760
+ context.reconcileTableIds
761
+ );
762
+ collectCrudCoverageByEntity(
763
+ sourceFile.sourceCode,
764
+ sourceFile.filePath,
765
+ context.crudCoverageByEntity
766
+ );
767
+ };
768
+
769
+ const collectFileProjectContext = (
770
+ sourceFile: SourceFile,
771
+ context: MutableProjectContext
772
+ ): void => {
773
+ collectFileKnownIds(sourceFile, context);
774
+ collectFileTrailRelationships(sourceFile, context);
775
+ collectFileSupplementalProjectContext(sourceFile, context);
776
+ };
777
+
778
+ const collectFileContourReferences = (
779
+ sourceFile: SourceFile,
780
+ context: MutableProjectContext
781
+ ): void => {
782
+ const ast = parse(sourceFile.filePath, sourceFile.sourceCode);
783
+ if (!ast) {
784
+ return;
785
+ }
786
+
787
+ const referencesByName = collectContourReferenceTargetsByName(
788
+ ast,
789
+ context.knownContourIds
790
+ );
791
+ for (const [contourName, targets] of referencesByName) {
792
+ addContourReferenceTargets(context, contourName, targets);
793
+ }
794
+ };
795
+
796
+ const collectFileImportResolutions = (
797
+ rootDir: string,
798
+ sourceFiles: readonly SourceFile[],
799
+ context: MutableProjectContext
800
+ ): void => {
801
+ const resolutionsByFile = collectProjectImportResolutions({
802
+ rootDir,
803
+ sourceFiles,
804
+ });
805
+ for (const [filePath, resolutions] of resolutionsByFile) {
806
+ context.importResolutionsByFile.set(filePath, resolutions);
807
+ }
808
+ };
809
+
810
+ const collectFileDocumentedImportResolutions = (
811
+ rootDir: string,
812
+ sourceFiles: readonly SourceFile[],
813
+ context: MutableProjectContext
814
+ ): void => {
815
+ const resolutionsByFile = collectProjectDocumentationImportResolutions({
816
+ rootDir,
817
+ sourceFiles,
818
+ });
819
+ for (const [filePath, resolutions] of resolutionsByFile) {
820
+ context.documentedImportResolutionsByFile.set(filePath, resolutions);
821
+ }
822
+ };
823
+
824
+ const buildProjectContext = (
825
+ sourceFiles: readonly SourceFile[],
826
+ rootDir: string,
827
+ appTopos: readonly Topo[] = []
180
828
  ): ProjectContext => {
181
- const knownTrailIds = new Set<string>();
182
- const detourTargetTrailIds = new Set<string>();
829
+ const context = createMutableProjectContext();
830
+ const typeScriptSourceFiles = sourceFiles.filter(
831
+ (sourceFile) => sourceFile.kind === 'typescript'
832
+ );
833
+ const documentationSourceFiles = sourceFiles.filter(
834
+ (sourceFile) => sourceFile.kind === 'documentation'
835
+ );
836
+ context.publicWorkspaces = collectPublicWorkspaces(rootDir);
183
837
 
184
- for (const sourceFile of sourceFiles) {
185
- collectKnownTrailIds(
186
- sourceFile.sourceCode,
187
- sourceFile.filePath,
188
- knownTrailIds
189
- );
190
- collectDetourTargetTrailIds(
191
- sourceFile.sourceCode,
192
- sourceFile.filePath,
193
- detourTargetTrailIds
194
- );
838
+ if (appTopos.length > 0) {
839
+ for (const appTopo of appTopos) {
840
+ collectTopoTrailContext(appTopo, context);
841
+ }
842
+ for (const sourceFile of typeScriptSourceFiles) {
843
+ collectFileSupplementalProjectContext(sourceFile, context);
844
+ }
845
+ } else {
846
+ for (const sourceFile of typeScriptSourceFiles) {
847
+ collectFileProjectContext(sourceFile, context);
848
+ }
195
849
  }
196
850
 
197
- return {
198
- detourTargetTrailIds,
199
- knownTrailIds,
200
- };
851
+ for (const sourceFile of typeScriptSourceFiles) {
852
+ collectFileContourReferences(sourceFile, context);
853
+ }
854
+ collectFileImportResolutions(rootDir, typeScriptSourceFiles, context);
855
+ collectFileDocumentedImportResolutions(
856
+ rootDir,
857
+ documentationSourceFiles,
858
+ context
859
+ );
860
+
861
+ return toProjectContext(context);
201
862
  };
202
863
 
203
864
  const isProjectAwareRule = (rule: WardenRule): rule is ProjectAwareWardenRule =>
204
865
  'checkWithContext' in rule;
205
866
 
867
+ const createOptionsDiagnostic = (message: string): WardenDiagnostic => ({
868
+ filePath: '<warden-options>',
869
+ line: 1,
870
+ message,
871
+ rule: 'warden-options',
872
+ severity: 'error',
873
+ });
874
+
875
+ const emptyProjectWardenRules = (): ProjectWardenRules => ({
876
+ diagnostics: [],
877
+ sourceRules: [],
878
+ topoRules: [],
879
+ });
880
+
881
+ const loadProjectRulesForRun = async (
882
+ rootDir: string,
883
+ options: WardenRunOptions,
884
+ runLint: boolean
885
+ ): Promise<ProjectWardenRules> => {
886
+ if (!runLint || options.projectRules === false) {
887
+ return emptyProjectWardenRules();
888
+ }
889
+ return loadProjectWardenRules(rootDir);
890
+ };
891
+
892
+ interface WardenRuleSelector {
893
+ readonly depth?: WardenDepth | undefined;
894
+ readonly tier?: WardenRuleTier | undefined;
895
+ }
896
+
897
+ const depthIncludesTier = (
898
+ depth: WardenDepth,
899
+ tier: WardenRuleTier
900
+ ): boolean => {
901
+ switch (depth) {
902
+ case 'source': {
903
+ return tier === 'source-static';
904
+ }
905
+ case 'project': {
906
+ return tier === 'source-static' || tier === 'project-static';
907
+ }
908
+ case 'topo': {
909
+ return (
910
+ tier === 'source-static' ||
911
+ tier === 'project-static' ||
912
+ tier === 'topo-aware'
913
+ );
914
+ }
915
+ case 'all': {
916
+ return true;
917
+ }
918
+ default: {
919
+ return false;
920
+ }
921
+ }
922
+ };
923
+
924
+ const ruleMatchesTier = (
925
+ metadata: ReturnType<typeof getWardenRuleMetadata>,
926
+ tier: WardenRuleTier | undefined
927
+ ): boolean => {
928
+ if (!tier) {
929
+ return true;
930
+ }
931
+
932
+ if (!metadata) {
933
+ return false;
934
+ }
935
+
936
+ return tier === 'advisory'
937
+ ? metadata.scope === 'advisory'
938
+ : metadata.tier === tier;
939
+ };
940
+
941
+ const ruleMatchesDepth = (
942
+ metadata: ReturnType<typeof getWardenRuleMetadata>,
943
+ depth: WardenDepth | undefined
944
+ ): boolean => {
945
+ if (!depth) {
946
+ return true;
947
+ }
948
+
949
+ if (!metadata) {
950
+ return false;
951
+ }
952
+
953
+ if (metadata.scope === 'advisory') {
954
+ return depth === 'all';
955
+ }
956
+
957
+ return depthIncludesTier(depth, metadata.tier);
958
+ };
959
+
960
+ const isSelectedRule = (
961
+ rule: WardenRule | TopoAwareWardenRule,
962
+ selector: WardenRuleSelector
963
+ ): boolean => {
964
+ const metadata = getWardenRuleMetadata(rule);
965
+ return selector.tier
966
+ ? ruleMatchesTier(metadata, selector.tier)
967
+ : ruleMatchesDepth(metadata, selector.depth);
968
+ };
969
+
970
+ const isSelectedTopoRule = (
971
+ rule: TopoAwareWardenRule,
972
+ selector: WardenRuleSelector
973
+ ): boolean => {
974
+ const metadata = getWardenRuleMetadata(rule);
975
+ if (selector.tier) {
976
+ return metadata
977
+ ? ruleMatchesTier(metadata, selector.tier)
978
+ : selector.tier === 'topo-aware';
979
+ }
980
+
981
+ return metadata ? ruleMatchesDepth(metadata, selector.depth) : true;
982
+ };
983
+
984
+ const withDiagnosticGuidance = (
985
+ diagnostic: WardenDiagnostic
986
+ ): WardenDiagnostic => {
987
+ if (diagnostic.guidance !== undefined) {
988
+ return diagnostic;
989
+ }
990
+
991
+ const guidance = getWardenRuleMetadata(diagnostic.rule)?.guidance;
992
+ return guidance === undefined ? diagnostic : { ...diagnostic, guidance };
993
+ };
994
+
995
+ const topoRuleFailureDiagnostic = (
996
+ rule: TopoAwareWardenRule,
997
+ error: unknown
998
+ ): WardenDiagnostic => {
999
+ const cause = error instanceof Error ? error : new Error(String(error));
1000
+ return {
1001
+ filePath: '<topo>',
1002
+ line: 1,
1003
+ message: `Topo-aware rule "${rule.name}" threw: ${cause.message}`,
1004
+ rule: rule.name,
1005
+ severity: 'error',
1006
+ };
1007
+ };
1008
+
206
1009
  /**
207
- * Lint all files against all warden rules.
1010
+ * Run all registered topo-aware rules against the resolved topo.
1011
+ *
1012
+ * Topo-aware rules fire exactly once per run (not per file) because they
1013
+ * inspect the compiled trail graph, not source text.
208
1014
  */
209
- const lintFiles = async (
210
- rootDir: string,
211
- appTopo?: Topo | undefined
212
- ): Promise<WardenDiagnostic[]> => {
213
- const allDiagnostics: WardenDiagnostic[] = [];
214
- const sourceFiles = await loadSourceFiles(rootDir);
215
- const context = appTopo
216
- ? buildProjectContextFromTopo(appTopo)
217
- : buildProjectContextFromFiles(sourceFiles);
1015
+ const lintTopo = async (
1016
+ appTopo: Topo,
1017
+ graph: TopoGraph | undefined,
1018
+ extraTopoRules: readonly TopoAwareWardenRule[],
1019
+ selector: WardenRuleSelector
1020
+ ): Promise<readonly WardenDiagnostic[]> => {
1021
+ const diagnostics: WardenDiagnostic[] = [];
1022
+ const rules: readonly TopoAwareWardenRule[] = [
1023
+ ...wardenTopoRules.values(),
1024
+ ...extraTopoRules,
1025
+ ].filter((rule) => isSelectedTopoRule(rule, selector));
1026
+ let contextGraph: TopoGraph;
1027
+ try {
1028
+ contextGraph = graph ?? deriveTopoGraph(appTopo);
1029
+ } catch (error) {
1030
+ for (const rule of rules) {
1031
+ diagnostics.push(topoRuleFailureDiagnostic(rule, error));
1032
+ }
1033
+ return diagnostics;
1034
+ }
1035
+
1036
+ for (const rule of rules) {
1037
+ try {
1038
+ diagnostics.push(
1039
+ ...(await rule.checkTopo(appTopo, { graph: contextGraph }))
1040
+ );
1041
+ } catch (error) {
1042
+ diagnostics.push(topoRuleFailureDiagnostic(rule, error));
1043
+ }
1044
+ }
1045
+ return diagnostics;
1046
+ };
218
1047
 
1048
+ const lintSourceFiles = (
1049
+ sourceFiles: readonly SourceFile[],
1050
+ context: ProjectContext,
1051
+ extraSourceRules: readonly WardenRule[],
1052
+ selector: WardenRuleSelector
1053
+ ): readonly WardenDiagnostic[] => {
1054
+ const diagnostics: WardenDiagnostic[] = [];
1055
+ const rules = [...wardenRules.values(), ...extraSourceRules];
219
1056
  for (const sourceFile of sourceFiles) {
220
- for (const rule of wardenRules.values()) {
1057
+ for (const rule of rules) {
1058
+ if (
1059
+ sourceFile.kind === 'text' &&
1060
+ rule.name !== 'no-dev-permit-in-source' &&
1061
+ rule.name !== 'public-internal-deep-imports'
1062
+ ) {
1063
+ continue;
1064
+ }
1065
+
1066
+ if (
1067
+ sourceFile.kind === 'documentation' &&
1068
+ rule.name !== 'public-internal-deep-imports'
1069
+ ) {
1070
+ continue;
1071
+ }
1072
+
1073
+ if (!isSelectedRule(rule, selector)) {
1074
+ continue;
1075
+ }
1076
+
221
1077
  if (isProjectAwareRule(rule)) {
222
- allDiagnostics.push(
1078
+ diagnostics.push(
223
1079
  ...rule.checkWithContext(
224
1080
  sourceFile.sourceCode,
225
1081
  sourceFile.filePath,
@@ -228,44 +1084,472 @@ const lintFiles = async (
228
1084
  );
229
1085
  continue;
230
1086
  }
231
-
232
- allDiagnostics.push(
1087
+ diagnostics.push(
233
1088
  ...rule.check(sourceFile.sourceCode, sourceFile.filePath)
234
1089
  );
235
1090
  }
236
1091
  }
1092
+ return diagnostics;
1093
+ };
1094
+
1095
+ const tagTopoDiagnostic = (
1096
+ diagnostic: WardenDiagnostic,
1097
+ topoName: string | undefined
1098
+ ): WardenDiagnostic =>
1099
+ topoName === undefined ? diagnostic : { ...diagnostic, topoName };
1100
+
1101
+ const lintTopoTargets = async (
1102
+ topoTargets: readonly WardenTopoTarget[],
1103
+ extraTopoRules: readonly TopoAwareWardenRule[],
1104
+ selector: WardenRuleSelector,
1105
+ tagDiagnostics: boolean
1106
+ ): Promise<readonly WardenDiagnostic[]> => {
1107
+ const diagnostics: WardenDiagnostic[] = [];
1108
+
1109
+ for (const target of topoTargets) {
1110
+ const topoDiagnostics = await lintTopo(
1111
+ target.topo,
1112
+ target.graph,
1113
+ extraTopoRules,
1114
+ selector
1115
+ );
1116
+ const topoName = target.name ?? target.topo.name;
1117
+ diagnostics.push(
1118
+ ...(tagDiagnostics
1119
+ ? topoDiagnostics.map((diagnostic) =>
1120
+ tagTopoDiagnostic(diagnostic, topoName)
1121
+ )
1122
+ : topoDiagnostics)
1123
+ );
1124
+ }
1125
+
1126
+ return diagnostics;
1127
+ };
1128
+
1129
+ const selectorIncludesTopoRules = (selector: WardenRuleSelector): boolean => {
1130
+ if (selector.tier) {
1131
+ return selector.tier === 'advisory';
1132
+ }
1133
+
1134
+ return !selector.depth || depthIncludesTier(selector.depth, 'topo-aware');
1135
+ };
1136
+
1137
+ /**
1138
+ * Lint all files against all warden rules.
1139
+ */
1140
+ interface WardenLintResult {
1141
+ readonly diagnostics: readonly WardenDiagnostic[];
1142
+ readonly sourceFiles: readonly SourceFile[];
1143
+ }
1144
+
1145
+ const lintFiles = async (
1146
+ rootDir: string,
1147
+ drafts: EffectiveWardenConfig['drafts'],
1148
+ topoTargets: readonly WardenTopoTarget[],
1149
+ extraTopoRules: readonly TopoAwareWardenRule[],
1150
+ extraSourceRules: readonly WardenRule[],
1151
+ selector: WardenRuleSelector
1152
+ ): Promise<WardenLintResult> => {
1153
+ if (selector.tier === 'topo-aware') {
1154
+ return {
1155
+ diagnostics: [
1156
+ ...(await lintTopoTargets(topoTargets, extraTopoRules, selector, true)),
1157
+ ],
1158
+ sourceFiles: [],
1159
+ };
1160
+ }
1161
+
1162
+ const sourceFiles = filterSourceFilesByDraftMode(
1163
+ await loadSourceFiles(rootDir),
1164
+ drafts
1165
+ );
1166
+ const context = buildProjectContext(
1167
+ sourceFiles,
1168
+ rootDir,
1169
+ topoTargets.map((target) => target.topo)
1170
+ );
1171
+ const allDiagnostics: WardenDiagnostic[] = [
1172
+ ...lintSourceFiles(sourceFiles, context, extraSourceRules, selector),
1173
+ ];
1174
+
1175
+ if (
1176
+ topoTargets.length > 0 &&
1177
+ (selector.tier === undefined || selector.tier === 'advisory') &&
1178
+ selectorIncludesTopoRules(selector)
1179
+ ) {
1180
+ allDiagnostics.push(
1181
+ ...(await lintTopoTargets(
1182
+ topoTargets,
1183
+ extraTopoRules,
1184
+ selector,
1185
+ topoTargets.length > 1
1186
+ ))
1187
+ );
1188
+ }
1189
+
1190
+ return { diagnostics: allDiagnostics, sourceFiles };
1191
+ };
1192
+
1193
+ const topoTargetsFromOptions = (
1194
+ options: WardenRunOptions
1195
+ ): readonly WardenTopoTarget[] => {
1196
+ if (options.topos !== undefined && options.topos.length > 0) {
1197
+ return options.topos;
1198
+ }
1199
+
1200
+ return options.topo ? [{ name: options.topo.name, topo: options.topo }] : [];
1201
+ };
1202
+
1203
+ const aggregateDriftHash = (
1204
+ topoTargets: readonly WardenTopoTarget[],
1205
+ driftResults: readonly DriftResult[]
1206
+ ): string => {
1207
+ const currentHashes = new Set(
1208
+ driftResults.map((result) => result.currentHash)
1209
+ );
1210
+ const [onlyHash] = currentHashes;
1211
+ if (currentHashes.size === 1 && onlyHash !== undefined) {
1212
+ return onlyHash;
1213
+ }
1214
+
1215
+ const payload = driftResults
1216
+ .map((result, index) => {
1217
+ const target = topoTargets[index];
1218
+ return {
1219
+ currentHash: result.currentHash,
1220
+ topoName: target?.name ?? target?.topo.name ?? `topo-${String(index)}`,
1221
+ };
1222
+ })
1223
+ .toSorted((left, right) => left.topoName.localeCompare(right.topoName));
1224
+ const hasher = new Bun.CryptoHasher('sha256');
1225
+ hasher.update(JSON.stringify(payload));
1226
+ return hasher.digest('hex');
1227
+ };
1228
+
1229
+ const describeTopoDriftHash = (
1230
+ topoTargets: readonly WardenTopoTarget[],
1231
+ driftResults: readonly DriftResult[]
1232
+ ): string =>
1233
+ driftResults
1234
+ .map((result, index) => {
1235
+ const target = topoTargets[index];
1236
+ const topoName =
1237
+ target?.name ?? target?.topo.name ?? `topo-${String(index)}`;
1238
+ return `${topoName}=${result.committedHash ?? '<none>'}`;
1239
+ })
1240
+ .join(', ');
1241
+
1242
+ const checkDriftForTopoTargets = async (
1243
+ rootDir: string,
1244
+ topoTargets: readonly WardenTopoTarget[]
1245
+ ): Promise<DriftResult> => {
1246
+ if (topoTargets.length <= 1) {
1247
+ return checkDrift(rootDir, topoTargets[0]?.topo);
1248
+ }
1249
+
1250
+ const driftResults = await Promise.all(
1251
+ topoTargets.map((target) => checkDrift(rootDir, target.topo))
1252
+ );
1253
+ const committedHashes = new Set(
1254
+ driftResults.map((result) => result.committedHash)
1255
+ );
1256
+ if (committedHashes.size > 1) {
1257
+ return {
1258
+ blockedReason: `multi-topo drift expected one committed trails.lock hash but found conflicting hashes: ${describeTopoDriftHash(topoTargets, driftResults)}`,
1259
+ committedHash: null,
1260
+ currentHash: 'blocked',
1261
+ stale: true,
1262
+ };
1263
+ }
1264
+ const committedHash = driftResults[0]?.committedHash ?? null;
1265
+ const blockedReasons = driftResults.flatMap((result, index) => {
1266
+ if (result.blockedReason === undefined) {
1267
+ return [];
1268
+ }
1269
+ const target = topoTargets[index];
1270
+ const topoName =
1271
+ target?.name ?? target?.topo.name ?? `topo-${String(index)}`;
1272
+ return [`${topoName}: ${result.blockedReason}`];
1273
+ });
1274
+
1275
+ if (blockedReasons.length > 0) {
1276
+ return {
1277
+ blockedReason: blockedReasons.join('; '),
1278
+ committedHash,
1279
+ currentHash: 'blocked',
1280
+ stale: true,
1281
+ };
1282
+ }
237
1283
 
238
- return allDiagnostics;
1284
+ const currentHash = aggregateDriftHash(topoTargets, driftResults);
1285
+ return {
1286
+ committedHash,
1287
+ currentHash,
1288
+ stale: committedHash !== null && committedHash !== currentHash,
1289
+ };
1290
+ };
1291
+
1292
+ const shouldRunLint = (options: WardenRunOptions): boolean =>
1293
+ options.tier ? options.tier !== 'drift' : !options.driftOnly;
1294
+
1295
+ const adapterDiagnosticsForRun = (
1296
+ rootDir: string,
1297
+ options: WardenRunOptions
1298
+ ): readonly WardenDiagnostic[] =>
1299
+ options.adapterCheck ? runWardenAdapterChecks(rootDir) : [];
1300
+
1301
+ const shouldRunDrift = (
1302
+ options: WardenRunOptions,
1303
+ effectiveConfig: EffectiveWardenConfig
1304
+ ): boolean => {
1305
+ if (effectiveConfig.lock === 'skip') {
1306
+ return false;
1307
+ }
1308
+
1309
+ if (options.tier) {
1310
+ return options.tier === 'drift';
1311
+ }
1312
+
1313
+ if (options.lintOnly) {
1314
+ return false;
1315
+ }
1316
+
1317
+ return options.driftOnly || effectiveConfig.depth === 'all';
1318
+ };
1319
+
1320
+ const reportPassed = ({
1321
+ drift,
1322
+ errorCount,
1323
+ failOn,
1324
+ warnCount,
1325
+ }: {
1326
+ readonly drift: DriftResult | null;
1327
+ readonly errorCount: number;
1328
+ readonly failOn: WardenFailOn;
1329
+ readonly warnCount: number;
1330
+ }): boolean =>
1331
+ errorCount === 0 &&
1332
+ (failOn === 'error' || warnCount === 0) &&
1333
+ !(drift?.stale ?? false) &&
1334
+ drift?.blockedReason === undefined;
1335
+
1336
+ const buildCliConfigLayer = (options: WardenRunOptions): WardenConfigLayer => ({
1337
+ ...(options.apps ? { apps: [...options.apps] } : {}),
1338
+ ...(options.depth ? { depth: options.depth } : {}),
1339
+ ...(options.drafts ? { drafts: options.drafts } : {}),
1340
+ ...(options.failOn ? { failOn: options.failOn } : {}),
1341
+ ...(options.format ? { format: options.format } : {}),
1342
+ ...(options.lock ? { lock: options.lock } : {}),
1343
+ ...(options.noLockMutation === undefined
1344
+ ? {}
1345
+ : { noLockMutation: options.noLockMutation }),
1346
+ });
1347
+
1348
+ const fixSummary = (application: WardenFixApplication): WardenFixSummary => ({
1349
+ applied: application.applied,
1350
+ filesChanged: application.filesChanged,
1351
+ skipped: application.skipped,
1352
+ });
1353
+
1354
+ const filterAppliedFixDiagnostics = (
1355
+ diagnostics: readonly WardenDiagnostic[],
1356
+ appliedDiagnostics: readonly WardenDiagnostic[]
1357
+ ): readonly WardenDiagnostic[] => {
1358
+ if (appliedDiagnostics.length === 0) {
1359
+ return diagnostics;
1360
+ }
1361
+ const applied = new Set(appliedDiagnostics);
1362
+ return diagnostics.filter((diagnostic) => !applied.has(diagnostic));
1363
+ };
1364
+
1365
+ const blockedDriftAfterSourceFixes = (): DriftResult => ({
1366
+ blockedReason:
1367
+ 'Source fixes were applied; rerun Warden to refresh drift evidence.',
1368
+ committedHash: null,
1369
+ currentHash: 'blocked',
1370
+ stale: true,
1371
+ });
1372
+
1373
+ /**
1374
+ * Apply every safe source fix among a run's diagnostics, writing patched files.
1375
+ *
1376
+ * Diagnostics with a safe, edit-bearing fix are grouped by file; each file is
1377
+ * re-read so the rule's recorded offsets stay valid, patched via
1378
+ * {@link applySafeFixesToSource}, and written back only when its source
1379
+ * actually changed. Diagnostics that carry fix metadata but are not safe with
1380
+ * edits (review-required or edit-less) are counted as skipped and left reported
1381
+ * for a human or downstream regrade to resolve. Diagnostics without fix
1382
+ * metadata — including topo diagnostics, which carry no source span — are
1383
+ * neither applied nor counted in `skipped`.
1384
+ */
1385
+ export const applySafeFixesToFiles = async (
1386
+ diagnostics: readonly WardenDiagnostic[],
1387
+ options: {
1388
+ readonly allowedFilePaths?: ReadonlySet<string> | readonly string[];
1389
+ readonly rootDir: string;
1390
+ }
1391
+ ): Promise<WardenFixApplication> => {
1392
+ const rootDir = resolve(options.rootDir);
1393
+ const allowedFilePaths =
1394
+ options.allowedFilePaths === undefined
1395
+ ? undefined
1396
+ : new Set(
1397
+ [...options.allowedFilePaths].map((filePath) => resolve(filePath))
1398
+ );
1399
+ const fixableByFile = new Map<string, WardenDiagnostic[]>();
1400
+ let skipped = 0;
1401
+ for (const diagnostic of diagnostics) {
1402
+ if (diagnostic.fix === undefined) {
1403
+ continue;
1404
+ }
1405
+ if (hasSafeFixEdits(diagnostic)) {
1406
+ const filePath = resolve(diagnostic.filePath);
1407
+ const rootRelativePath = relative(rootDir, filePath);
1408
+ const insideRoot =
1409
+ rootRelativePath.length === 0 ||
1410
+ (!rootRelativePath.startsWith('..') && !isAbsolute(rootRelativePath));
1411
+ if (
1412
+ !insideRoot ||
1413
+ (allowedFilePaths !== undefined && !allowedFilePaths.has(filePath))
1414
+ ) {
1415
+ skipped += 1;
1416
+ continue;
1417
+ }
1418
+ const bucket = fixableByFile.get(filePath) ?? [];
1419
+ bucket.push(diagnostic);
1420
+ fixableByFile.set(filePath, bucket);
1421
+ } else {
1422
+ skipped += 1;
1423
+ }
1424
+ }
1425
+
1426
+ let applied = 0;
1427
+ const appliedDiagnostics: WardenDiagnostic[] = [];
1428
+ let filesChanged = 0;
1429
+ for (const [filePath, group] of fixableByFile) {
1430
+ const source = await Bun.file(filePath).text();
1431
+ const result = applySafeFixesToSource(source, group);
1432
+ applied += result.applied.length;
1433
+ appliedDiagnostics.push(...result.applied);
1434
+ if (result.changed) {
1435
+ await Bun.write(filePath, result.patched);
1436
+ filesChanged += 1;
1437
+ }
1438
+ }
1439
+
1440
+ return { applied, appliedDiagnostics, filesChanged, skipped };
239
1441
  };
240
1442
 
241
1443
  /**
242
1444
  * Run all warden checks and return a structured report.
243
1445
  */
244
1446
  export const runWarden = async (
245
- options: WardenOptions = {}
1447
+ options: WardenRunOptions = {}
246
1448
  ): Promise<WardenReport> => {
247
- const rootDir = resolve(options.rootDir ?? process.cwd());
248
- const allDiagnostics = options.driftOnly
249
- ? []
250
- : await lintFiles(rootDir, options.topo);
251
- const drift = options.lintOnly
252
- ? null
253
- : await checkDrift(rootDir, options.topo);
254
-
255
- const errorCount = allDiagnostics.filter(
1449
+ const { rootDir } = resolveTrailsProjectRoot({
1450
+ explicitRootDir: options.rootDir,
1451
+ startDir: process.cwd(),
1452
+ });
1453
+ const { diagnostics: configDiagnostics, effectiveConfig } =
1454
+ resolveWardenConfig({
1455
+ cli: buildCliConfigLayer(options),
1456
+ config: options.config,
1457
+ env: options.env,
1458
+ });
1459
+ const optionDiagnostics =
1460
+ !options.tier && options.lintOnly && options.driftOnly
1461
+ ? [
1462
+ createOptionsDiagnostic(
1463
+ 'lintOnly and driftOnly cannot both be true. Use tier to select a single Warden mode.'
1464
+ ),
1465
+ ]
1466
+ : [];
1467
+ const topoTargets = topoTargetsFromOptions(options);
1468
+ const selector = {
1469
+ depth: options.tier ? undefined : effectiveConfig.depth,
1470
+ tier: options.tier,
1471
+ } satisfies WardenRuleSelector;
1472
+ const runLint = shouldRunLint(options);
1473
+ const runDrift = shouldRunDrift(options, effectiveConfig);
1474
+ const projectRules = await loadProjectRulesForRun(rootDir, options, runLint);
1475
+ const lintResult = runLint
1476
+ ? await lintFiles(
1477
+ rootDir,
1478
+ effectiveConfig.drafts,
1479
+ topoTargets,
1480
+ [...projectRules.topoRules, ...(options.extraTopoRules ?? [])],
1481
+ [...projectRules.sourceRules, ...(options.extraSourceRules ?? [])],
1482
+ selector
1483
+ )
1484
+ : { diagnostics: [], sourceFiles: [] };
1485
+ const adapterDiagnostics = adapterDiagnosticsForRun(rootDir, options);
1486
+
1487
+ const rawDiagnostics = [
1488
+ ...configDiagnostics,
1489
+ ...projectRules.diagnostics,
1490
+ ...optionDiagnostics,
1491
+ ...lintResult.diagnostics,
1492
+ ...adapterDiagnostics,
1493
+ ];
1494
+ const allDiagnostics = rawDiagnostics.map(withDiagnosticGuidance);
1495
+ const fixApplication = options.fix
1496
+ ? await applySafeFixesToFiles(allDiagnostics, {
1497
+ allowedFilePaths: lintResult.sourceFiles.map(
1498
+ (sourceFile) => sourceFile.filePath
1499
+ ),
1500
+ rootDir,
1501
+ })
1502
+ : undefined;
1503
+ const reportDiagnostics = filterAppliedFixDiagnostics(
1504
+ allDiagnostics,
1505
+ fixApplication?.appliedDiagnostics ?? []
1506
+ );
1507
+ let drift: DriftResult | null = null;
1508
+ if (runDrift) {
1509
+ drift =
1510
+ fixApplication !== undefined && fixApplication.filesChanged > 0
1511
+ ? blockedDriftAfterSourceFixes()
1512
+ : await checkDriftForTopoTargets(rootDir, topoTargets);
1513
+ }
1514
+
1515
+ const errorCount = reportDiagnostics.filter(
256
1516
  (d) => d.severity === 'error'
257
1517
  ).length;
258
- const warnCount = allDiagnostics.filter((d) => d.severity === 'warn').length;
1518
+ const warnCount = reportDiagnostics.filter(
1519
+ (d) => d.severity === 'warn'
1520
+ ).length;
1521
+ const topoNames =
1522
+ topoTargets.length > 0
1523
+ ? topoTargets.map((target) => target.name ?? target.topo.name)
1524
+ : undefined;
259
1525
 
260
1526
  return {
261
- diagnostics: allDiagnostics,
1527
+ diagnostics: reportDiagnostics,
262
1528
  drift,
1529
+ effectiveConfig,
263
1530
  errorCount,
264
- passed: errorCount === 0 && !(drift?.stale ?? false),
1531
+ ...(fixApplication === undefined
1532
+ ? {}
1533
+ : { fixes: fixSummary(fixApplication) }),
1534
+ passed: reportPassed({
1535
+ drift,
1536
+ errorCount,
1537
+ failOn: effectiveConfig.failOn,
1538
+ warnCount,
1539
+ }),
1540
+ ...(topoNames === undefined ? {} : { topoNames }),
265
1541
  warnCount,
266
1542
  };
267
1543
  };
268
1544
 
1545
+ const formatPlainGuidanceLink = (link: WardenGuidanceLink): string => {
1546
+ const target = link.path ?? link.url;
1547
+ if (target === undefined || target === link.label) {
1548
+ return link.label;
1549
+ }
1550
+ return `${link.label} (${target})`;
1551
+ };
1552
+
269
1553
  /**
270
1554
  * Format the lint section of the report.
271
1555
  */
@@ -283,6 +1567,25 @@ const formatLintSection = (report: WardenReport): string[] => {
283
1567
  lines.push(
284
1568
  ` ${d.filePath}:${String(d.line)} [${prefix}] ${d.rule} ${d.message}`
285
1569
  );
1570
+ if (d.guidance !== undefined) {
1571
+ lines.push(` Next: ${d.guidance.summary}`);
1572
+ for (const [index, step] of (d.guidance.steps ?? []).entries()) {
1573
+ lines.push(` ${String(index + 1)}. ${step}`);
1574
+ }
1575
+ if (d.guidance.commands !== undefined) {
1576
+ lines.push(
1577
+ ` Commands: ${d.guidance.commands.map((cmd) => `\`${cmd}\``).join(', ')}`
1578
+ );
1579
+ }
1580
+ if (d.guidance.docs !== undefined) {
1581
+ lines.push(
1582
+ ` Docs: ${d.guidance.docs.map(formatPlainGuidanceLink).join(', ')}`
1583
+ );
1584
+ }
1585
+ if (d.guidance.relatedRules !== undefined) {
1586
+ lines.push(` Related: ${d.guidance.relatedRules.join(', ')}`);
1587
+ }
1588
+ }
286
1589
  }
287
1590
 
288
1591
  return lines;
@@ -295,8 +1598,11 @@ const formatDriftSection = (drift: DriftResult | null): string[] => {
295
1598
  if (drift === null) {
296
1599
  return [];
297
1600
  }
1601
+ if (drift.blockedReason !== undefined) {
1602
+ return [`Drift: blocked (${drift.blockedReason})`, ''];
1603
+ }
298
1604
  const label = drift.stale
299
- ? 'Drift: surface.lock is stale (regenerate with `trails survey generate`)'
1605
+ ? 'Drift: trails.lock is stale (regenerate with `trails compile`)'
300
1606
  : 'Drift: clean';
301
1607
  return [label, ''];
302
1608
  };
@@ -312,7 +1618,12 @@ const formatResultLine = (report: WardenReport): string => {
312
1618
  if (report.errorCount > 0) {
313
1619
  parts.push(`${report.errorCount} errors`);
314
1620
  }
315
- if (report.drift?.stale) {
1621
+ if (report.warnCount > 0 && report.effectiveConfig?.failOn === 'warning') {
1622
+ parts.push(`${report.warnCount} warnings`);
1623
+ }
1624
+ if (report.drift?.blockedReason !== undefined) {
1625
+ parts.push('established exports blocked');
1626
+ } else if (report.drift?.stale) {
316
1627
  parts.push('drift detected');
317
1628
  }
318
1629
  return `Result: FAIL (${parts.join(', ')})`;