aontu 0.52.0 → 0.53.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 (273) hide show
  1. package/README.md +88 -0
  2. package/bin/aontu-mcp.js +4 -0
  3. package/dist/agentsmd.d.ts +16 -0
  4. package/dist/agentsmd.js +107 -0
  5. package/dist/agentsmd.js.map +1 -0
  6. package/dist/aontu.d.ts +14 -3
  7. package/dist/aontu.js +145 -4
  8. package/dist/aontu.js.map +1 -1
  9. package/dist/cli.d.ts +44 -1
  10. package/dist/cli.js +2401 -44
  11. package/dist/cli.js.map +1 -1
  12. package/dist/ctx.d.ts +16 -0
  13. package/dist/ctx.js +44 -0
  14. package/dist/ctx.js.map +1 -1
  15. package/dist/diff.d.ts +22 -0
  16. package/dist/diff.js +141 -0
  17. package/dist/diff.js.map +1 -0
  18. package/dist/err.d.ts +3 -1
  19. package/dist/err.js +48 -8
  20. package/dist/err.js.map +1 -1
  21. package/dist/graph.d.ts +16 -0
  22. package/dist/graph.js +73 -0
  23. package/dist/graph.js.map +1 -0
  24. package/dist/hcanon.d.ts +3 -0
  25. package/dist/hcanon.js +146 -0
  26. package/dist/hcanon.js.map +1 -0
  27. package/dist/hints.js +223 -5
  28. package/dist/hints.js.map +1 -1
  29. package/dist/jsonschema.d.ts +20 -0
  30. package/dist/jsonschema.js +391 -0
  31. package/dist/jsonschema.js.map +1 -0
  32. package/dist/lang.js +698 -35
  33. package/dist/lang.js.map +1 -1
  34. package/dist/lsp.d.ts +9 -2
  35. package/dist/lsp.js +262 -46
  36. package/dist/lsp.js.map +1 -1
  37. package/dist/mcp-server.d.ts +20 -0
  38. package/dist/mcp-server.js +147 -0
  39. package/dist/mcp-server.js.map +1 -0
  40. package/dist/mcp.d.ts +42 -0
  41. package/dist/mcp.js +814 -0
  42. package/dist/mcp.js.map +1 -0
  43. package/dist/mod-tool.d.ts +58 -0
  44. package/dist/mod-tool.js +498 -0
  45. package/dist/mod-tool.js.map +1 -0
  46. package/dist/mod.d.ts +31 -0
  47. package/dist/mod.js +250 -0
  48. package/dist/mod.js.map +1 -0
  49. package/dist/patch.d.ts +44 -0
  50. package/dist/patch.js +506 -0
  51. package/dist/patch.js.map +1 -0
  52. package/dist/provenance.d.ts +40 -0
  53. package/dist/provenance.js +335 -0
  54. package/dist/provenance.js.map +1 -0
  55. package/dist/query.d.ts +27 -0
  56. package/dist/query.js +294 -0
  57. package/dist/query.js.map +1 -0
  58. package/dist/reach.d.ts +14 -0
  59. package/dist/reach.js +140 -0
  60. package/dist/reach.js.map +1 -0
  61. package/dist/relation.d.ts +19 -0
  62. package/dist/relation.js +305 -0
  63. package/dist/relation.js.map +1 -0
  64. package/dist/report-sarif.d.ts +14 -0
  65. package/dist/report-sarif.js +102 -0
  66. package/dist/report-sarif.js.map +1 -0
  67. package/dist/site.d.ts +4 -0
  68. package/dist/site.js +31 -0
  69. package/dist/site.js.map +1 -1
  70. package/dist/std.d.ts +1 -0
  71. package/dist/std.js +73 -0
  72. package/dist/std.js.map +1 -0
  73. package/dist/subsume.d.ts +39 -0
  74. package/dist/subsume.js +526 -0
  75. package/dist/subsume.js.map +1 -0
  76. package/dist/trim.d.ts +19 -0
  77. package/dist/trim.js +155 -0
  78. package/dist/trim.js.map +1 -0
  79. package/dist/tsconfig.tsbuildinfo +1 -1
  80. package/dist/type.d.ts +17 -1
  81. package/dist/type.js.map +1 -1
  82. package/dist/unify.d.ts +3 -1
  83. package/dist/unify.js +287 -18
  84. package/dist/unify.js.map +1 -1
  85. package/dist/utility.d.ts +9 -1
  86. package/dist/utility.js +122 -1
  87. package/dist/utility.js.map +1 -1
  88. package/dist/val/AggFuncVal.d.ts +33 -0
  89. package/dist/val/AggFuncVal.js +202 -0
  90. package/dist/val/AggFuncVal.js.map +1 -0
  91. package/dist/val/ArithFuncVal.d.ts +31 -0
  92. package/dist/val/ArithFuncVal.js +62 -0
  93. package/dist/val/ArithFuncVal.js.map +1 -0
  94. package/dist/val/BagVal.d.ts +5 -0
  95. package/dist/val/BagVal.js +96 -5
  96. package/dist/val/BagVal.js.map +1 -1
  97. package/dist/val/CloseFuncVal.js +9 -1
  98. package/dist/val/CloseFuncVal.js.map +1 -1
  99. package/dist/val/ConjunctVal.d.ts +1 -1
  100. package/dist/val/ConjunctVal.js +19 -0
  101. package/dist/val/ConjunctVal.js.map +1 -1
  102. package/dist/val/ConstraintVal.d.ts +48 -1
  103. package/dist/val/ConstraintVal.js +1501 -110
  104. package/dist/val/ConstraintVal.js.map +1 -1
  105. package/dist/val/CopyFuncVal.d.ts +1 -2
  106. package/dist/val/CopyFuncVal.js +7 -0
  107. package/dist/val/CopyFuncVal.js.map +1 -1
  108. package/dist/val/Decimal.d.ts +1 -0
  109. package/dist/val/Decimal.js +13 -0
  110. package/dist/val/Decimal.js.map +1 -1
  111. package/dist/val/DeprecateFuncVal.d.ts +11 -0
  112. package/dist/val/DeprecateFuncVal.js +47 -0
  113. package/dist/val/DeprecateFuncVal.js.map +1 -0
  114. package/dist/val/DisjunctVal.js +130 -21
  115. package/dist/val/DisjunctVal.js.map +1 -1
  116. package/dist/val/EachFuncVal.d.ts +15 -0
  117. package/dist/val/EachFuncVal.js +75 -0
  118. package/dist/val/EachFuncVal.js.map +1 -0
  119. package/dist/val/ExpectVal.d.ts +1 -0
  120. package/dist/val/ExpectVal.js +41 -4
  121. package/dist/val/ExpectVal.js.map +1 -1
  122. package/dist/val/FeatureVal.js +1 -1
  123. package/dist/val/FeatureVal.js.map +1 -1
  124. package/dist/val/FilterFuncVal.d.ts +15 -0
  125. package/dist/val/FilterFuncVal.js +91 -0
  126. package/dist/val/FilterFuncVal.js.map +1 -0
  127. package/dist/val/FuncBaseVal.d.ts +6 -1
  128. package/dist/val/FuncBaseVal.js +178 -2
  129. package/dist/val/FuncBaseVal.js.map +1 -1
  130. package/dist/val/HideFuncVal.js.map +1 -1
  131. package/dist/val/IdFuncVal.d.ts +13 -0
  132. package/dist/val/IdFuncVal.js +54 -0
  133. package/dist/val/IdFuncVal.js.map +1 -0
  134. package/dist/val/JunctionVal.js +7 -1
  135. package/dist/val/JunctionVal.js.map +1 -1
  136. package/dist/val/KeyFuncVal.d.ts +1 -1
  137. package/dist/val/KeyFuncVal.js +38 -30
  138. package/dist/val/KeyFuncVal.js.map +1 -1
  139. package/dist/val/ListVal.js +117 -17
  140. package/dist/val/ListVal.js.map +1 -1
  141. package/dist/val/LowerFuncVal.js.map +1 -1
  142. package/dist/val/MapVal.js +102 -8
  143. package/dist/val/MapVal.js.map +1 -1
  144. package/dist/val/MatchFuncVal.d.ts +15 -0
  145. package/dist/val/MatchFuncVal.js +107 -0
  146. package/dist/val/MatchFuncVal.js.map +1 -0
  147. package/dist/val/MoveFuncVal.js.map +1 -1
  148. package/dist/val/NilVal.js +24 -0
  149. package/dist/val/NilVal.js.map +1 -1
  150. package/dist/val/OpBaseVal.d.ts +1 -1
  151. package/dist/val/OpBaseVal.js +24 -2
  152. package/dist/val/OpBaseVal.js.map +1 -1
  153. package/dist/val/OpenFuncVal.js +4 -1
  154. package/dist/val/OpenFuncVal.js.map +1 -1
  155. package/dist/val/PackFuncVal.d.ts +15 -0
  156. package/dist/val/PackFuncVal.js +108 -0
  157. package/dist/val/PackFuncVal.js.map +1 -0
  158. package/dist/val/PathFuncVal.js.map +1 -1
  159. package/dist/val/PlaceVal.d.ts +13 -0
  160. package/dist/val/PlaceVal.js +131 -0
  161. package/dist/val/PlaceVal.js.map +1 -0
  162. package/dist/val/PlusOpVal.js +11 -2
  163. package/dist/val/PlusOpVal.js.map +1 -1
  164. package/dist/val/PrefFuncVal.js.map +1 -1
  165. package/dist/val/PrefVal.d.ts +2 -2
  166. package/dist/val/PrefVal.js +78 -23
  167. package/dist/val/PrefVal.js.map +1 -1
  168. package/dist/val/RefVal.d.ts +1 -1
  169. package/dist/val/RefVal.js +158 -30
  170. package/dist/val/RefVal.js.map +1 -1
  171. package/dist/val/ReferFuncVal.d.ts +36 -0
  172. package/dist/val/ReferFuncVal.js +303 -0
  173. package/dist/val/ReferFuncVal.js.map +1 -0
  174. package/dist/val/ScalarKindVal.d.ts +1 -2
  175. package/dist/val/ScalarKindVal.js +0 -11
  176. package/dist/val/ScalarKindVal.js.map +1 -1
  177. package/dist/val/TopVal.js.map +1 -1
  178. package/dist/val/TypeFuncVal.js.map +1 -1
  179. package/dist/val/UpperFuncVal.js.map +1 -1
  180. package/dist/val/Val.d.ts +9 -2
  181. package/dist/val/Val.js +150 -4
  182. package/dist/val/Val.js.map +1 -1
  183. package/dist/val/VarVal.js.map +1 -1
  184. package/dist/val/arith.d.ts +6 -0
  185. package/dist/val/arith.js +170 -0
  186. package/dist/val/arith.js.map +1 -0
  187. package/dist/vet.d.ts +45 -0
  188. package/dist/vet.js +776 -0
  189. package/dist/vet.js.map +1 -0
  190. package/dist/walk.d.ts +2 -0
  191. package/dist/walk.js +91 -0
  192. package/dist/walk.js.map +1 -0
  193. package/grammar/aontu.gbnf +130 -0
  194. package/grammar/aontu.lark +113 -0
  195. package/package.json +30 -15
  196. package/skill/SKILL.md +37 -0
  197. package/skill/error-codes.md +62 -0
  198. package/skill/examples.md +99 -0
  199. package/skill/grammar-card.md +57 -0
  200. package/src/agentsmd.ts +135 -0
  201. package/src/aontu.ts +192 -4
  202. package/src/cli.ts +2858 -71
  203. package/src/ctx.ts +81 -0
  204. package/src/diff.ts +196 -0
  205. package/src/err.ts +52 -8
  206. package/src/graph.ts +135 -0
  207. package/src/hcanon.ts +169 -0
  208. package/src/hints.ts +271 -5
  209. package/src/jsonschema.ts +511 -0
  210. package/src/lang.ts +779 -37
  211. package/src/lsp.ts +281 -47
  212. package/src/mcp-server.ts +187 -0
  213. package/src/mcp.ts +993 -0
  214. package/src/mod-tool.ts +679 -0
  215. package/src/mod.ts +344 -0
  216. package/src/patch.ts +624 -0
  217. package/src/provenance.ts +430 -0
  218. package/src/query.ts +379 -0
  219. package/src/reach.ts +184 -0
  220. package/src/relation.ts +395 -0
  221. package/src/report-sarif.ts +137 -0
  222. package/src/site.ts +36 -1
  223. package/src/std.ts +73 -0
  224. package/src/subsume.ts +690 -0
  225. package/src/trim.ts +195 -0
  226. package/src/tsconfig.json +10 -4
  227. package/src/type.ts +51 -2
  228. package/src/unify.ts +311 -16
  229. package/src/utility.ts +139 -1
  230. package/src/val/AggFuncVal.ts +319 -0
  231. package/src/val/ArithFuncVal.ts +108 -0
  232. package/src/val/BagVal.ts +101 -4
  233. package/src/val/CloseFuncVal.ts +9 -1
  234. package/src/val/ConjunctVal.ts +20 -0
  235. package/src/val/ConstraintVal.ts +1699 -116
  236. package/src/val/CopyFuncVal.ts +7 -1
  237. package/src/val/Decimal.ts +15 -0
  238. package/src/val/DeprecateFuncVal.ts +84 -0
  239. package/src/val/DisjunctVal.ts +139 -28
  240. package/src/val/EachFuncVal.ts +133 -0
  241. package/src/val/ExpectVal.ts +43 -6
  242. package/src/val/FeatureVal.ts +1 -1
  243. package/src/val/FilterFuncVal.ts +154 -0
  244. package/src/val/FuncBaseVal.ts +200 -3
  245. package/src/val/HideFuncVal.ts +0 -2
  246. package/src/val/IdFuncVal.ts +91 -0
  247. package/src/val/JunctionVal.ts +7 -1
  248. package/src/val/KeyFuncVal.ts +39 -35
  249. package/src/val/ListVal.ts +125 -18
  250. package/src/val/LowerFuncVal.ts +0 -1
  251. package/src/val/MapVal.ts +110 -8
  252. package/src/val/MatchFuncVal.ts +176 -0
  253. package/src/val/MoveFuncVal.ts +0 -2
  254. package/src/val/NilVal.ts +25 -0
  255. package/src/val/OpBaseVal.ts +26 -3
  256. package/src/val/OpenFuncVal.ts +4 -2
  257. package/src/val/PackFuncVal.ts +175 -0
  258. package/src/val/PathFuncVal.ts +0 -1
  259. package/src/val/PlaceVal.ts +193 -0
  260. package/src/val/PlusOpVal.ts +11 -2
  261. package/src/val/PrefFuncVal.ts +0 -1
  262. package/src/val/PrefVal.ts +79 -36
  263. package/src/val/RefVal.ts +163 -30
  264. package/src/val/ReferFuncVal.ts +387 -0
  265. package/src/val/ScalarKindVal.ts +0 -13
  266. package/src/val/TopVal.ts +0 -1
  267. package/src/val/TypeFuncVal.ts +0 -2
  268. package/src/val/UpperFuncVal.ts +0 -1
  269. package/src/val/Val.ts +213 -3
  270. package/src/val/VarVal.ts +0 -1
  271. package/src/val/arith.ts +316 -0
  272. package/src/vet.ts +992 -0
  273. package/src/walk.ts +99 -0
