@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,205 @@
1
+ /**
2
+ * Run file-scoped warden rule trails against a single source file.
3
+ *
4
+ * Returns a flat array of diagnostics from every source-aware rule. Built-in
5
+ * topo-aware rules are dispatched separately via `runTopoAwareWardenTrails()`
6
+ * so callers that loop files do not duplicate graph-level findings.
7
+ */
8
+
9
+ import type { Intent, Topo } from '@ontrails/core';
10
+ import { run } from '@ontrails/core';
11
+
12
+ import { wardenRules, wardenTopoRules } from '../rules/index.js';
13
+ import type {
14
+ GovernedVocabularyHistoryEvidence,
15
+ GovernedVocabularyHistoryIssue,
16
+ ProjectAwareWardenRule,
17
+ ProjectContext,
18
+ WardenDiagnostic,
19
+ WardenRule,
20
+ } from '../rules/types.js';
21
+ import type { WardenImportResolution } from '../resolve.js';
22
+ import type { WardenPublicWorkspace } from '../workspaces.js';
23
+ import { projectAwareRuleInput } from './schema.js';
24
+ import type { RuleOutput } from './schema.js';
25
+ import { wardenTopo } from './topo.js';
26
+ import { buildProjectContext } from './wrap-rule.js';
27
+
28
+ /**
29
+ * Run all file-scoped warden rule trails for a given file and collect diagnostics.
30
+ *
31
+ * Each rule trail runs independently. Errors from individual trails are
32
+ * silently skipped so that one broken rule does not block the rest.
33
+ */
34
+ const appendDiagnostics = (
35
+ target: WardenDiagnostic[],
36
+ diagnostics: readonly WardenDiagnostic[]
37
+ ): void => {
38
+ for (const diagnostic of diagnostics) {
39
+ target.push(diagnostic);
40
+ }
41
+ };
42
+
43
+ type TrailIntentMap = Readonly<Record<string, Intent>>;
44
+
45
+ interface ProjectRuleOptions {
46
+ readonly unownedWorkspaceLocks?: ProjectContext['unownedWorkspaceLocks'];
47
+ readonly governedVocabularyHistories?: readonly GovernedVocabularyHistoryEvidence[];
48
+ readonly governedVocabularyHistoryIssues?: readonly GovernedVocabularyHistoryIssue[];
49
+ readonly governedVocabularyHistoryRequired?: boolean;
50
+ readonly entityReferencesByName?: Readonly<Record<string, readonly string[]>>;
51
+ readonly composeTargetTrailIds?: readonly string[];
52
+ readonly crudTableIds?: readonly string[];
53
+ readonly crudCoverageByEntity?: Readonly<Record<string, readonly string[]>>;
54
+ readonly knownEntityIds?: readonly string[];
55
+ readonly importResolutionsByFile?: Readonly<
56
+ Record<string, readonly WardenImportResolution[]>
57
+ >;
58
+ readonly documentedImportResolutionsByFile?: Readonly<
59
+ Record<string, readonly WardenImportResolution[]>
60
+ >;
61
+ readonly knownResourceIds?: readonly string[];
62
+ readonly knownSignalIds?: readonly string[];
63
+ readonly knownTrailIds?: readonly string[];
64
+ readonly onTargetSignalIds?: readonly string[];
65
+ readonly publicWorkspaces?: Readonly<Record<string, WardenPublicWorkspace>>;
66
+ readonly reconcileTableIds?: readonly string[];
67
+ readonly trailIntentsById?: TrailIntentMap;
68
+ }
69
+
70
+ const PROJECT_OPTION_KEYS = [
71
+ 'unownedWorkspaceLocks',
72
+ 'governedVocabularyHistories',
73
+ 'governedVocabularyHistoryIssues',
74
+ 'governedVocabularyHistoryRequired',
75
+ 'entityReferencesByName',
76
+ 'composeTargetTrailIds',
77
+ 'crudTableIds',
78
+ 'crudCoverageByEntity',
79
+ 'knownEntityIds',
80
+ 'importResolutionsByFile',
81
+ 'documentedImportResolutionsByFile',
82
+ 'knownResourceIds',
83
+ 'knownSignalIds',
84
+ 'knownTrailIds',
85
+ 'onTargetSignalIds',
86
+ 'publicWorkspaces',
87
+ 'reconcileTableIds',
88
+ 'trailIntentsById',
89
+ ] as const satisfies readonly (keyof ProjectRuleOptions)[];
90
+
91
+ const hasProjectOptions = (options?: ProjectRuleOptions): boolean =>
92
+ Boolean(
93
+ options && PROJECT_OPTION_KEYS.some((key) => options[key] !== undefined)
94
+ );
95
+
96
+ const collectProjectOptions = (
97
+ options?: ProjectRuleOptions
98
+ ): ProjectRuleOptions => {
99
+ if (!options) {
100
+ return {};
101
+ }
102
+
103
+ return Object.fromEntries(
104
+ PROJECT_OPTION_KEYS.flatMap((key) => {
105
+ const value = options[key];
106
+ return value === undefined ? [] : [[key, value] as const];
107
+ })
108
+ ) as ProjectRuleOptions;
109
+ };
110
+
111
+ const buildRuleInput = (
112
+ filePath: string,
113
+ sourceCode: string,
114
+ options?: ProjectRuleOptions
115
+ ): {
116
+ readonly filePath: string;
117
+ readonly sourceCode: string;
118
+ } & ProjectRuleOptions => {
119
+ const base = { filePath, sourceCode };
120
+ if (!hasProjectOptions(options)) {
121
+ return base;
122
+ }
123
+
124
+ return { ...base, ...collectProjectOptions(options) };
125
+ };
126
+
127
+ const topoAwareTrailIds = new Set(
128
+ [...wardenTopoRules.keys()].map((ruleName) => `warden.rule.${ruleName}`)
129
+ );
130
+
131
+ export const runWardenTrails = async (
132
+ filePath: string,
133
+ sourceCode: string,
134
+ options?: ProjectRuleOptions
135
+ ): Promise<readonly WardenDiagnostic[]> => {
136
+ const allDiagnostics: WardenDiagnostic[] = [];
137
+ const input = buildRuleInput(filePath, sourceCode, options);
138
+
139
+ for (const id of wardenTopo.ids()) {
140
+ if (topoAwareTrailIds.has(id)) {
141
+ continue;
142
+ }
143
+ const result = await run(wardenTopo, id, input);
144
+ if (result.isOk()) {
145
+ appendDiagnostics(
146
+ allDiagnostics,
147
+ (result.value as RuleOutput).diagnostics
148
+ );
149
+ }
150
+ }
151
+
152
+ return allDiagnostics;
153
+ };
154
+
155
+ const isProjectAwareRule = (rule: WardenRule): rule is ProjectAwareWardenRule =>
156
+ 'checkWithContext' in rule;
157
+
158
+ /**
159
+ * Run project-wide built-in Warden diagnostics once for one project context.
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * const diagnostics = runProjectWardenRules({
164
+ * governedVocabularyHistories: histories,
165
+ * });
166
+ * ```
167
+ */
168
+ export const runProjectWardenRules = (
169
+ options?: ProjectRuleOptions
170
+ ): readonly WardenDiagnostic[] => {
171
+ const context = buildProjectContext(
172
+ projectAwareRuleInput.parse(buildRuleInput('<project>', '', options))
173
+ );
174
+ const diagnostics: WardenDiagnostic[] = [];
175
+ for (const rule of wardenRules.values()) {
176
+ if (isProjectAwareRule(rule) && rule.checkProject !== undefined) {
177
+ appendDiagnostics(diagnostics, rule.checkProject(context));
178
+ }
179
+ }
180
+ return diagnostics;
181
+ };
182
+
183
+ /**
184
+ * Run the built-in topo-aware warden rule trails once against a resolved topo.
185
+ *
186
+ * Unlike `runWardenTrails()`, which is file-scoped, topo-aware rules inspect
187
+ * the compiled graph and should only be dispatched once per topo.
188
+ */
189
+ export const runTopoAwareWardenTrails = async (
190
+ topo: Topo
191
+ ): Promise<readonly WardenDiagnostic[]> => {
192
+ const allDiagnostics: WardenDiagnostic[] = [];
193
+
194
+ for (const id of topoAwareTrailIds) {
195
+ const result = await run(wardenTopo, id, { topo });
196
+ if (result.isOk()) {
197
+ appendDiagnostics(
198
+ allDiagnostics,
199
+ (result.value as RuleOutput).diagnostics
200
+ );
201
+ }
202
+ }
203
+
204
+ return allDiagnostics;
205
+ };
@@ -0,0 +1,56 @@
1
+ import { Result, schedule, topo, trail } from '@ontrails/core';
2
+ import { z } from 'zod';
3
+
4
+ import { scheduledDestroyIntent } from '../rules/scheduled-destroy-intent.js';
5
+ import { wrapTopoRule } from './wrap-rule.js';
6
+
7
+ export const scheduledDestroyTrail = trail('billing.purge-expired', {
8
+ implementation: () => Result.ok({ ok: true }),
9
+ input: z.object({}),
10
+ intent: 'destroy',
11
+ on: [
12
+ schedule('schedule.billing.purge-expired', {
13
+ cron: '0 2 * * *',
14
+ }),
15
+ ],
16
+ output: z.object({ ok: z.boolean() }),
17
+ permit: { scopes: ['billing:purge'] },
18
+ });
19
+
20
+ const scheduledWriteTrail = trail('billing.reconcile', {
21
+ implementation: () => Result.ok({ ok: true }),
22
+ input: z.object({}),
23
+ on: [schedule('schedule.billing.reconcile', { cron: '0 * * * *' })],
24
+ output: z.object({ ok: z.boolean() }),
25
+ });
26
+
27
+ export const scheduledDestroyIntentTrail = wrapTopoRule({
28
+ examples: [
29
+ {
30
+ expected: {
31
+ diagnostics: [
32
+ {
33
+ filePath: '<topo>',
34
+ line: 1,
35
+ message:
36
+ 'Trail "billing.purge-expired" declares intent: \'destroy\' and is activated by schedule source "schedule.billing.purge-expired". Before this runs unattended, confirm the schedule cadence, that the declared permit scopes cover the destroy, that idempotent: true is set only if a repeat run is safe, and that detours cover the failure modes you expect to recover.',
37
+ rule: 'scheduled-destroy-intent',
38
+ severity: 'warn',
39
+ },
40
+ ],
41
+ },
42
+ input: {
43
+ topo: topo('trl-457-scheduled-destroy', { scheduledDestroyTrail }),
44
+ },
45
+ name: 'Scheduled destroy trails emit coaching',
46
+ },
47
+ {
48
+ expected: { diagnostics: [] },
49
+ input: {
50
+ topo: topo('trl-457-scheduled-write', { scheduledWriteTrail }),
51
+ },
52
+ name: 'Scheduled write trails do not emit destroy coaching',
53
+ },
54
+ ],
55
+ rule: scheduledDestroyIntent,
56
+ });
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Shared Zod schemas for warden rule trails.
3
+ *
4
+ * Every rule trail shares the same input (source file) and output
5
+ * (array of diagnostics) shape.
6
+ */
7
+
8
+ import { intentValues } from '@ontrails/core';
9
+ import type { Topo } from '@ontrails/core';
10
+ import type { TopoGraph } from '@ontrails/topography';
11
+ import { z } from 'zod';
12
+ import { wardenImportResolutionErrorKinds } from '../resolve.js';
13
+ import { wardenFixClasses, wardenFixSafeties } from '../rules/metadata.js';
14
+
15
+ export const guidanceLinkSchema = z.object({
16
+ label: z.string(),
17
+ path: z.string().optional(),
18
+ url: z.string().optional(),
19
+ });
20
+
21
+ export const guidanceSchema = z.object({
22
+ commands: z.array(z.string()).readonly().optional(),
23
+ docs: z.array(guidanceLinkSchema).readonly().optional(),
24
+ relatedRules: z.array(z.string()).readonly().optional(),
25
+ steps: z.array(z.string()).readonly().optional(),
26
+ summary: z.string(),
27
+ });
28
+
29
+ export const fixEditSchema = z.object({
30
+ end: z.number(),
31
+ replacement: z.string(),
32
+ start: z.number(),
33
+ });
34
+
35
+ export const fixSchema = z.object({
36
+ class: z.enum(wardenFixClasses),
37
+ edits: z.array(fixEditSchema).readonly().optional(),
38
+ fixture: z.string().optional(),
39
+ reason: z.string(),
40
+ safety: z.enum(wardenFixSafeties),
41
+ });
42
+
43
+ /** A single diagnostic emitted by a warden rule trail. */
44
+ export const diagnosticSchema = z.object({
45
+ code: z.string().optional().describe('Optional rule-local diagnostic code'),
46
+ filePath: z.string().describe('File path that was analyzed'),
47
+ fix: fixSchema.optional().describe('Structured fix metadata'),
48
+ guidance: guidanceSchema
49
+ .optional()
50
+ .describe('Structured remediation guidance'),
51
+ line: z.number().describe('1-based line number'),
52
+ message: z.string().describe('Human-readable diagnostic message'),
53
+ rule: z.string().describe('Rule name'),
54
+ severity: z.enum(['error', 'warn']).describe('Diagnostic severity'),
55
+ });
56
+
57
+ /** Input accepted by every warden rule trail. */
58
+ export const ruleInput = z.object({
59
+ filePath: z.string().describe('Path to the source file'),
60
+ sourceCode: z.string().describe('Source code content'),
61
+ });
62
+
63
+ export const importResolutionSchema = z.object({
64
+ builtinModule: z.string().optional(),
65
+ crossesPackageBoundary: z.boolean(),
66
+ errorKind: z.enum(wardenImportResolutionErrorKinds).optional(),
67
+ errorMessage: z.string().optional(),
68
+ importSource: z.string(),
69
+ importerPath: z.string(),
70
+ isInternalTarget: z.boolean(),
71
+ line: z.number(),
72
+ packageName: z.string().optional(),
73
+ packageRoot: z.string().optional(),
74
+ resolvedPath: z.string().optional(),
75
+ usesPublicExport: z.boolean(),
76
+ });
77
+
78
+ export const publicWorkspaceSchema = z.object({
79
+ bin: z.record(z.string(), z.string()).optional(),
80
+ exportTargets: z.record(z.string(), z.string()).optional(),
81
+ files: z.array(z.string()).optional(),
82
+ hasExports: z.boolean(),
83
+ name: z.string(),
84
+ packageJsonPath: z.string(),
85
+ rootDir: z.string(),
86
+ });
87
+
88
+ export const exportedSymbolDefinitionSchema = z.object({
89
+ filePath: z.string(),
90
+ kind: z.enum([
91
+ 'class',
92
+ 'const',
93
+ 'enum',
94
+ 'export',
95
+ 'function',
96
+ 'interface',
97
+ 'type',
98
+ ]),
99
+ line: z.number(),
100
+ name: z.string(),
101
+ workspaceName: z.string(),
102
+ workspaceRoot: z.string(),
103
+ });
104
+
105
+ /**
106
+ * Extended input for project-aware warden rule trails.
107
+ *
108
+ * Adds `knownTrailIds` so the caller can supply compose-file context and avoid
109
+ * false positives for `@see` references or compose-file entity relationships.
110
+ */
111
+ export const authoredMcpSurfaceBindingSetSchema = z.object({
112
+ appName: z.string().describe('App/topo label the bindings were authored for'),
113
+ bindings: z
114
+ .record(z.string(), z.union([z.string(), z.array(z.string()).readonly()]))
115
+ .describe('Surfaces overlay mcp bindings: binding name to selector(s)'),
116
+ trailIds: z
117
+ .array(z.string())
118
+ .readonly()
119
+ .describe('Trail ids registered in the owning app topo'),
120
+ });
121
+
122
+ const unownedWorkspaceLockObservationSchema = z.object({
123
+ coaching: z.string(),
124
+ kind: z.enum(['forbidden-workspace-aggregate', 'unconfigured-app-lock']),
125
+ path: z.string(),
126
+ provenance: z.literal('source-collection'),
127
+ });
128
+
129
+ const governedVocabularyHistoryFormJudgmentSchema = z.object({
130
+ disposition: z.string(),
131
+ form: z.string(),
132
+ reason: z.string().optional(),
133
+ representative: z
134
+ .object({
135
+ line: z.number().int().positive(),
136
+ path: z.string(),
137
+ })
138
+ .optional(),
139
+ target: z.string().optional(),
140
+ });
141
+
142
+ const governedVocabularyHistoryEvidenceSchema = z.object({
143
+ caseSensitive: z.boolean(),
144
+ id: z.string(),
145
+ latestFormJudgments: z
146
+ .array(governedVocabularyHistoryFormJudgmentSchema)
147
+ .readonly(),
148
+ path: z.string(),
149
+ runCount: z.number().int().nonnegative(),
150
+ transitionId: z.string(),
151
+ });
152
+
153
+ export const projectAwareRuleInput = ruleInput.extend({
154
+ authoredMcpSurfaceBindingSets: z
155
+ .array(authoredMcpSurfaceBindingSetSchema)
156
+ .readonly()
157
+ .optional()
158
+ .describe(
159
+ 'Per-app authored surfaces overlay mcp bindings with owning-app trail ids'
160
+ ),
161
+ composeTargetTrailIds: z
162
+ .array(z.string())
163
+ .optional()
164
+ .describe('Trail IDs referenced by composes arrays across the project'),
165
+ crudCoverageByEntity: z
166
+ .record(z.string(), z.array(z.string()))
167
+ .optional()
168
+ .describe(
169
+ 'CRUD operation coverage per entity aggregated across the project'
170
+ ),
171
+ crudTableIds: z
172
+ .array(z.string())
173
+ .optional()
174
+ .describe('Store table IDs used with CRUD factories across the project'),
175
+ documentedImportResolutionsByFile: z
176
+ .record(z.string(), z.array(importResolutionSchema))
177
+ .optional()
178
+ .describe('Resolved docs/specifier facts keyed by documentation file path'),
179
+ entityReferencesByName: z
180
+ .record(z.string(), z.array(z.string()))
181
+ .optional()
182
+ .describe('Declared entity references keyed by source entity name'),
183
+ exportedSymbolDefinitionsByName: z
184
+ .record(z.string(), z.array(exportedSymbolDefinitionSchema))
185
+ .optional()
186
+ .describe('Public exported symbol definitions grouped by exported name'),
187
+ governedVocabularyHistories: z
188
+ .array(governedVocabularyHistoryEvidenceSchema)
189
+ .readonly()
190
+ .optional()
191
+ .describe('Validated committed Regrade histories by governed transition'),
192
+ governedVocabularyHistoryIssues: z
193
+ .array(
194
+ z.object({
195
+ message: z.string(),
196
+ path: z.string(),
197
+ transitionId: z.string().optional(),
198
+ })
199
+ )
200
+ .readonly()
201
+ .optional()
202
+ .describe('Invalid committed Regrade history artifacts'),
203
+ governedVocabularyHistoryRequired: z
204
+ .boolean()
205
+ .optional()
206
+ .describe('Whether the project must prove completed governed migrations'),
207
+ importResolutionsByFile: z
208
+ .record(z.string(), z.array(importResolutionSchema))
209
+ .optional()
210
+ .describe('Resolved import facts keyed by importer file path'),
211
+ knownEntityIds: z
212
+ .array(z.string())
213
+ .optional()
214
+ .describe('Entity names known across the project'),
215
+ knownResourceIds: z
216
+ .array(z.string())
217
+ .optional()
218
+ .describe('Resource IDs known across the project'),
219
+ knownSignalIds: z
220
+ .array(z.string())
221
+ .optional()
222
+ .describe('Signal IDs known across the project'),
223
+ knownTrailIds: z
224
+ .array(z.string())
225
+ .optional()
226
+ .describe('Trail IDs known across the project'),
227
+ onTargetSignalIds: z
228
+ .array(z.string())
229
+ .optional()
230
+ .describe('Signal IDs referenced by trail on arrays across the project'),
231
+ publicWorkspaces: z
232
+ .record(z.string(), publicWorkspaceSchema)
233
+ .optional()
234
+ .describe('Non-private published @ontrails workspaces by package name'),
235
+ reconcileTableIds: z
236
+ .array(z.string())
237
+ .optional()
238
+ .describe('Store table IDs used with reconcile trails across the project'),
239
+ topoTrailIds: z
240
+ .array(z.string())
241
+ .optional()
242
+ .describe('Trail IDs registered in configured app topo targets'),
243
+ trailIntentsById: z
244
+ .record(z.string(), z.enum(intentValues))
245
+ .optional()
246
+ .describe('Normalized trail intents keyed by trail ID'),
247
+ unownedWorkspaceLocks: z
248
+ .array(unownedWorkspaceLockObservationSchema)
249
+ .readonly()
250
+ .optional()
251
+ .describe(
252
+ 'Observation-only trails.lock artifacts outside configured app ownership'
253
+ ),
254
+ });
255
+
256
+ /**
257
+ * Input for topo-aware warden rule trails.
258
+ *
259
+ * The `Topo` graph is not a serializable value, so the schema accepts it
260
+ * as an opaque `z.custom`. Topo-aware rules are invoked from the warden
261
+ * runtime with a live, resolved topo reference — they are not expected
262
+ * to be called across a network boundary.
263
+ */
264
+ export const topoAwareRuleInput = z.object({
265
+ graph: z
266
+ .custom<TopoGraph>(
267
+ (value) =>
268
+ typeof value === 'object' && value !== null && 'entries' in value,
269
+ { message: 'Expected a serialized TopoGraph object' }
270
+ )
271
+ .optional()
272
+ .describe('Optional derived TopoGraph with graph-only audit annotations'),
273
+ topo: z
274
+ .custom<Topo>(
275
+ (value) =>
276
+ typeof value === 'object' &&
277
+ value !== null &&
278
+ 'trails' in value &&
279
+ 'resources' in value &&
280
+ 'entities' in value &&
281
+ 'signals' in value,
282
+ { message: 'Expected a resolved Topo instance' }
283
+ )
284
+ .describe('Resolved topo graph under inspection'),
285
+ });
286
+
287
+ /** Output returned by every warden rule trail. */
288
+ export const ruleOutput = z.object({
289
+ diagnostics: z.array(diagnosticSchema).describe('Diagnostics found'),
290
+ });
291
+
292
+ export type RuleInput = z.infer<typeof ruleInput>;
293
+ export type ProjectAwareRuleInput = z.infer<typeof projectAwareRuleInput>;
294
+ export type TopoAwareRuleInput = z.infer<typeof topoAwareRuleInput>;
295
+ export type RuleOutput = z.infer<typeof ruleOutput>;
@@ -0,0 +1,77 @@
1
+ import { Result, resource, signal, topo, trail } from '@ontrails/core';
2
+ import { z } from 'zod';
3
+
4
+ import { signalGraphCoaching } from '../rules/signal-graph-coaching.js';
5
+ import { wrapTopoRule } from './wrap-rule.js';
6
+
7
+ const unusedSignal = signal('invoice.unused', {
8
+ payload: z.object({ invoiceId: z.string() }),
9
+ });
10
+
11
+ const producedSignal = signal('invoice.created', {
12
+ payload: z.object({ invoiceId: z.string() }),
13
+ });
14
+
15
+ const producerTrail = trail('invoice.create', {
16
+ fires: [producedSignal],
17
+ implementation: async (_input, ctx) => {
18
+ await ctx.fire?.(producedSignal, { invoiceId: 'inv_1' });
19
+ return Result.ok({ invoiceId: 'inv_1' });
20
+ },
21
+ input: z.object({}),
22
+ output: z.object({ invoiceId: z.string() }),
23
+ });
24
+
25
+ const resourceSignal = signal('store:invoice.created', {
26
+ payload: z.object({ invoiceId: z.string() }),
27
+ });
28
+
29
+ const invoiceStore = resource('store', {
30
+ create: () => Result.ok({ ok: true }),
31
+ signals: [resourceSignal],
32
+ });
33
+
34
+ export const signalGraphCoachingTrail = wrapTopoRule({
35
+ examples: [
36
+ {
37
+ expected: {
38
+ diagnostics: [
39
+ {
40
+ filePath: '<topo>',
41
+ line: 1,
42
+ message:
43
+ 'Signal "invoice.created" is produced by producer trail "invoice.create" but has no consumer trails. Add an on: consumer if the signal is meant to drive reactive work, or remove the unused fires:/producer declaration.',
44
+ rule: 'signal-graph-coaching',
45
+ severity: 'warn',
46
+ },
47
+ {
48
+ filePath: '<topo>',
49
+ line: 1,
50
+ message:
51
+ 'Signal "invoice.unused" is declared in the topo but has no producer trails, producer resources, or consumer trails. Add fires:/on: edges, attach producer metadata, or remove the unused signal contract.',
52
+ rule: 'signal-graph-coaching',
53
+ severity: 'warn',
54
+ },
55
+ {
56
+ filePath: '<topo>',
57
+ line: 1,
58
+ message:
59
+ 'Signal "store:invoice.created" is produced by producer resource "store" but has no consumer trails. Add an on: consumer if the signal is meant to drive reactive work, or remove the unused fires:/producer declaration.',
60
+ rule: 'signal-graph-coaching',
61
+ severity: 'warn',
62
+ },
63
+ ],
64
+ },
65
+ input: {
66
+ topo: topo('trl-447-signal-graph-coaching', {
67
+ invoiceStore,
68
+ producedSignal,
69
+ producerTrail,
70
+ unusedSignal,
71
+ }),
72
+ },
73
+ name: 'Declared and produced signals without consumers get coaching',
74
+ },
75
+ ],
76
+ rule: signalGraphCoaching,
77
+ });
@@ -0,0 +1,25 @@
1
+ import { staticResourceAccessorPreference } from '../rules/static-resource-accessor-preference.js';
2
+ import { wrapRule } from './wrap-rule.js';
3
+
4
+ export const staticResourceAccessorPreferenceTrail = wrapRule({
5
+ examples: [
6
+ {
7
+ expected: { diagnostics: [] },
8
+ input: {
9
+ filePath: 'clean.ts',
10
+ sourceCode: `const db = resource("db.main", {
11
+ create: () => Result.ok({ source: "factory" }),
12
+ });
13
+
14
+ trail("entity.show", {
15
+ resources: [db],
16
+ implementation: async (_input, ctx) => {
17
+ return Result.ok(db.from(ctx));
18
+ }
19
+ })`,
20
+ },
21
+ name: 'Static resource helper access',
22
+ },
23
+ ],
24
+ rule: staticResourceAccessorPreference,
25
+ });
@@ -0,0 +1,24 @@
1
+ import { Result, topo, trail } from '@ontrails/core';
2
+ import { z } from 'zod';
3
+
4
+ import { surfaceOverlayCoherence } from '../rules/surface-overlay-coherence.js';
5
+ import { wrapTopoRule } from './wrap-rule.js';
6
+
7
+ const listTrail = trail('gear.list', {
8
+ implementation: () => Result.ok([]),
9
+ input: z.object({}),
10
+ output: z.array(z.string()),
11
+ });
12
+
13
+ export const surfaceOverlayCoherenceTrail = wrapTopoRule({
14
+ examples: [
15
+ {
16
+ expected: { diagnostics: [] },
17
+ input: {
18
+ topo: topo('surface-overlay-coherence', { listTrail }),
19
+ },
20
+ name: 'Topo without a serialized surfaces overlay stays quiet',
21
+ },
22
+ ],
23
+ rule: surfaceOverlayCoherence,
24
+ });