package/src/vet.ts ADDED
@@ -0,0 +1,992 @@
1
+ /* Copyright (c) 2025 Richard Rodger, MIT License */
2
+
3
+ // The validation verb: check a data document against a schema document
4
+ // and return a MACHINE-READABLE report (G2 phase 2,
5
+ // docs/capability-review/g2-validation-verb.md).
6
+ //
7
+ // This module is the engine only. The CLI verb, the JSON/SARIF
8
+ // renderers and `--watch` are phase 3 and 5; the Go port is phase 4.
9
+ // Keeping the engine transport-free is the split lsp.ts already uses,
10
+ // and for the same reason: it is the part that has to be unit-testable
11
+ // and embeddable.
12
+ //
13
+ // Two properties of the engine shape everything here, and both were
14
+ // probed rather than assumed:
15
+ //
16
+ // - A CONTRADICTION surfaces as a NilVal in the unified tree, so
17
+ // conflict findings come from a tree walk (the `walkNils` pattern
18
+ // lsp.ts already uses, generalised).
19
+ // - INCOMPLETENESS does not. `{name:"auth"}` against
20
+ // `{name:string, port:integer}` unifies cleanly and leaves
21
+ // `port:integer` standing — no nil, no error. It surfaces only when
22
+ // something tries to GENERATE, which is why vet runs a generate
23
+ // check in an isolated collect context and reads the
24
+ // `incomplete`-class errors out of it. The two verdicts the report
25
+ // distinguishes therefore come from two different mechanisms.
26
+
27
+ import type { TrustOptions, Val } from './type'
28
+
29
+ import { Aontu } from './aontu'
30
+ import {
31
+ dirname, isAbsolute, join as pathJoin, relative as pathRelative,
32
+ resolve as pathResolve,
33
+ } from 'node:path'
34
+
35
+ import { descErr, getHint } from './err'
36
+ import { ConjunctVal } from './val/ConjunctVal'
37
+ import { walkVals, collectNils } from './walk'
38
+ import { sizingResidue } from './val/BagVal'
39
+ import { collectDeprecations, walkBagVals, deprecationMessage } from './utility'
40
+ import { subsumeNode, effectiveDefault } from './subsume'
41
+ // The `--at` refusal is the SAME refusal `get` and `why` give for a
42
+ // path that names nothing, down to the "did you mean" -- so it is that
43
+ // one, not a second spelling of it. A cycle in the module graph
44
+ // (query imports anchorAt from here), and a benign one: both sides
45
+ // use the other only from inside a function body, never at load time.
46
+ import { noPathFinding } from './query'
47
+
48
+
49
+ export type VetVerdict = 'valid' | 'invalid' | 'incomplete' | 'error'
50
+
51
+ export type VetRole = 'data' | 'schema'
52
+
53
+ export type VetSite = {
54
+ file: string
55
+ row: number
56
+ col: number
57
+ // The extent in UTF-16 code units, or -1 when unknown — the same
58
+ // "unknown" row and col already use.
59
+ //
60
+ // THIS IS WHAT MAKES A FINDING REPAIRABLE. `value` is the CANON, not
61
+ // the source text: `port: 0x1F` reports canon `31` at column 7, so a
62
+ // consumer replacing `(col, value.length)` writes `port: 5x1F` and
63
+ // corrupts the document. With `len` the span is `(col, 4)` and the
64
+ // replacement is exact.
65
+ //
66
+ // NEVER GUESSED. Where the span is unknown this is -1 and a consumer
67
+ // must not edit — unlike the LSP, which falls back to canon because a
68
+ // wonky highlight is cosmetic while a wrong edit is a lost file.
69
+ // See ts/src/site.ts for what the extent covers.
70
+ len: number
71
+ role: VetRole
72
+ // The SOURCE TEXT the span covers, or '' when unknown.
73
+ //
74
+ // This is what makes the span SELF-VERIFYING, and it is not the same
75
+ // as `value`. For a scalar the two differ by normalisation — `0x1F`
76
+ // has src `0x1F` and value (canon) `31`. For a COMPOUND the span
77
+ // names the opening token only, exactly as row and col always have:
78
+ // a constraint `min(1)` reports src `min`, and a reference `$.b`
79
+ // reports src `$`.
80
+ //
81
+ // So a consumer must read the document at (row, col, len), compare it
82
+ // to `src`, and REFUSE when they differ — and, seeing `min` where it
83
+ // expected `min(1)`, refuse rather than replace the name and orphan
84
+ // the arguments. Without this field that mistake is undetectable.
85
+ src?: string
86
+ value?: string
87
+ }
88
+
89
+ export type VetFinding = {
90
+ code: string
91
+ class: string
92
+ severity: 'error' | 'warning' | 'info'
93
+ path: string
94
+ message: string
95
+
96
+ // THE REPAIR, not just the diagnosis. `message` is one line by
97
+ // design -- it is the headline, and the frames under it are for a
98
+ // human at a terminal -- but for several codes the part that says
99
+ // what to DO about the failure lived only in those frames, so a
100
+ // machine reader (an agent, a CI annotation, an editor) got the
101
+ // complaint and none of the cure. `0d` is the clearest case: the
102
+ // engine refuses a lossy integer literal and the hint names the
103
+ // exact-decimal escape that fixes it. Populated from the shared
104
+ // hints table (ts/src/hints.ts, mirrored by go/hints.go) whenever
105
+ // the code has one; absent when it does not (the report-layer
106
+ // compat_* codes, notably, carry no hint text).
107
+ //
108
+ // Excluded from spec goldens for the same reason `message` is: it is
109
+ // prose, it is long, and the two ports hold it to the byte through
110
+ // the message tests instead of through every vet row.
111
+ hint?: string
112
+
113
+ sites: VetSite[]
114
+ expected?: string
115
+ actual?: string
116
+ note?: string
117
+ }
118
+
119
+ export type VetReport = {
120
+ verdict: VetVerdict
121
+ truncated: boolean
122
+ findings: VetFinding[]
123
+ }
124
+
125
+ export type VetOptions = {
126
+ at?: string // validate against this path of the schema
127
+ closed?: boolean // close() the anchor for this run
128
+ partial?: boolean // residue is not a failure
129
+ maxErrors?: number // cap the finding list (default 20)
130
+ schemaUrl?: string // provenance label for schema sites
131
+ dataUrl?: string // provenance label for data sites
132
+
133
+ // Where each document CAME FROM, used to resolve its relative
134
+ // `@"file"` loads -- the file path, as `Aontu({path})` takes it, not
135
+ // the directory. Vet takes two documents from its caller rather than
136
+ // from the filesystem, so it cannot know this: without it a modular
137
+ // schema resolved its includes against the process working
138
+ // directory, which fails outside that directory and, worse, silently
139
+ // reads a same-named file that happens to sit there. The two
140
+ // documents get their OWN bases, because they need not live in the
141
+ // same place.
142
+ schemaPath?: string
143
+ dataPath?: string
144
+
145
+ // The trust profile this run evaluates under (G5, docs/trust.md).
146
+ // Vet's whole job is to evaluate a document its caller did not
147
+ // write, so the caller must be able to say what that document is
148
+ // allowed to reach: without this the include chain is the default
149
+ // one, and `@"x.js"` in hostile data is arbitrary code execution in
150
+ // the validating process. A server passes `{include:'none'}`.
151
+ trust?: TrustOptions
152
+ }
153
+
154
+
155
+ // The default cap, exported because the CLI applies it to the WHOLE
156
+ // report across several data files and must not carry a second copy of
157
+ // the number (ts/src/cli.ts).
158
+ export const VET_MAX_ERRORS = 20
159
+
160
+ const DEFAULT_SCHEMA_URL = 'schema'
161
+ const DEFAULT_DATA_URL = 'data'
162
+
163
+
164
+ // Every site in a freshly parsed tree carries the same url, and for a
165
+ // bare parse that url is the empty string: `site.url` is only populated
166
+ // by the multisource loader (ts/src/lang.ts). Vet takes two documents
167
+ // from its CALLER, not from the filesystem, so it stamps provenance
168
+ // itself — which is what lets the report assign site ROLES by
169
+ // provenance rather than by NilVal's source-order heuristic, exactly as
170
+ // the design requires.
171
+ // EVERY SITE NAMES THE FILE WHOSE TEXT IT EXCERPTS (the review's
172
+ // finding F, use-cases/BUGS.md §25). The parser already names the file
173
+ // each value was read from -- a value loaded through `@"lib/types.aon"`
174
+ // carries that path, with that file's row and column -- and this walk
175
+ // used to OVERWRITE every url with the entry document's name. The
176
+ // coordinates stayed the included file's, so a finding cited
177
+ // `entry.aon:3:7` for text that lives three files away, at a line the
178
+ // entry may not even have. A repair agent that follows the site edits
179
+ // the wrong file.
180
+ //
181
+ // Only the values that carry no name of their own are stamped: those
182
+ // are the ones the engine minted rather than read, and the entry is
183
+ // the honest name for them. The urls actually seen are collected, so
184
+ // the report can still tell WHICH DOCUMENT a site belongs to without
185
+ // pretending they all came from one file -- see roleOf.
186
+ function stampUrl(v: any, url: string, seen?: Set<string>): Set<string> {
187
+ const urls = seen ?? new Set<string>()
188
+ urls.add(url)
189
+ walkVals(v, (n: any) => {
190
+ // UNDEFINED counts as unstamped, not just empty: the parser leaves
191
+ // the url undefined on one of its two paths (ts/src/lang.ts), and
192
+ // treating that as a name would put `undefined` in the url set --
193
+ // where the OTHER document's unstamped values would then match it,
194
+ // and every site would read `data`.
195
+ if (null == n.site.url || '' === n.site.url) {
196
+ n.site.url = url
197
+ }
198
+ urls.add(n.site.url)
199
+ return true
200
+ }, new Set())
201
+ return urls
202
+ }
203
+
204
+
205
+ // The provenance a report projects its sites through: which urls
206
+ // belong to the DATA document, and how the caller reached each of the
207
+ // two documents (which is what says how to NAME a third file either of
208
+ // them included).
209
+ type Prov = {
210
+ // The urls the data walk reached. Roles are decided by membership,
211
+ // on the RAW url -- never by a name comparison.
212
+ data: Set<string>
213
+ schemaUrl?: string
214
+ schemaPath?: string
215
+ dataUrl?: string
216
+ dataPath?: string
217
+ }
218
+
219
+
220
+ // A FILE THE READER CAN OPEN. The parser resolves an include to an
221
+ // absolute path, which is the right identity (two files loading the
222
+ // same library by different relative spellings must be one file) and
223
+ // the wrong NAME: a report whose entry reads `contract.aon` and whose
224
+ // included site reads `/home/someone/checkout/types.aon` is a report
225
+ // that cannot be uploaded as SARIF, diffed between machines, or read
226
+ // beside the command that produced it.
227
+ //
228
+ // So an included file is named as the ENTRY'S OWN NAME reaches it:
229
+ // relative to the entry's directory, then re-anchored on however the
230
+ // caller spelled the entry. `vet contract.aon` names `types.aon`;
231
+ // `vet a/b/contract.aon` names `a/b/types.aon`; an absolute entry
232
+ // keeps absolute includes. A caller who passed no path at all has no
233
+ // base to relativise against and gets the url unchanged.
234
+ export function displayFile(
235
+ url: string, label: string, path?: string): string {
236
+ if (url === label || null == path || '' === url || !isAbsolute(url)) {
237
+ return url
238
+ }
239
+ const rel = pathRelative(dirname(pathResolve(path)), url)
240
+ const dir = dirname(label)
241
+ return '.' === dir ? rel : pathJoin(dir, rel)
242
+ }
243
+
244
+
245
+ // The name for one site, taken from the document the site BELONGS to
246
+ // -- which is the role, already decided by url-set membership. Doing
247
+ // it here rather than from a map built at stamping time is not a
248
+ // shortcut: a nil's operands are off the tree by the time the report
249
+ // is built, so a value first seen during the MEET (the commonest
250
+ // schema site there is) would be missing from any such map.
251
+ function displayOf(file: string, role: VetRole, prov: Prov): string {
252
+ return 'data' === role
253
+ ? displayFile(file, prov.dataUrl ?? file, prov.dataPath)
254
+ : displayFile(file, prov.schemaUrl ?? file, prov.schemaPath)
255
+ }
256
+
257
+
258
+ // The ROLE of a site: which of the two documents it belongs to. Not a
259
+ // name comparison -- a data document may itself include another file,
260
+ // and that file's values are still data. Membership of the url set the
261
+ // stamping walk collected is the question, and the answer is `schema`
262
+ // for anything the data walk never reached (an engine-minted value
263
+ // stamped with the schema entry, say).
264
+ function roleOf(file: string, prov: Prov): VetRole {
265
+ return prov.data.has(file) ? 'data' : 'schema'
266
+ }
267
+
268
+
269
+ // `$.a.b`, and `$` for the root. Deliberately NOT delimiter-escaped: a
270
+ // map key may contain any character, including every separator a
271
+ // compact summary might pick, so the path is carried as a JSON string
272
+ // and never parsed back out of a larger token.
273
+ function pathText(path?: string[]): string {
274
+ return '$' + (null != path && 0 < path.length ? '.' + path.join('.') : '')
275
+ }
276
+
277
+
278
+ // `secondary` is the only operand that can be absent — a `closed` or an
279
+ // incomplete finding has one side, a two-site conflict has both — so
280
+ // this is the one nullable input, and every Val that does arrive
281
+ // carries a site and a canon.
282
+ function siteOf(v: any, prov: Prov): VetSite | undefined {
283
+ if (null == v) {
284
+ return undefined
285
+ }
286
+ // The report's `file` is whatever the site carries, and by the time a
287
+ // site reaches a report that is always a stamped name: vet walks both
288
+ // documents before they meet, and the walk reaches the off-peg values
289
+ // a finding can name (ts/src/walk.ts). A consumer therefore reads
290
+ // `file` without a presence check, and the Go port -- whose field is
291
+ // a plain string -- writes the same key.
292
+ //
293
+ // NOT coalesced. The parser leaves the url undefined on one of its
294
+ // two paths (ts/src/lang.ts), and a `?? ''` here would be dead code
295
+ // that hides it: if a value ever reaches a report unstamped, the two
296
+ // ports should disagree loudly rather than quietly agree on an empty
297
+ // name that neither of them meant.
298
+ const file = v.site.url
299
+ // NAMED for the reader, ROLED by the raw url: the two questions are
300
+ // different, and only the first is about how the file is spelled
301
+ // (see displayFile).
302
+ const role = roleOf(file, prov)
303
+ return {
304
+ file: displayOf(file, role, prov),
305
+ row: v.site.row,
306
+ col: v.site.col,
307
+ len: v.site.len,
308
+ role,
309
+ src: v.site.src,
310
+ value: v.canon,
311
+ }
312
+ }
313
+
314
+
315
+ // The data site first — it is the thing to fix — then the schema site.
316
+ // The underlying NilVal fields are untouched: this is a report-layer
317
+ // projection, so the existing error.tsv assertions do not move.
318
+ function sitesOf(nil: any, prov: Prov): VetSite[] {
319
+ // `?? nil`: a failure raised about a CONSTRUCT rather than about a
320
+ // failed meet -- a lossy integer literal, say -- carries no operands
321
+ // at all, and reporting it about ITSELF is what ctx.adderr already
322
+ // does for the same reason. Without the fallback the report built a
323
+ // site out of `undefined` and threw while partitioning it, which is
324
+ // the one thing vet promises not to do: a bad value in the data is
325
+ // DATA, and the caller gets a report.
326
+ const sites: VetSite[] = [siteOf(nil.primary ?? nil, prov) as VetSite]
327
+
328
+ const secondary = siteOf(nil.secondary, prov)
329
+ if (null != secondary) {
330
+ sites.push(secondary)
331
+ }
332
+
333
+ // Partitioned rather than sorted: which of the two NilVal operands is
334
+ // `primary` follows source order within one document, which says
335
+ // nothing useful when one side is a schema and the other is data.
336
+ return [
337
+ ...sites.filter((s) => 'data' === s.role),
338
+ ...sites.filter((s) => 'schema' === s.role),
339
+ ]
340
+ }
341
+
342
+
343
+ // The message text is MATERIALISED on demand, exactly as handleErrors
344
+ // materialises one before a caller sees it: makeNilErr defers it
345
+ // because most NilVals are transient and never rendered, and only the
346
+ // throwing path asks for it. Without this a finding could carry an
347
+ // empty `message` -- which is what the incomplete half of every report
348
+ // did, and what any nil built during the PARSE of a document did.
349
+ function materialise(nil: any, ctx: any): void {
350
+ if (null == nil.msg || '' === nil.msg) {
351
+ descErr(nil, ctx)
352
+ }
353
+ }
354
+
355
+
356
+ // The terminal colour escapes the parser puts in its message text. A
357
+ // RegExp built from a string, not a literal: the escape is a control
358
+ // character, and spelling it `\u001b` keeps the source readable.
359
+ const ANSI_RE = new RegExp('\u001b\\[[0-9;]*m', 'g')
360
+
361
+ function stripAnsi(s: string): string {
362
+ return s.replace(ANSI_RE, '')
363
+ }
364
+
365
+
366
+ function findingOf(nil: any, prov: Prov): VetFinding {
367
+ const details = nil.details ?? {}
368
+ const finding: VetFinding = {
369
+ code: nil.why,
370
+ class: nil.class,
371
+ severity: 'error',
372
+ path: pathText(nil.path),
373
+ // The HEADLINE only, WITHOUT ANSI: the frames below it are for a
374
+ // human reading a terminal, and the first line is the part the two
375
+ // ports hold to byte parity. Materialised before this runs, so it
376
+ // is always there (see materialise above). The escapes matter for
377
+ // one family only -- a parse failure's text comes from the parser,
378
+ // which colours its marker -- and a machine-readable report is no
379
+ // place for terminal control codes.
380
+ message: stripAnsi(nil.msg.split('\n')[0]),
381
+ sites: sitesOf(nil, prov),
382
+ }
383
+
384
+ // The hint, whole, with its detail placeholders filled in exactly as
385
+ // the terminal frame fills them. Trailing whitespace is dropped
386
+ // because it is spacing for the frame that used to follow it, not
387
+ // part of the text; the deliberate blank lines INSIDE a hint are
388
+ // `\n \n` and survive.
389
+ const hint = getHint(nil.why, nil.details)
390
+ if (null != hint && '' !== hint) {
391
+ finding.hint = stripAnsi(hint).replace(/\s+$/, '')
392
+ }
393
+
394
+ // `expected`/`actual` are the admissible-alternatives contract, and
395
+ // the constraint algebra already produces them: G1's atoms attach the
396
+ // normalised residual and the offending value, and `must` attaches
397
+ // the author's message. Read them where they are rather than
398
+ // re-deriving them here.
399
+ if ('string' === typeof details.expected) {
400
+ finding.expected = details.expected
401
+ }
402
+ if ('string' === typeof details.actual) {
403
+ finding.actual = details.actual
404
+ }
405
+ if ('string' === typeof details.message) {
406
+ finding.note = details.message
407
+ }
408
+
409
+ return finding
410
+ }
411
+
412
+
413
+ // Findings are sorted BY VET, not by the walk. The underlying walk
414
+ // iterates raw object keys and the two hosts disagree about their order
415
+ // — `10:… 9:…` yields ["9","10"] in JavaScript, which hoists
416
+ // integer-like keys, against Go's insertion order (ts/src/keyorder.ts
417
+ // exists for exactly this) — so an unsorted report could never be in
418
+ // cross-port parity.
419
+ //
420
+ // The order is by data site (file, row, column), then code, then path.
421
+ // It is carried in ONE key string rather than a cascade of comparisons:
422
+ // the row and column are zero-padded so lexicographic order is numeric
423
+ // order, and NUL joins the fields because no field can contain one.
424
+ // A cascade would need a test per tie-breaker to stay honest; a key
425
+ // needs none, and cannot disagree with itself.
426
+ const ORDER_PAD = 9
427
+
428
+
429
+ function pad(n: number): string {
430
+ return String(n).padStart(ORDER_PAD, '0')
431
+ }
432
+
433
+
434
+ // The walk index is the LAST field, which makes every key unique and
435
+ // the sort below total: two findings can otherwise share everything the
436
+ // key carries — same data site, same code, same path — and a comparator
437
+ // that has to answer "equal" is one more thing to get right in two
438
+ // languages. With the index appended, ties simply keep walk order, in
439
+ // both ports, by construction rather than by the sort's promises.
440
+ function orderKey(f: VetFinding, index: number): string {
441
+ const site = f.sites[0]
442
+ return [
443
+ site.file,
444
+ pad(site.row),
445
+ pad(site.col),
446
+ f.code,
447
+ f.path,
448
+ pad(index),
449
+ ].join('\u0000')
450
+ }
451
+
452
+
453
+ // A DOCUMENT THAT DOES NOT STAND UP, in the finding shape (the
454
+ // review's finding F). `trim` and `relations` answered an unusable
455
+ // document with `verdict: error` and an EMPTY list: the caller learned
456
+ // that something was wrong and nothing about what, which is the one
457
+ // thing a repair loop cannot work with. Both verbs take ONE document,
458
+ // so there is no role to decide -- the document is the thing being
459
+ // checked and the thing to edit, which is what `data` means here.
460
+ //
461
+ // The engine's own first error IS the finding: these verbs add nothing
462
+ // to a diagnosis the evaluator already made, and the FIRST is enough
463
+ // because everything after it is a consequence.
464
+ //
465
+ // The Go twin is failureFinding in go/vet.go.
466
+ export function failureFinding(
467
+ ctx: any, url?: string, failed?: any): VetFinding {
468
+ // ctx.err IS SOMETIMES EMPTY, and the comment that used to stand here
469
+ // said otherwise (use-cases/BUGS.md §43). `&: id(root)` fails with a
470
+ // NIL ROOT and NO COLLECTED ERROR -- the id-spread refusal is the
471
+ // root itself -- and every verb that reports "this document does not
472
+ // stand up" then read `ctx.err[0]` as undefined and died: a TypeError
473
+ // out of `relations`, `reaches` and `jsonschema` in TypeScript, a
474
+ // panic in Go. The one shape where finding F's own invariant, that a
475
+ // document which does not stand up SAYS SO in the finding shape, was
476
+ // answered with a stack trace.
477
+ //
478
+ // `failed` is the caller's own root -- every caller has it, and its
479
+ // condition is `0 < ctx.err.length || root.isNil`, so when the first
480
+ // half is false the second holds and the root IS the reason.
481
+ const nil: any = ctx.err[0] ?? failed
482
+ materialise(nil, ctx)
483
+
484
+ // STAMPED, as vet stamps both documents before they meet: siteOf does
485
+ // not coalesce a missing name (deliberately -- see there), so a site
486
+ // that reached the report unstamped would carry `file: undefined`.
487
+ // The three Vals a finding can name are the nil and its two operands,
488
+ // and the url set collects whatever name each already had, so a value
489
+ // read from an included file keeps that file's name and still counts
490
+ // as part of the one document being checked.
491
+ const at = url ?? ''
492
+ const urls = new Set([at])
493
+ for (const v of [nil, nil.primary, nil.secondary]) {
494
+ if (null == v || null == v.site) {
495
+ continue
496
+ }
497
+ if (null == v.site.url || '' === v.site.url) {
498
+ v.site.url = at
499
+ }
500
+ urls.add(v.site.url)
501
+ }
502
+
503
+ return findingOf(nil, { data: urls })
504
+ }
505
+
506
+
507
+ // Walk the evaluated schema to the anchor path. `$` and `$.a.b` are
508
+ // both accepted, as is the bare `a.b` a shell is likely to hand over
509
+ // unquoted.
510
+ export function anchorAt(root: any, at: string): Val | undefined {
511
+ const trimmed = at.startsWith('$') ? at.slice(1) : at
512
+ const parts = trimmed.split('.').filter((p) => '' !== p)
513
+
514
+ let node: any = root
515
+ for (const part of parts) {
516
+ // A SIZING RESIDUE IS ITS CONTAINER, plus a note about what the
517
+ // container must still satisfy (use-cases/BUGS.md §16). The path
518
+ // steps through it: `$.a.ports.0.port` names the same node whether
519
+ // or not `ports` still carries a `unique()`, and an anchor that
520
+ // stopped here would report `no_path` for a key the document
521
+ // plainly has.
522
+ node = throughResidue(node)
523
+
524
+ // TYPE-DIRECTED, not a property lookup on whatever `peg` happens to
525
+ // be. An anchor is a STRUCTURAL path into the schema — the same
526
+ // thing a reference means by `$.a.b` — so it walks map keys and
527
+ // list indices, and stops at anything else.
528
+ //
529
+ // Indexing the peg generically walked much further than that: into
530
+ // a junction's branches (`a:1|2` with `--at $.a.0` validated
531
+ // against ONE branch), into a constraint's atom arguments (so
532
+ // `min(2)` with `--at $.a.0` reported the bound's own argument as
533
+ // the truth), into a pref's wrapped value through the literal key
534
+ // `peg`, and into an array's `length` — that last one handing back
535
+ // a JavaScript NUMBER as the anchor, after which every document
536
+ // whatsoever came back valid. The Go port has always been
537
+ // type-directed here; this is the canonical side moving to it.
538
+ if (true === node?.isMap) {
539
+ const peg = node.peg
540
+ if (null == peg || !Object.prototype.hasOwnProperty.call(peg, part)) {
541
+ return undefined
542
+ }
543
+ node = peg[part]
544
+ }
545
+ else if (true === node?.isList) {
546
+ // CANONICAL DECIMAL, the spelling a reference uses for a list
547
+ // index (`0`, or a non-zero digit run) -- so `$.a.01` names
548
+ // nothing here exactly as it names nothing there.
549
+ const peg = node.peg
550
+ const index = Number(part)
551
+ if (!/^(0|[1-9][0-9]*)$/.test(part) ||
552
+ !Array.isArray(peg) || peg.length <= index) {
553
+ return undefined
554
+ }
555
+ node = peg[index]
556
+ }
557
+ else {
558
+ return undefined
559
+ }
560
+ }
561
+
562
+ // THE ANCHOR KEEPS ITS ATOM. Stepping THROUGH a residue is right --
563
+ // `$.x.a` names a key of the container whatever the container still
564
+ // has to satisfy -- but ARRIVING at one and handing back the bare
565
+ // container drops a constraint the author wrote, so `--at $.x` vetted
566
+ // clean against a `length` the evaluator enforces. The residue is the
567
+ // honest schema for the node: the meet drives it, and generation
568
+ // settles it, exactly as it does without an anchor.
569
+ return node
570
+ }
571
+
572
+
573
+ // The container inside a settled sizing residue, or the value itself.
574
+ function throughResidue(v: any): any {
575
+ return sizingResidue(v)?.bag ?? v
576
+ }
577
+
578
+
579
+ // Validate `dataSrc` against `schemaSrc`.
580
+ //
581
+ // Never throws for findings: a contradiction in the data is DATA, and
582
+ // the caller gets a report. It throws only when the caller's own inputs
583
+ // are unusable — which is why an unusable schema is a verdict (`error`)
584
+ // rather than an exception too: "the schema is broken" is a fact the
585
+ // agent loop needs to branch on, not an exceptional condition.
586
+ export function vet(
587
+ schemaSrc: string, dataSrc: string, opts?: VetOptions): VetReport {
588
+ const options = opts ?? {}
589
+ const schemaUrl = options.schemaUrl ?? DEFAULT_SCHEMA_URL
590
+ const dataUrl = options.dataUrl ?? DEFAULT_DATA_URL
591
+ const maxErrors = options.maxErrors ?? VET_MAX_ERRORS
592
+
593
+ // ONE instance, two bases: the path rides on each CALL rather than on
594
+ // the constructor, because the schema and the data may live in
595
+ // different directories (Lang.parse takes `opts.path` per parse).
596
+ const aontu = new Aontu(
597
+ null == options.trust ? undefined : { trust: options.trust })
598
+ const schemaOpts = null == options.schemaPath ?
599
+ undefined : { path: options.schemaPath }
600
+ const dataOpts = null == options.dataPath ?
601
+ undefined : { path: options.dataPath }
602
+
603
+ // 1. The schema alone. If it does not stand up on its own, the data
604
+ // is never blamed for it.
605
+ const schemaCtx = aontu.ctx({ collect: true })
606
+ const schemaVal: any = aontu.unify(schemaSrc, schemaOpts, schemaCtx)
607
+ if (0 < schemaCtx.err.length || true === schemaVal?.isNil) {
608
+ // A broken schema REPORTS, exactly as broken data does. It used to
609
+ // answer `findings: []` with exit 4 and nothing else, in both
610
+ // ports: the engine had collected the fault and vet threw it away,
611
+ // so an agent -- or a person -- was told the schema was broken and
612
+ // not what or where. The verdict stays `error` (the fault is in
613
+ // the truth, not in the data, and that distinction is the whole
614
+ // point of the class), but the finding travels with it.
615
+ //
616
+ // The FIRST error only, and the data path's reasoning applies
617
+ // unchanged: later errors in a document that does not stand up are
618
+ // consequences of the first rather than separate things to fix.
619
+ //
620
+ // ONE OF THE TWO IS ALWAYS THERE, and both are nils: the branch
621
+ // condition admits a collected error or a nil root, and every
622
+ // value on `schemaCtx.err` is a NilVal. There is no third case, so
623
+ // there is no guard here -- a guard that cannot fire is dead code,
624
+ // and dead code is what ADR-002 exists to keep out. (One stood
625
+ // here and the TypeScript line report called it covered; the Go
626
+ // gate, which measures blocks, refused the twin.)
627
+ const failure: any =
628
+ 0 < schemaCtx.err.length ? schemaCtx.err[0] : schemaVal
629
+ // The normal path stamps both documents before they meet
630
+ // (stampUrl(anchor...) below), and this early return never reaches
631
+ // it, so it stamps what it is about to report: the unified root,
632
+ // and the failure itself -- a COLLECTED error is minted during
633
+ // unification and hangs off no tree, so nothing else would name
634
+ // it. The walk reaches a failure's operands (ts/src/walk.ts),
635
+ // which is what makes the sites say which file.
636
+ stampUrl(schemaVal, schemaUrl)
637
+ stampUrl(failure, schemaUrl)
638
+ materialise(failure, schemaCtx)
639
+ return {
640
+ verdict: 'error',
641
+ truncated: false,
642
+ // A schema that does not stand up: nothing here is data, so the
643
+ // data-url set is empty and every site reads `schema`.
644
+ findings: [findingOf(failure, { data: new Set<string>() })],
645
+ }
646
+ }
647
+
648
+ // 2. The anchor: the whole schema, or the value at `--at`.
649
+ let anchor: any = schemaVal
650
+ if (null != options.at) {
651
+ anchor = anchorAt(schemaVal, options.at)
652
+ if (null == anchor) {
653
+ // AND IT SAYS WHICH SEGMENT. `--at` naming nothing is an error
654
+ // verdict for the same reason a broken schema is -- the run
655
+ // could not be set up from the truth's side -- and it reports
656
+ // for the same reason too: a caller handed exit 4 and an empty
657
+ // list has nothing to act on.
658
+ return {
659
+ verdict: 'error',
660
+ truncated: false,
661
+ findings: [noPathFinding(schemaVal, options.at)],
662
+ }
663
+ }
664
+ }
665
+
666
+ // 3. Both documents get their provenance stamped BEFORE they meet, so
667
+ // every site in the result knows which document it came from.
668
+ const dataCtx = aontu.ctx({ collect: true })
669
+ const dataVal: any = aontu.parse(dataSrc, dataOpts, dataCtx)
670
+ if (0 < dataCtx.err.length || null == dataVal) {
671
+ // A DATA DOCUMENT THAT WILL NOT PARSE IS THE DATA'S FAULT, and the
672
+ // report says so: verdict `invalid`, with a finding carrying the
673
+ // parser's own code and a site in the data. `error` is left to mean
674
+ // what the exit table says it means -- the run could not be set up
675
+ // from the SCHEMA side.
676
+ //
677
+ // The engine already answered it this way one character earlier: a
678
+ // refused CONSTRUCT (`a: 9007199254740993`) reaches the tree as an
679
+ // ordinary nil and is reported as an invalid data finding. A stray
680
+ // `]` took the throwing path instead and came back as a broken
681
+ // SCHEMA -- the same fault, classified two opposite ways by which
682
+ // branch the parser happened to take.
683
+ //
684
+ // The FIRST error only: the parser stops at the first syntax error,
685
+ // so a second entry would be a consequence of the first rather than
686
+ // a separate thing to fix.
687
+ const failure = dataCtx.err[0]
688
+ if (null == failure) {
689
+ return { verdict: 'error', truncated: false, findings: [] }
690
+ }
691
+ failure.site.url = dataUrl
692
+ materialise(failure, dataCtx)
693
+ return {
694
+ verdict: 'invalid',
695
+ truncated: false,
696
+ findings: [findingOf(failure, { data: new Set([dataUrl]) })],
697
+ }
698
+ }
699
+ stampUrl(anchor, schemaUrl)
700
+ const dataUrls = stampUrl(dataVal, dataUrl)
701
+ // The projection every site in this report goes through: roles by
702
+ // url-set membership, names by how the caller reached each document.
703
+ const prov: Prov = {
704
+ data: dataUrls,
705
+ schemaUrl, schemaPath: options.schemaPath,
706
+ dataUrl, dataPath: options.dataPath,
707
+ }
708
+
709
+ // Default-validity lint (G3 phase 5, re-examined under ADR-004): for
710
+ // every disjunction in the SCHEMA carrying a preference, warn when
711
+ // the effective default is not an instance of any REMAINING
712
+ // alternative (code `pref_not_instance`, class compat, severity
713
+ // warning).
714
+ //
715
+ // What the finding MEANS changed with the admission gate (ADR-004).
716
+ // Before the gate it flagged a soundness hole: the preference held
717
+ // the disjunction open, so `a:*5|string` both generated a value the
718
+ // alternatives refuse AND admitted any same-kind override. The gate
719
+ // closed that hole — a preferred branch now contributes exactly its
720
+ // own value to the admitted set, so a default can no longer be
721
+ // "invalid against its own disjunct" and the enum-with-default idiom
722
+ // (`*'auto'|'literal'|'data'`) is sound as written. The lint is KEPT,
723
+ // as an advisory: a default admitted only because it is the default
724
+ // is also the exact shape of a typo'd default
725
+ // (`level:*wran|info|warn|debug` — the intended `*warn` would be
726
+ // silent), and nothing at meet time can catch that. The
727
+ // repeated-branch spelling (`*warn|warn|...`) states "the default is
728
+ // a first-class member", silences the lint, and — unlike before the
729
+ // gate — enforces exactly the same admitted set. The message names
730
+ // the REMAINING alternatives because that is what was scanned: the
731
+ // preferred branch itself always admits its own default, so the old
732
+ // wording ("any alternative of *5|string") read as false on its face
733
+ // (use-cases/BUGS.md §4).
734
+ const lintFindings: VetFinding[] = []
735
+ walkBagVals(anchor, (v: any, path: string[]): void => {
736
+ if (true === v.isDisjunct && Array.isArray(v.peg)) {
737
+ const d = effectiveDefault(v)
738
+ if (null != d && 'indeterminate' !== d) {
739
+ const rest = v.peg.filter((m: any) => true !== m?.isPref)
740
+ const state: any = {
741
+ profile: 'values', findings: [],
742
+ generalUrl: schemaUrl, specificUrl: schemaUrl,
743
+ }
744
+ const admitted = rest.some(
745
+ (m: any) => 'yes' === subsumeNode(state, path, m, d))
746
+ if (!admitted && 0 < rest.length) {
747
+ lintFindings.push({
748
+ code: 'pref_not_instance',
749
+ class: 'compat',
750
+ severity: 'warning',
751
+ path: pathText(path),
752
+ message: 'the default ' + d.canon +
753
+ ' is not an instance of any remaining alternative of ' +
754
+ v.canon,
755
+ sites: [{
756
+ file: schemaUrl,
757
+ row: d.site?.row ?? -1,
758
+ col: d.site?.col ?? -1,
759
+ len: d.site?.len ?? -1,
760
+ role: 'schema',
761
+ src: d.site?.src ?? '',
762
+ value: d.canon,
763
+ }],
764
+ })
765
+ }
766
+ }
767
+ }
768
+ })
769
+
770
+ // `--closed` sets the flag `close()` itself sets, rather than wrapping
771
+ // the anchor in a CloseFuncVal: the anchor is an already-evaluated
772
+ // tree, and a func value would have to resolve again to have any
773
+ // effect. A scalar anchor has no keys to close, so the flag is only
774
+ // meaningful on a bag.
775
+ if (true === options.closed && (true === anchor.isMap || true === anchor.isList)) {
776
+ anchor.closed = true
777
+ }
778
+
779
+ // THE MEET IS FROM A FRESH PARSE, NOT THE SETTLED SCHEMA (the
780
+ // review's finding C, use-cases/BUGS.md §15).
781
+ //
782
+ // Step 1 evaluated the schema ALONE, to decide whether it stands up
783
+ // before any data is blamed for it. That answer is a diagnosis, and
784
+ // it was also being used as the left side of the meet -- so every
785
+ // reference in the schema had already RESOLVED against the schema's
786
+ // own values and been replaced by them. `a:integer b:$.a` settled to
787
+ // `a:integer b:integer`, and data `{a:3,b:4}` then vetted VALID,
788
+ // while the same four lines as one document refuse with
789
+ // scalar_value. A reference is a statement about the FINAL model, and
790
+ // vet is asking about a model the data is part of.
791
+ //
792
+ // Parsing again is what makes `vet(S,D)` and `eval(S ∪ D)` the same
793
+ // question: the meet runs the fixpoint once, over both documents, so
794
+ // references, spreads and generators all see the data. Parsed trees
795
+ // are single-use, hence a second parse rather than a reuse of step
796
+ // 1's. The lint above still reads the SETTLED tree, where
797
+ // disjunctions are ranked and normalised.
798
+ //
799
+ // ONLY WHEN THERE IS NO `--at`. An anchor is a SUBTREE lifted out of
800
+ // the schema, and an absolute reference inside it (`$.OrderPlaced`,
801
+ // the discriminated-union idiom) names a sibling of the document
802
+ // root -- which the lifted subtree no longer has. The settled tree is
803
+ // where those references have already been resolved and substituted,
804
+ // so an anchored run keeps meeting that, exactly as it always has.
805
+ // Making the rule explicit rather than leaving it to whether
806
+ // anchorAt happens to find the path in an unresolved tree: the two
807
+ // ports answered that differently, which is an ADR-001 divergence
808
+ // waiting to happen.
809
+ const ctx = aontu.ctx({ collect: true })
810
+ let meetAnchor: any = anchor
811
+ if (null == options.at) {
812
+ const meetCtx = aontu.ctx({ collect: true })
813
+ const freshSchema: any = aontu.parse(schemaSrc, schemaOpts, meetCtx)
814
+ if (0 === meetCtx.err.length && null != freshSchema) {
815
+ meetAnchor = freshSchema
816
+ if (true === options.closed &&
817
+ (true === meetAnchor.isMap || true === meetAnchor.isList)) {
818
+ meetAnchor.closed = true
819
+ }
820
+ stampUrl(meetAnchor, schemaUrl)
821
+ }
822
+ }
823
+ const pair = new ConjunctVal({ peg: [meetAnchor, dataVal] }, ctx)
824
+ const unified: any = aontu.unify(pair, undefined, ctx)
825
+
826
+ // 4. Contradictions: every NilVal standing in the result, PLUS the
827
+ // ones that never made it into the tree.
828
+ //
829
+ // The second half is not belt-and-braces. When a parent collapses to
830
+ // a nil the whole subtree goes with it, so `service: close({...})`
831
+ // meeting a typo AND a kind conflict leaves ONE nil in the tree and
832
+ // reports the other only on the context — the vet verb's own
833
+ // motivating example, reporting half of what it found. The language
834
+ // server already walks both for this reason; vet dedups by identity
835
+ // the same way, and skips the transient disjunct-trial sentinel,
836
+ // which is bookkeeping rather than a finding.
837
+ const seen = new Set<any>()
838
+ const nils: any[] = collectNils(unified, seen)
839
+ for (const err of ctx.err) {
840
+ if (true === err?.isNil && '|:trial-nil' !== err.why && !seen.has(err)) {
841
+ seen.add(err)
842
+ nils.push(err)
843
+ }
844
+ }
845
+
846
+ const findings: VetFinding[] = nils.map((n) => {
847
+ materialise(n, ctx)
848
+ return findingOf(n, prov)
849
+ })
850
+
851
+ // 5. Incompleteness: what is left standing that cannot generate. The
852
+ // generate check runs in its own collect context so nothing it
853
+ // raises reaches the caller's error list, and so a schema that is
854
+ // merely unsatisfied does not look like one that is contradicted.
855
+ // No try/catch: in collect mode `gen` records its reasons on the
856
+ // context instead of throwing, which is the whole point of the mode.
857
+ const genCtx: any = aontu.ctx({ collect: true })
858
+ genCtx.root = unified
859
+ // Under `--at` the probe descends through the OUTPUT marks: the
860
+ // caller named this node as the truth to validate against, so a
861
+ // `type()` or `hide()` on it (or propagated into it) is not a reason
862
+ // to check nothing. See AontuContext.probe.
863
+ genCtx.probe = null != options.at
864
+ unified.gen(genCtx)
865
+ for (const err of genCtx.err) {
866
+ // A CONFLICT RAISED AT GENERATION COUNTS TOO (the review's finding
867
+ // C, use-cases/BUGS.md §16). The filter used to keep the
868
+ // `incomplete` class alone, on the reading that step 4 had already
869
+ // found every contradiction -- true while every conflict was
870
+ // decided during the meet, and untrue since a sizing atom or a
871
+ // container `must` may hold a PROVISIONAL reading until generation,
872
+ // which is where no more members can arrive. Dropping those left
873
+ // `vet` answering `valid` for data the evaluator refuses, which is
874
+ // the one disagreement the vet-equals-eval harness exists to catch
875
+ // -- and did.
876
+ //
877
+ // Deduped against step 4 by the same cause key the loop below uses,
878
+ // so a contradiction seen twice is still reported once.
879
+ if ('incomplete' === err.class || 'conflict' === err.class) {
880
+ materialise(err, genCtx)
881
+ findings.push(findingOf(err, prov))
882
+ }
883
+ }
884
+
885
+ // 5b. Deprecation warnings (G3 phase 4): a value that carries the
886
+ // deprecate() record after the meet was USED — the data met a
887
+ // deprecated schema value, or the schema's own default will
888
+ // generate one. Severity `warning` (the slot G2 reserved for
889
+ // exactly this mark), and warnings never touch the verdict below.
890
+ findings.push(...lintFindings)
891
+ for (const { val, path } of collectDeprecations(unified)) {
892
+ const v: any = val
893
+ // The same file/role projection sitesOf makes: the url as stamped
894
+ // (empty when the value belongs to neither document), the role by
895
+ // comparing it to the data document's.
896
+ const file = v.site.url
897
+ findings.push({
898
+ code: 'deprecated',
899
+ class: 'compat',
900
+ severity: 'warning',
901
+ path: pathText(path),
902
+ message: deprecationMessage(v.deprecation),
903
+ sites: [{
904
+ file: displayOf(file, roleOf(file, prov), prov),
905
+ row: v.site.row ?? -1,
906
+ col: v.site.col ?? -1,
907
+ len: v.site.len ?? -1,
908
+ role: roleOf(file, prov),
909
+ src: v.site.src ?? '',
910
+ value: v.canon,
911
+ }],
912
+ })
913
+ }
914
+
915
+ const keyed = findings.map((f, i) => ({ key: orderKey(f, i), finding: f }))
916
+ keyed.sort((a, b) => a.key < b.key ? -1 : 1)
917
+ let ordered = keyed.map((k) => k.finding)
918
+
919
+ // ONE CAUSE, ONE FINDING. A reference resolves by CLONING its target,
920
+ // so a target that later fails can fail once per referrer — same
921
+ // code, same two source sites, a different path each time. Multi-pass
922
+ // collection (G2 phase 6) made this reachable: the pass loop now
923
+ // continues past the erroring pass, so the clones' own folds run too.
924
+ // The dedup key is the CODE plus the SITES (file, row, col, value,
925
+ // role): two findings that name the same meet of the same two source
926
+ // positions are one contradiction observed from two paths. The key is
927
+ // NOT (code, path) — the design's sketch — because the paths are
928
+ // exactly what differ. Sorted order makes the kept finding the first
929
+ // by data site then path, deterministically in both ports.
930
+ //
931
+ // THE KEPT PATH IS THE DEEPEST one (use-cases/BUGS.md §41). A meet
932
+ // that fails inside a REFERENCED map is recorded twice: once at the
933
+ // key that actually conflicts, and once at the enclosing map, which
934
+ // collapsed as a consequence and carries the child's two sites. Both
935
+ // are the same cause; only the deeper one names the field an author
936
+ // or an agent has to edit, and `$.q` for a conflict in `$.q.a` sent a
937
+ // repair loop to rewrite the whole record -- twice over, identically,
938
+ // when two of its fields conflicted. Depth first, then the sort order
939
+ // above, so the choice stays deterministic in both ports.
940
+ const causeKey = (f: VetFinding): string =>
941
+ f.code + '\u0000' + f.sites.map((s) =>
942
+ [s.file, s.row, s.col, s.role, s.value].join('\u0000')).join('\u0000')
943
+ const depth = (f: VetFinding): number => f.path.split('.').length
944
+ const deepest = new Map<string, VetFinding>()
945
+ for (const f of ordered) {
946
+ const cause = causeKey(f)
947
+ const held = deepest.get(cause)
948
+ if (null == held || depth(held) < depth(f)) {
949
+ deepest.set(cause, f)
950
+ }
951
+ }
952
+ const causes = new Set<string>()
953
+ ordered = ordered.filter((f) => {
954
+ const cause = causeKey(f)
955
+ if (causes.has(cause) || deepest.get(cause) !== f) {
956
+ return false
957
+ }
958
+ causes.add(cause)
959
+ return true
960
+ })
961
+
962
+ const truncated = maxErrors < ordered.length
963
+ const kept = truncated ? ordered.slice(0, maxErrors) : ordered
964
+
965
+ // 6. The verdict derives from finding CLASSES, never from codes, so a
966
+ // new code can never change exit behaviour.
967
+ //
968
+ // BY CLASS, NOT BY STAGE. The split used to be positional -- whatever
969
+ // step 4 found counted as contradiction and whatever step 5 added
970
+ // counted as incompleteness -- which stopped being true when a sizing
971
+ // atom or a container `must` began holding a provisional reading
972
+ // until generation (the review's finding C, use-cases/BUGS.md §16). A
973
+ // CONTRADICTION found at generation is still a contradiction: reading
974
+ // it as mere incompleteness answered `incomplete` where the evaluator
975
+ // refuses, and `vet` and `eval` have to agree.
976
+ //
977
+ // So: an error-severity finding that is not INCOMPLETENESS makes the
978
+ // document invalid, wherever it was found -- a contradiction, a parse
979
+ // refusal, an unresolvable reference alike. Warnings (the `compat`
980
+ // class: lint and deprecation) never touch the verdict.
981
+ let verdict: VetVerdict = 'valid'
982
+ const errors = ordered.filter((f) => 'error' === f.severity)
983
+ const unmet = errors.filter((f) => 'incomplete' === f.class).length
984
+ if (unmet < errors.length) {
985
+ verdict = 'invalid'
986
+ }
987
+ else if (0 < unmet && true !== options.partial) {
988
+ verdict = 'incomplete'
989
+ }
990
+
991
+ return { verdict, truncated, findings: kept }
992
+ }