@principal-ai/subsystems-core 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 (214) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/boundary.d.ts +104 -0
  3. package/dist/audit/boundary.d.ts.map +1 -0
  4. package/dist/audit/boundary.js +363 -0
  5. package/dist/audit/boundary.js.map +1 -0
  6. package/dist/audit/c4.d.ts +41 -0
  7. package/dist/audit/c4.d.ts.map +1 -0
  8. package/dist/audit/c4.js +41 -0
  9. package/dist/audit/c4.js.map +1 -0
  10. package/dist/audit/engine.d.ts +135 -0
  11. package/dist/audit/engine.d.ts.map +1 -0
  12. package/dist/audit/engine.js +865 -0
  13. package/dist/audit/engine.js.map +1 -0
  14. package/dist/audit/fixes.d.ts +80 -0
  15. package/dist/audit/fixes.d.ts.map +1 -0
  16. package/dist/audit/fixes.js +162 -0
  17. package/dist/audit/fixes.js.map +1 -0
  18. package/dist/audit/graphify-provider.d.ts +51 -0
  19. package/dist/audit/graphify-provider.d.ts.map +1 -0
  20. package/dist/audit/graphify-provider.js +36 -0
  21. package/dist/audit/graphify-provider.js.map +1 -0
  22. package/dist/audit/hash.d.ts +25 -0
  23. package/dist/audit/hash.d.ts.map +1 -0
  24. package/dist/audit/hash.js +53 -0
  25. package/dist/audit/hash.js.map +1 -0
  26. package/dist/audit/index.d.ts +12 -0
  27. package/dist/audit/index.d.ts.map +1 -0
  28. package/dist/audit/index.js +40 -0
  29. package/dist/audit/index.js.map +1 -0
  30. package/dist/audit/local-graphify.d.ts +75 -0
  31. package/dist/audit/local-graphify.d.ts.map +1 -0
  32. package/dist/audit/local-graphify.js +283 -0
  33. package/dist/audit/local-graphify.js.map +1 -0
  34. package/dist/audit/paths.d.ts +16 -0
  35. package/dist/audit/paths.d.ts.map +1 -0
  36. package/dist/audit/paths.js +31 -0
  37. package/dist/audit/paths.js.map +1 -0
  38. package/dist/audit/pure.d.ts +18 -0
  39. package/dist/audit/pure.d.ts.map +1 -0
  40. package/dist/audit/pure.js +50 -0
  41. package/dist/audit/pure.js.map +1 -0
  42. package/dist/audit/report-logic.d.ts +17 -0
  43. package/dist/audit/report-logic.d.ts.map +1 -0
  44. package/dist/audit/report-logic.js +206 -0
  45. package/dist/audit/report-logic.js.map +1 -0
  46. package/dist/audit/report.d.ts +140 -0
  47. package/dist/audit/report.d.ts.map +1 -0
  48. package/dist/audit/report.js +3 -0
  49. package/dist/audit/report.js.map +1 -0
  50. package/dist/audit/trail.d.ts +29 -0
  51. package/dist/audit/trail.d.ts.map +1 -0
  52. package/dist/audit/trail.js +59 -0
  53. package/dist/audit/trail.js.map +1 -0
  54. package/dist/audit/verification.d.ts +98 -0
  55. package/dist/audit/verification.d.ts.map +1 -0
  56. package/dist/audit/verification.js +11 -0
  57. package/dist/audit/verification.js.map +1 -0
  58. package/dist/audit/verify/component.d.ts +68 -0
  59. package/dist/audit/verify/component.d.ts.map +1 -0
  60. package/dist/audit/verify/component.js +500 -0
  61. package/dist/audit/verify/component.js.map +1 -0
  62. package/dist/audit/verify/declarations.d.ts +58 -0
  63. package/dist/audit/verify/declarations.d.ts.map +1 -0
  64. package/dist/audit/verify/declarations.js +227 -0
  65. package/dist/audit/verify/declarations.js.map +1 -0
  66. package/dist/audit/verify/grammar.d.ts +12 -0
  67. package/dist/audit/verify/grammar.d.ts.map +1 -0
  68. package/dist/audit/verify/grammar.js +57 -0
  69. package/dist/audit/verify/grammar.js.map +1 -0
  70. package/dist/audit/verify/index.d.ts +12 -0
  71. package/dist/audit/verify/index.d.ts.map +1 -0
  72. package/dist/audit/verify/index.js +31 -0
  73. package/dist/audit/verify/index.js.map +1 -0
  74. package/dist/audit/verify/parser.d.ts +19 -0
  75. package/dist/audit/verify/parser.d.ts.map +1 -0
  76. package/dist/audit/verify/parser.js +122 -0
  77. package/dist/audit/verify/parser.js.map +1 -0
  78. package/dist/audit/verify/span.d.ts +49 -0
  79. package/dist/audit/verify/span.d.ts.map +1 -0
  80. package/dist/audit/verify/span.js +377 -0
  81. package/dist/audit/verify/span.js.map +1 -0
  82. package/dist/graphify/anchor.d.ts +45 -0
  83. package/dist/graphify/anchor.d.ts.map +1 -0
  84. package/dist/graphify/anchor.js +179 -0
  85. package/dist/graphify/anchor.js.map +1 -0
  86. package/dist/graphify/consolidated.d.ts +259 -0
  87. package/dist/graphify/consolidated.d.ts.map +1 -0
  88. package/dist/graphify/consolidated.js +12 -0
  89. package/dist/graphify/consolidated.js.map +1 -0
  90. package/dist/graphify/construct.d.ts +41 -0
  91. package/dist/graphify/construct.d.ts.map +1 -0
  92. package/dist/graphify/construct.js +106 -0
  93. package/dist/graphify/construct.js.map +1 -0
  94. package/dist/graphify/ids.d.ts +19 -0
  95. package/dist/graphify/ids.d.ts.map +1 -0
  96. package/dist/graphify/ids.js +53 -0
  97. package/dist/graphify/ids.js.map +1 -0
  98. package/dist/graphify/index.d.ts +16 -0
  99. package/dist/graphify/index.d.ts.map +1 -0
  100. package/dist/graphify/index.js +32 -0
  101. package/dist/graphify/index.js.map +1 -0
  102. package/dist/graphify/resolve.d.ts +48 -0
  103. package/dist/graphify/resolve.d.ts.map +1 -0
  104. package/dist/graphify/resolve.js +89 -0
  105. package/dist/graphify/resolve.js.map +1 -0
  106. package/dist/graphify/signature.d.ts +87 -0
  107. package/dist/graphify/signature.d.ts.map +1 -0
  108. package/dist/graphify/signature.js +282 -0
  109. package/dist/graphify/signature.js.map +1 -0
  110. package/dist/graphify/types.d.ts +141 -0
  111. package/dist/graphify/types.d.ts.map +1 -0
  112. package/dist/graphify/types.js +9 -0
  113. package/dist/graphify/types.js.map +1 -0
  114. package/dist/index.d.ts +4 -0
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +9 -1
  117. package/dist/index.js.map +1 -1
  118. package/dist/infra/c4.d.ts +59 -0
  119. package/dist/infra/c4.d.ts.map +1 -0
  120. package/dist/infra/c4.js +106 -0
  121. package/dist/infra/c4.js.map +1 -0
  122. package/dist/infra/index.d.ts +13 -0
  123. package/dist/infra/index.d.ts.map +1 -0
  124. package/dist/infra/index.js +22 -0
  125. package/dist/infra/index.js.map +1 -0
  126. package/dist/infra/jsonc.d.ts +10 -0
  127. package/dist/infra/jsonc.d.ts.map +1 -0
  128. package/dist/infra/jsonc.js +77 -0
  129. package/dist/infra/jsonc.js.map +1 -0
  130. package/dist/infra/terraform.d.ts +41 -0
  131. package/dist/infra/terraform.d.ts.map +1 -0
  132. package/dist/infra/terraform.js +208 -0
  133. package/dist/infra/terraform.js.map +1 -0
  134. package/dist/infra/types.d.ts +107 -0
  135. package/dist/infra/types.d.ts.map +1 -0
  136. package/dist/infra/types.js +47 -0
  137. package/dist/infra/types.js.map +1 -0
  138. package/dist/infra/wrangler.d.ts +32 -0
  139. package/dist/infra/wrangler.d.ts.map +1 -0
  140. package/dist/infra/wrangler.js +177 -0
  141. package/dist/infra/wrangler.js.map +1 -0
  142. package/dist/node.d.ts +3 -0
  143. package/dist/node.d.ts.map +1 -1
  144. package/dist/node.js +4 -1
  145. package/dist/node.js.map +1 -1
  146. package/dist/storage/topic-reference-links.d.ts +3 -3
  147. package/dist/storage/topic-reference-links.d.ts.map +1 -1
  148. package/dist/storage/topic-reference-links.js +23 -8
  149. package/dist/storage/topic-reference-links.js.map +1 -1
  150. package/dist/storage/topic-share.d.ts +69 -0
  151. package/dist/storage/topic-share.d.ts.map +1 -0
  152. package/dist/storage/topic-share.js +67 -0
  153. package/dist/storage/topic-share.js.map +1 -0
  154. package/dist/storage/topic-types.d.ts +5 -1
  155. package/dist/storage/topic-types.d.ts.map +1 -1
  156. package/dist/types/subsystem-model.d.ts +59 -0
  157. package/dist/types/subsystem-model.d.ts.map +1 -1
  158. package/dist/types/subsystem-model.js +50 -1
  159. package/dist/types/subsystem-model.js.map +1 -1
  160. package/dist/validation.d.ts.map +1 -1
  161. package/dist/validation.js +25 -2
  162. package/dist/validation.js.map +1 -1
  163. package/package.json +22 -2
  164. package/schemas/subsystem-model.schema.json +35 -19
  165. package/src/audit/boundary.ts +447 -0
  166. package/src/audit/c4.ts +70 -0
  167. package/src/audit/engine.ts +1099 -0
  168. package/src/audit/fixes.ts +192 -0
  169. package/src/audit/graphify-provider.test.ts +58 -0
  170. package/src/audit/graphify-provider.ts +77 -0
  171. package/src/audit/hash.ts +58 -0
  172. package/src/audit/index.ts +34 -0
  173. package/src/audit/local-graphify.test.ts +163 -0
  174. package/src/audit/local-graphify.ts +354 -0
  175. package/src/audit/paths.ts +25 -0
  176. package/src/audit/pure.ts +91 -0
  177. package/src/audit/report-logic.test.ts +145 -0
  178. package/src/audit/report-logic.ts +245 -0
  179. package/src/audit/report.ts +207 -0
  180. package/src/audit/trail.ts +77 -0
  181. package/src/audit/verification.ts +104 -0
  182. package/src/audit/verify/component.ts +760 -0
  183. package/src/audit/verify/declarations.ts +284 -0
  184. package/src/audit/verify/grammar.ts +57 -0
  185. package/src/audit/verify/index.ts +41 -0
  186. package/src/audit/verify/parser.ts +124 -0
  187. package/src/audit/verify/span.ts +478 -0
  188. package/src/graphify/anchor.ts +206 -0
  189. package/src/graphify/consolidated.ts +298 -0
  190. package/src/graphify/construct.ts +153 -0
  191. package/src/graphify/ids.ts +48 -0
  192. package/src/graphify/index.ts +16 -0
  193. package/src/graphify/resolve.ts +115 -0
  194. package/src/graphify/signature.ts +354 -0
  195. package/src/graphify/types.ts +164 -0
  196. package/src/index.ts +10 -0
  197. package/src/infra/c4.ts +146 -0
  198. package/src/infra/index.ts +21 -0
  199. package/src/infra/infra.test.ts +360 -0
  200. package/src/infra/jsonc.ts +70 -0
  201. package/src/infra/terraform.ts +251 -0
  202. package/src/infra/types.ts +136 -0
  203. package/src/infra/wrangler.ts +203 -0
  204. package/src/node.ts +3 -0
  205. package/src/storage/topic-reference-links.test.ts +7 -1
  206. package/src/storage/topic-reference-links.ts +24 -8
  207. package/src/storage/topic-share.test.ts +91 -0
  208. package/src/storage/topic-share.ts +118 -0
  209. package/src/storage/topic-types.ts +3 -1
  210. package/src/storage/topicStore.test.ts +1 -0
  211. package/src/types/subsystem-model.test.ts +52 -2
  212. package/src/types/subsystem-model.ts +104 -0
  213. package/src/validation.test.ts +71 -7
  214. package/src/validation.ts +27 -2
@@ -0,0 +1,1099 @@
1
+ /**
2
+ * Deterministic subsystem-model audit engine.
3
+ *
4
+ * The engine owns the audit pass: per-component verification, boundary and
5
+ * trail checks, report assembly, fingerprinting, persistence, and provenance
6
+ * stamping. Hosts (Studio, the CLI, a future MCP daemon) supply the concrete
7
+ * adapters for the model store, Graphify, source access, C4 evidence,
8
+ * augmentations, and persistence.
9
+ */
10
+
11
+ import type {
12
+ SubsystemComponent,
13
+ SubsystemTrail,
14
+ } from '../types/subsystem-model'
15
+ import { isUnbuiltComponent, isUnbuiltStep } from '../types/subsystem-model'
16
+ import {
17
+ auditBoundaryFields,
18
+ auditProcessBacking,
19
+ auditProcessVerification,
20
+ dropUnbackedMissing,
21
+ } from './boundary'
22
+ import type { C4AuditElement } from './c4'
23
+ import {
24
+ adoptGraphifyDeclarationRefFixFromVerify,
25
+ adoptGraphifyFileFixFromVerify,
26
+ adoptGraphifySignatureFixFromVerify,
27
+ adoptTreeSitterSpanFixFromVerify,
28
+ installedDependencyPackage,
29
+ storeTypeStale,
30
+ verificationFailureDiagnostic,
31
+ verificationUnavailableFinding,
32
+ } from './fixes'
33
+ import type {
34
+ GraphifyAuditProvider,
35
+ GraphifyAuditReadiness,
36
+ } from './graphify-provider'
37
+ import { hashContentRange } from './hash'
38
+ import { isRepoPurl, purlRepoKey } from './paths'
39
+ import { classifyAuditReport } from './report-logic'
40
+ import type {
41
+ SubsystemModelAuditCheck,
42
+ SubsystemModelAuditFinding,
43
+ SubsystemModelAuditReport,
44
+ } from './report'
45
+ import {
46
+ callsSiteOutsideFrom,
47
+ unconnectedComponentFindings,
48
+ } from './trail'
49
+ import type { AuditComponentVerification } from './verification'
50
+
51
+ /** The model surface the engine reads. Hosts adapt their stored record. */
52
+ export interface AuditModel {
53
+ graphId: string
54
+ title: string
55
+ updatedAt: string
56
+ components: SubsystemComponent[]
57
+ trails?: SubsystemTrail[]
58
+ }
59
+
60
+ export interface AuditModelFileCheck {
61
+ missing: Array<{ componentAlias: string }>
62
+ missingCount: number
63
+ }
64
+
65
+ export interface AuditCallSiteClaim {
66
+ lines: { start: number; end: number }
67
+ contentHash: string
68
+ }
69
+
70
+ export interface AuditGraphifySlot {
71
+ slotKey: string
72
+ builtAt?: string
73
+ }
74
+
75
+ /**
76
+ * Host adapters. Everything here is I/O or host-owned state; the engine holds
77
+ * the audit policy.
78
+ */
79
+ export interface AuditEngineDeps {
80
+ graphifyProvider: GraphifyAuditProvider
81
+
82
+ /** Load the stored model, or null when the id is unknown. */
83
+ loadModel(graphId: string): Promise<AuditModel | null>
84
+
85
+ /** Mechanical file-presence check for the whole model. */
86
+ verifyModelFiles(model: AuditModel): Promise<AuditModelFileCheck>
87
+
88
+ /** Verify one component. The host owns filesystem/Graphify/tree-sitter. */
89
+ verifyComponent(
90
+ graphId: string,
91
+ componentAlias: string,
92
+ options: { graphifyProvider: GraphifyAuditProvider; treeCache: unknown },
93
+ ): Promise<AuditComponentVerification>
94
+
95
+ /** One parse cache per audit pass, opaque to the engine. */
96
+ createSpanTreeCache(): unknown
97
+ disposeSpanTreeCache(cache: unknown): void
98
+
99
+ /** Accepted module-boundary augmentation for an intentional module≠file. */
100
+ findAcceptedModuleAugmentation(input: {
101
+ purl: string
102
+ file: string
103
+ symbol: string
104
+ module: string
105
+ }): Promise<unknown | null>
106
+
107
+ /** Accepted call-site augmentation for a trail step. */
108
+ findAcceptedCallSiteAugmentation(input: {
109
+ purl: string
110
+ file: string
111
+ symbol: string
112
+ targetFile: string
113
+ targetSymbol: string
114
+ mechanism: string
115
+ }): Promise<{ claims: { callSite?: AuditCallSiteClaim } } | null>
116
+
117
+ /** Read one repo's accepted C4 element set. */
118
+ readC4Elements(repoKey: string): Promise<{ elements: readonly C4AuditElement[] }>
119
+
120
+ /** Read a repo-relative file from a checkout. */
121
+ readFile(repoRoot: string, file: string): Promise<string>
122
+
123
+ /** Resolve the declaration enclosing a line in a file. */
124
+ enclosingDeclaration(input: {
125
+ repoRoot: string
126
+ file: string
127
+ line: number
128
+ }): Promise<{ symbol: string; startLine: number; endLine: number } | null>
129
+
130
+ /** Resolve a named declaration in a file. */
131
+ declarationForSymbol(input: {
132
+ repoRoot: string
133
+ file: string
134
+ symbol: string
135
+ }): Promise<{ startLine: number; endLine: number } | null>
136
+
137
+ /** Current HEAD(+dirty) graphify slot identity for fingerprinting. */
138
+ resolveGraphifySlot(
139
+ purl: string,
140
+ options: { repoRoot?: string },
141
+ ): Promise<AuditGraphifySlot | null>
142
+
143
+ /** Persist the report (and its fingerprint). */
144
+ persistReport(
145
+ graphId: string,
146
+ report: SubsystemModelAuditReport,
147
+ fingerprint: string,
148
+ ): Promise<void>
149
+
150
+ /** True when every referenced file is clean in its checkout. */
151
+ referencedFilesClean(
152
+ components: readonly SubsystemComponent[],
153
+ trails: readonly SubsystemTrail[] | undefined,
154
+ ): Promise<boolean>
155
+
156
+ /** Capture one commit per referenced purl repo key. */
157
+ capturePurlCommits(
158
+ components: readonly SubsystemComponent[],
159
+ ): Promise<Record<string, unknown>>
160
+
161
+ /** Stamp the verified commit pin on the model. */
162
+ stampVerifiedCommits(
163
+ graphId: string,
164
+ commits: Record<string, unknown>,
165
+ ): Promise<void>
166
+
167
+ /** Clock override (tests). */
168
+ now?(): Date
169
+
170
+ /** Non-fatal diagnostics. */
171
+ warn?(message: string, err?: unknown): void
172
+ }
173
+
174
+ export type AuditEngineResult =
175
+ | { ok: true; report: SubsystemModelAuditReport; fingerprint: string }
176
+ | { ok: false; error: string }
177
+
178
+ /**
179
+ * Stable fingerprint of model claims + current checkout graphify slot.
180
+ * Changes when the model is edited, HEAD/dirty moves, or the exact slot rebuilds.
181
+ */
182
+ export async function buildAuditFingerprint(
183
+ model: AuditModel,
184
+ graphify: GraphifyAuditReadiness | undefined,
185
+ resolveSlot: AuditEngineDeps['resolveGraphifySlot'],
186
+ ): Promise<string> {
187
+ const claims = [...model.components]
188
+ .map((c) =>
189
+ [
190
+ c.alias,
191
+ c.file ?? '',
192
+ c.symbol ?? '',
193
+ c.construct ?? '',
194
+ purlRepoKey(c.purl) ?? '',
195
+ ].join('\t'),
196
+ )
197
+ .sort()
198
+ .join('\n')
199
+
200
+ const graphifyParts = (
201
+ await Promise.all(
202
+ (graphify?.purls ?? []).map(async (p) => {
203
+ const current = await resolveSlot(p.purl, { repoRoot: p.repoRoot })
204
+ if (!current) return `${p.purl}:${p.status}:`
205
+ const builtAt = current.builtAt ?? ''
206
+ return `${p.purl}:${p.status}:${current.slotKey}:${builtAt}`
207
+ }),
208
+ )
209
+ )
210
+ .sort()
211
+ .join('|')
212
+
213
+ return [
214
+ `updatedAt=${model.updatedAt}`,
215
+ `components=${model.components.length}`,
216
+ `claims=${claims}`,
217
+ `graphify=${graphifyParts}`,
218
+ ].join('\n')
219
+ }
220
+
221
+ /** Run one deterministic audit pass. */
222
+ export async function runSubsystemModelAudit(
223
+ graphId: string,
224
+ deps: AuditEngineDeps,
225
+ ): Promise<AuditEngineResult> {
226
+ const warn = deps.warn ?? (() => undefined)
227
+ try {
228
+ const model = await deps.loadModel(graphId)
229
+ if (!model) return { ok: false, error: `unknown graph: ${graphId}` }
230
+ const graphifyProvider = deps.graphifyProvider
231
+
232
+ // Audit must use the current HEAD(+dirty) graphify slot, not a stale fallback.
233
+ let graphifyEnsure
234
+ try {
235
+ graphifyEnsure = await graphifyProvider.ensureCurrent(model)
236
+ if (graphifyEnsure.failed.length > 0) {
237
+ warn(
238
+ `[audit] graphify ensure incomplete for ${graphId}: ${graphifyEnsure.failed
239
+ .map((f) => `${f.purl} (${f.error})`)
240
+ .join('; ')}`,
241
+ )
242
+ }
243
+ } catch (err) {
244
+ warn(`[audit] graphify ensure failed for ${graphId}:`, err)
245
+ graphifyEnsure = { ensured: [], failed: [] }
246
+ }
247
+
248
+ const files = await deps.verifyModelFiles(model)
249
+ // A proposed component's file is where the code is meant to live, so its
250
+ // absence is expected — never a missing file.
251
+ const proposedAliases = new Set(
252
+ model.components.filter(isUnbuiltComponent).map((c) => c.alias),
253
+ )
254
+ const missingFiles = files.missing.filter((m) => !proposedAliases.has(m.componentAlias))
255
+ const missingFileAliases = new Set(missingFiles.map((m) => m.componentAlias))
256
+
257
+ const findings: SubsystemModelAuditFinding[] = unconnectedComponentFindings(
258
+ model.components,
259
+ model.trails ?? [],
260
+ )
261
+ const checks: SubsystemModelAuditCheck[] = []
262
+
263
+ // One parsed tree-sitter tree per file for the whole pass.
264
+ const treeCache = deps.createSpanTreeCache()
265
+
266
+ // missing_file findings are attached in the per-component loop so we can
267
+ // include a deterministic Graphify file-relocate fix when available.
268
+ // Symbol presence is graphify-only (exact anchor).
269
+
270
+ let unresolved = 0
271
+ let staleDeclarations = 0
272
+ let constructMismatches = 0
273
+ let signatureMismatches = 0
274
+ let weakAnchors = 0
275
+ let okComponents = 0
276
+ let filesVerified = 0
277
+ let symbolsVerified = 0
278
+ let declarationsFresh = 0
279
+ let constructsMatched = 0
280
+ let signaturesMatched = 0
281
+ let anchorsExact = 0
282
+ let externalsSkipped = 0
283
+ let proposedSkipped = 0
284
+ let missingSymbols = 0
285
+
286
+ const seenComponentIssue = new Set<string>([...missingFileAliases])
287
+ // Availability findings are per-repo (purl), not per-component.
288
+ const repoUnresolvedPurls = new Set<string>()
289
+ const cacheUnavailablePurls = new Set<string>()
290
+
291
+ for (const c of model.components) {
292
+ // A proposed claim has no source yet. Skip it; it becomes checkable when
293
+ // its status flips to built.
294
+ if (isUnbuiltComponent(c)) {
295
+ proposedSkipped++
296
+ okComponents++
297
+ checks.push({
298
+ componentAlias: c.alias,
299
+ componentName: c.name,
300
+ construct: c.construct,
301
+ symbol: c.symbol,
302
+ file: c.file || undefined,
303
+ fileExists: null,
304
+ symbolDeclared: null,
305
+ declarationFreshness: 'n/a',
306
+ constructMatch: null,
307
+ signature: 'n/a',
308
+ anchor: 'n/a',
309
+ graphify: 'skipped',
310
+ verdict: 'skipped',
311
+ note: 'proposed — not built yet',
312
+ })
313
+ continue
314
+ }
315
+
316
+ // A deprecated claim's source is gone upstream — deliberately, with a
317
+ // commit recorded. Skip it so the model converges.
318
+ if (c.deprecated) {
319
+ externalsSkipped++
320
+ okComponents++
321
+ checks.push({
322
+ componentAlias: c.alias,
323
+ componentName: c.name,
324
+ construct: c.construct,
325
+ symbol: c.symbol,
326
+ file: c.file || undefined,
327
+ fileExists: null,
328
+ symbolDeclared: null,
329
+ declarationFreshness: 'n/a',
330
+ constructMatch: null,
331
+ signature: 'n/a',
332
+ anchor: 'n/a',
333
+ graphify: 'skipped',
334
+ verdict: 'skipped',
335
+ note: c.removedIn?.commit
336
+ ? `deprecated — removed in ${c.removedIn.commit}`
337
+ : 'deprecated — source removed upstream',
338
+ })
339
+ continue
340
+ }
341
+
342
+ // A claim anchored into an install root is a third-party dependency
343
+ // wearing a repo-relative path. There is nothing to verify here.
344
+ const dependency = installedDependencyPackage(c.file)
345
+ if (dependency) {
346
+ externalsSkipped++
347
+ okComponents++
348
+ findings.push({
349
+ kind: 'third_party_path',
350
+ severity: 'info',
351
+ componentAlias: c.alias,
352
+ componentName: c.name,
353
+ message: `File ${c.file} points into node_modules — installed artifacts are not part of the repo and cannot be verified. Model ${dependency.packageName} as construct "external" with purl "pkg:npm/${dependency.packageName}" and no file, or anchor the claim to the package's real source.`,
354
+ })
355
+ checks.push({
356
+ componentAlias: c.alias,
357
+ componentName: c.name,
358
+ construct: c.construct,
359
+ symbol: c.symbol,
360
+ file: c.file || undefined,
361
+ fileExists: null,
362
+ symbolDeclared: null,
363
+ declarationFreshness: 'n/a',
364
+ constructMatch: null,
365
+ signature: 'n/a',
366
+ anchor: 'n/a',
367
+ graphify: 'skipped',
368
+ verdict: 'skipped',
369
+ note: `installed dependency (${dependency.packageName}) — no repo source declaration check`,
370
+ })
371
+ continue
372
+ }
373
+
374
+ if (c.construct === 'external' || c.construct === 'custom_entity') {
375
+ externalsSkipped++
376
+ okComponents++
377
+ checks.push({
378
+ componentAlias: c.alias,
379
+ componentName: c.name,
380
+ construct: c.construct,
381
+ symbol: c.symbol,
382
+ file: c.file || undefined,
383
+ fileExists: null,
384
+ symbolDeclared: null,
385
+ declarationFreshness: 'n/a',
386
+ constructMatch: null,
387
+ signature: 'n/a',
388
+ anchor: 'n/a',
389
+ graphify: 'skipped',
390
+ verdict: 'skipped',
391
+ note: 'external / custom entity — no source declaration check',
392
+ })
393
+ continue
394
+ }
395
+
396
+ // Declared before the verify call so the catch below can report a
397
+ // per-component skip when verify throws (e.g. a tree-sitter WASM abort).
398
+ const check: SubsystemModelAuditCheck = {
399
+ componentAlias: c.alias,
400
+ componentName: c.name,
401
+ construct: c.construct,
402
+ symbol: c.symbol,
403
+ file: c.file || undefined,
404
+ fileExists: null,
405
+ symbolDeclared: null,
406
+ declarationFreshness: 'n/a',
407
+ constructMatch: null,
408
+ signature: 'n/a',
409
+ anchor: 'n/a',
410
+ graphify: 'unavailable',
411
+ verdict: 'ok',
412
+ }
413
+
414
+ let r: AuditComponentVerification
415
+ try {
416
+ r = await deps.verifyComponent(graphId, c.alias, {
417
+ graphifyProvider,
418
+ treeCache,
419
+ })
420
+ } catch (err) {
421
+ warn(`[audit] verify failed for ${c.alias}:`, err)
422
+ const diagnostic = verificationFailureDiagnostic(err)
423
+ checks.push({
424
+ ...check,
425
+ graphify: 'unavailable',
426
+ verdict: 'skipped',
427
+ note: diagnostic,
428
+ })
429
+ const purl = purlRepoKey(c.purl) ?? c.purl?.trim()
430
+ if (purl && !cacheUnavailablePurls.has(purl)) {
431
+ cacheUnavailablePurls.add(purl)
432
+ unresolved++
433
+ findings.push(verificationUnavailableFinding(purl, err))
434
+ }
435
+ continue
436
+ }
437
+ let issue = seenComponentIssue.has(c.alias)
438
+
439
+ if (!r.file?.repoRoot) {
440
+ const purl = (c.purl || '').trim()
441
+ const repoPurl = isRepoPurl(purl)
442
+ check.fileExists = null
443
+ check.graphify = 'unavailable'
444
+ check.note = repoPurl
445
+ ? `No local repoRoot for ${purl || c.file || c.alias}`
446
+ : `Internal / declaration-only — no code repo for ${purl || c.alias}`
447
+ check.verdict = 'skipped'
448
+ if (repoPurl && !repoUnresolvedPurls.has(purl)) {
449
+ repoUnresolvedPurls.add(purl)
450
+ findings.push({
451
+ kind: 'repo_unresolved',
452
+ severity: 'info',
453
+ purl,
454
+ message: `Repo ${purl} is not available locally — clone it to verify its components`,
455
+ })
456
+ unresolved++
457
+ }
458
+ checks.push(check)
459
+ continue
460
+ }
461
+
462
+ check.fileExists = r.file.exists === true
463
+ if (check.fileExists) filesVerified++
464
+ else {
465
+ issue = true
466
+ const fix = r.fileSuggest
467
+ ? adoptGraphifyFileFixFromVerify(c, r.fileSuggest)
468
+ : undefined
469
+ const candidates = r.fileCandidates?.map((x) => x.file) ?? []
470
+ findings.push({
471
+ kind: 'missing_file',
472
+ severity: 'error',
473
+ componentAlias: c.alias,
474
+ componentName: c.name,
475
+ message: fix
476
+ ? `File not found: ${c.file} — Graphify has ${c.symbol} at ${fix.file} (deterministic update available)`
477
+ : candidates.length > 1
478
+ ? `File not found: ${c.file} — Graphify has ${c.symbol} at multiple paths: ${candidates.join(', ')} (agent judgment required)`
479
+ : `File not found: ${c.file}`,
480
+ fix,
481
+ })
482
+ }
483
+
484
+ if (typeof c.symbol === 'string' && c.symbol.trim()) {
485
+ // Graphify exact anchor ⇒ symbol present. No cache ⇒ leave null.
486
+ if (r.cache?.status === 'ready' && r.anchor?.resolution) {
487
+ check.symbolDeclared = r.anchor.resolution === 'exact'
488
+ if (check.symbolDeclared) symbolsVerified++
489
+ else missingSymbols++
490
+ } else {
491
+ check.symbolDeclared = null
492
+ }
493
+ } else {
494
+ check.symbolDeclared = null
495
+ check.note = 'no symbol claimed'
496
+ }
497
+
498
+ if (r.declaration?.freshness) {
499
+ check.declarationFreshness = r.declaration.freshness
500
+ if (r.declaration.freshness === 'full') declarationsFresh++
501
+ if (r.declaration.freshness === 'unanchored') {
502
+ // An unanchored claim whose declaration span tree-sitter can pin
503
+ // exactly is a deterministic one-click capture, not a hard failure.
504
+ const derivedFix = adoptTreeSitterSpanFixFromVerify(r.declaration)
505
+ if (derivedFix) {
506
+ findings.push({
507
+ kind: 'construct_span_capturable',
508
+ severity: 'info',
509
+ componentAlias: c.alias,
510
+ componentName: c.name,
511
+ message: `No span captured, but the declaration is derivable — ${derivedFix.label}.`,
512
+ fix: derivedFix,
513
+ })
514
+ } else {
515
+ // A hard failure: no captured span and tree-sitter could not
516
+ // derive one deterministically — the agent lane must mint it.
517
+ issue = true
518
+ const deriv = r.declaration.derivation
519
+ const why = deriv?.failedGates?.length
520
+ ? ` (derivation ${deriv.class}: ${deriv.failedGates.join(', ')})`
521
+ : ''
522
+ findings.push({
523
+ kind: 'construct_span_unconfirmed',
524
+ severity: 'error',
525
+ componentAlias: c.alias,
526
+ componentName: c.name,
527
+ message: `No source span captured — capture a span (start/end/content hash) from source to verify this construct.${why}`,
528
+ })
529
+ seenComponentIssue.add(c.alias)
530
+ }
531
+ }
532
+ if (r.declaration.freshness === 'stale') {
533
+ // A warning: the span was captured but drifted.
534
+ const stored = c.declarationSpan
535
+ const fix = adoptGraphifyDeclarationRefFixFromVerify(
536
+ c,
537
+ r.declaration,
538
+ r.anchor,
539
+ )
540
+ findings.push({
541
+ kind: 'construct_span_stale',
542
+ severity: 'info',
543
+ componentAlias: c.alias,
544
+ componentName: c.name,
545
+ message: fix
546
+ ? `Declaration moved — Graphify pins L${fix.declarationSpan.startLine}${
547
+ stored ? ` (model had L${stored.startLine})` : ''
548
+ }`
549
+ : `Declaration span no longer matches source — the content changed (stored L${stored?.startLine ?? '?'}).`,
550
+ fix,
551
+ })
552
+ staleDeclarations++
553
+ }
554
+ }
555
+
556
+ if (r.construct) {
557
+ check.constructMatch = r.construct.match
558
+ check.constructClaimed = r.construct.claimed
559
+ check.constructInferred = r.construct.inferred
560
+ if (r.construct.evidence?.length)
561
+ check.constructEvidence = r.construct.evidence
562
+ if (r.construct.match === true) constructsMatched++
563
+ }
564
+ if (r.construct?.match === null || r.code === 'construct_unconfirmed') {
565
+ findings.push({
566
+ kind: 'construct_unconfirmed',
567
+ severity: 'info',
568
+ componentAlias: c.alias,
569
+ componentName: c.name,
570
+ message: `Construct unclassified — claimed ${r.construct?.claimed ?? c.construct ?? '?'}; classify it from source.${
571
+ r.construct?.evidence?.length
572
+ ? ` (${r.construct.evidence.join('; ')})`
573
+ : ''
574
+ }`,
575
+ })
576
+ }
577
+ if (!r.ok && r.code === 'construct_mismatch') {
578
+ issue = true
579
+ findings.push({
580
+ kind: 'construct_mismatch',
581
+ severity: 'error',
582
+ componentAlias: c.alias,
583
+ componentName: c.name,
584
+ message: r.error ?? 'Construct mismatch',
585
+ })
586
+ constructMismatches++
587
+ seenComponentIssue.add(c.alias)
588
+ }
589
+
590
+ // Store completeness — an in-memory store that declares no type, and a
591
+ // store whose declared type may have drifted. Both are gaps (info).
592
+ if (c.construct === 'store') {
593
+ if (storeTypeStale(c, r.declaration?.freshness)) {
594
+ check.storeType = 'stale'
595
+ findings.push({
596
+ kind: 'store_type_stale',
597
+ severity: 'info',
598
+ componentAlias: c.alias,
599
+ componentName: c.name,
600
+ message: `Store declaration moved — its declared value type may be out of date; re-read the declaration and re-propose \`declaration.valueType\` if the type changed.`,
601
+ })
602
+ } else {
603
+ check.storeType = r.storeTypeUndeclared ? 'undeclared' : 'declared'
604
+ }
605
+ } else {
606
+ check.storeType = 'n/a'
607
+ }
608
+ if (r.storeTypeUndeclared) {
609
+ findings.push({
610
+ kind: 'store_type_undeclared',
611
+ severity: 'info',
612
+ componentAlias: c.alias,
613
+ componentName: c.name,
614
+ message:
615
+ 'In-memory store declares no type — read the state declaration and claim `declaration.valueType` (e.g. `Map<string, FeedState>`) or name its state members.',
616
+ })
617
+ }
618
+
619
+ if (r.signature) {
620
+ if (r.signature.skipped) check.signature = 'skipped'
621
+ else if (r.signature.augmented) {
622
+ check.signature = 'augmented'
623
+ signaturesMatched++
624
+ } else if (r.signature.match) {
625
+ check.signature = 'match'
626
+ signaturesMatched++
627
+ } else {
628
+ check.signature = 'mismatch'
629
+ }
630
+ }
631
+ if (r.signature?.skipped) {
632
+ findings.push({
633
+ kind: 'signature_unconfirmed',
634
+ severity: 'info',
635
+ componentAlias: c.alias,
636
+ componentName: c.name,
637
+ message:
638
+ 'Signature could not be confirmed automatically — claim the declared signature from source.',
639
+ })
640
+ }
641
+ if (!r.ok && r.code === 'signature_mismatch') {
642
+ issue = true
643
+ const fix =
644
+ r.signature != null
645
+ ? adoptGraphifySignatureFixFromVerify(r.signature)
646
+ : undefined
647
+ findings.push({
648
+ kind: 'signature_mismatch',
649
+ severity: 'error',
650
+ componentAlias: c.alias,
651
+ componentName: c.name,
652
+ message: fix
653
+ ? `${r.error ?? 'Signature mismatch'} — model has no named types; graphify does (deterministic fill available)`
654
+ : (r.error ?? 'Signature mismatch'),
655
+ fix,
656
+ })
657
+ signatureMismatches++
658
+ seenComponentIssue.add(c.alias)
659
+ }
660
+
661
+ const hasClaimedSymbol =
662
+ typeof c.symbol === 'string' && c.symbol.trim().length > 0
663
+ const resolution = r.anchor?.resolution
664
+ if (r.cache?.status === 'ready' && resolution) {
665
+ check.anchor = resolution
666
+ if (!hasClaimedSymbol) {
667
+ check.graphify = 'skipped'
668
+ check.note = 'graphify anchor skipped - no symbol claimed'
669
+ } else if (check.fileExists === false) {
670
+ check.graphify = 'unavailable'
671
+ check.note = r.fileSuggest
672
+ ? `claimed file missing — Graphify has symbol at ${r.fileSuggest.file}`
673
+ : r.fileCandidates && r.fileCandidates.length > 1
674
+ ? `claimed file missing — Graphify has symbol at ${r.fileCandidates.map((x) => x.file).join(', ')}`
675
+ : 'graphify anchor skipped - source file missing'
676
+ } else if (resolution === 'exact') {
677
+ anchorsExact++
678
+ check.graphify = 'confirmed'
679
+ } else {
680
+ check.graphify = 'weak'
681
+ const base = { componentAlias: c.alias, componentName: c.name }
682
+ if (resolution === 'ambiguous') {
683
+ issue = true
684
+ findings.push({
685
+ ...base,
686
+ kind: 'symbol_ambiguous',
687
+ severity: 'error',
688
+ message: `Multiple Graphify nodes match ${c.symbol} (${r.anchor?.candidates?.length ?? 0} candidates)`,
689
+ })
690
+ seenComponentIssue.add(c.alias)
691
+ } else {
692
+ // A claimed symbol with no matching declaration is a broken claim.
693
+ issue = true
694
+ findings.push({
695
+ ...base,
696
+ kind: 'symbol_unmatched',
697
+ severity: 'error',
698
+ message: `No Graphify node matches symbol ${c.symbol} in ${c.file}`,
699
+ })
700
+ seenComponentIssue.add(c.alias)
701
+ }
702
+ weakAnchors++
703
+ }
704
+ } else if (r.cache && r.cache.status !== 'ready') {
705
+ check.anchor = 'n/a'
706
+ check.graphify = 'unavailable'
707
+ check.note = `Graphify cache ${r.cache.status}`
708
+ const purl = r.cache.purl
709
+ if (purl && !cacheUnavailablePurls.has(purl)) {
710
+ cacheUnavailablePurls.add(purl)
711
+ findings.push({
712
+ kind: 'graphify_unavailable',
713
+ severity: 'info',
714
+ purl,
715
+ message: `Graphify cache ${r.cache.status} for ${purl} — build it to verify constructs and anchors`,
716
+ })
717
+ unresolved++
718
+ }
719
+ } else {
720
+ check.graphify = 'unavailable'
721
+ }
722
+
723
+ check.verdict = issue ? 'issue' : 'ok'
724
+ if (!issue && r.ok) okComponents++
725
+ checks.push(check)
726
+ }
727
+ deps.disposeSpanTreeCache(treeCache)
728
+
729
+ // --- Boundary membership: process (runtime) + module (containment) ---
730
+ const augmentedModuleAliases = new Set<string>()
731
+ for (const c of model.components) {
732
+ const mod = c.module?.trim()
733
+ if (!mod || !c.file?.trim() || !c.symbol?.trim()) continue
734
+ const purl = c.purl?.trim()
735
+ if (!purl || purl === 'external') continue
736
+ const hit = await deps.findAcceptedModuleAugmentation({
737
+ purl,
738
+ file: c.file,
739
+ symbol: c.symbol,
740
+ module: mod,
741
+ })
742
+ if (hit) augmentedModuleAliases.add(c.alias)
743
+ }
744
+
745
+ const boundary = auditBoundaryFields(model.components, {
746
+ augmentedModuleAliases,
747
+ })
748
+
749
+ // Process-boundary verification — read the accepted element set(s) for the
750
+ // repos this model references. Kept per-repo for the backing check; merged
751
+ // for the boundary read.
752
+ const backingSets = new Map<string, readonly C4AuditElement[]>()
753
+ for (const c of model.components) {
754
+ const repoKey = purlRepoKey(c.purl)
755
+ if (!repoKey || backingSets.has(repoKey)) continue
756
+ const set = await deps.readC4Elements(repoKey)
757
+ backingSets.set(repoKey, set.elements)
758
+ }
759
+ const processVerification = auditProcessVerification(
760
+ model.components,
761
+ [...backingSets.values()].flat(),
762
+ )
763
+ boundary.checks.push(...processVerification.checks)
764
+
765
+ const backingFindings = auditProcessBacking(model.components, backingSets)
766
+ const processFindings = dropUnbackedMissing([
767
+ ...boundary.findings,
768
+ ...processVerification.findings,
769
+ ...backingFindings,
770
+ ])
771
+ for (const f of processFindings) {
772
+ findings.push({
773
+ kind: f.kind,
774
+ severity: f.severity,
775
+ processKey: f.processKey,
776
+ componentAlias: f.componentAlias,
777
+ componentName: f.componentName,
778
+ moduleKey: f.moduleKey,
779
+ message: f.message,
780
+ })
781
+ }
782
+
783
+ // Trail step verification via call site augmentations
784
+ let stepsVerified = 0
785
+ let stepsUnconfirmed = 0
786
+ let stepsStale = 0
787
+ let stepsProposed = 0
788
+ const componentByAlias = new Map(
789
+ model.components.map((c) => [c.alias, c]),
790
+ )
791
+
792
+ for (const trail of model.trails ?? []) {
793
+ for (let stepIndex = 0; stepIndex < trail.steps.length; stepIndex++) {
794
+ const step = trail.steps[stepIndex]!
795
+ const toComponent = componentByAlias.get(step.to)
796
+ const fromComponent = componentByAlias.get(step.from)
797
+
798
+ // A proposed seam is not in the code yet — nothing to resolve.
799
+ if (isUnbuiltStep(step, componentByAlias)) {
800
+ stepsProposed++
801
+ continue
802
+ }
803
+
804
+ // A calls step's site is the caller frame, so the portable schema
805
+ // requires it. Surface stored models from before that requirement as a
806
+ // hard gap so the UI can drive the fix.
807
+ if (step.mechanism === 'calls' && !step.site) {
808
+ findings.push({
809
+ kind: 'step_site_unconfirmed',
810
+ severity: 'error',
811
+ trailId: trail.id,
812
+ step: stepIndex,
813
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: calls step has no site construct (${step.from} → ${step.to}); add the enclosing caller declaration.`,
814
+ })
815
+ }
816
+
817
+ // The step's site purl determines the repo.
818
+ const stepPurl = step.purl?.trim()
819
+ if (!stepPurl || !isRepoPurl(stepPurl)) continue
820
+
821
+ const repoRoot = graphifyProvider.resolveRepoRoot(stepPurl)
822
+ if (!repoRoot) continue
823
+
824
+ // Prefer the step's own span; fall back to the accepted call-site
825
+ // augmentation — the capture lane that mints it.
826
+ let span = step.span
827
+ if (!span && toComponent?.file?.trim() && toComponent?.symbol?.trim()) {
828
+ const aug = await deps.findAcceptedCallSiteAugmentation({
829
+ purl: stepPurl,
830
+ file: step.file,
831
+ symbol: step.symbol,
832
+ targetFile: toComponent.file,
833
+ targetSymbol: toComponent.symbol,
834
+ mechanism: step.mechanism,
835
+ })
836
+ const claim = aug?.claims.callSite
837
+ if (claim) {
838
+ span = {
839
+ startLine: claim.lines.start,
840
+ endLine: claim.lines.end,
841
+ contentHash: claim.contentHash,
842
+ }
843
+ }
844
+ }
845
+
846
+ if (!span) {
847
+ // No captured span — the step is unconfirmed (a gap, not a failure).
848
+ stepsUnconfirmed++
849
+ findings.push({
850
+ kind: 'step_span_unconfirmed',
851
+ severity: 'error',
852
+ trailId: trail.id,
853
+ step: stepIndex,
854
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: step span not captured (${step.from} → ${step.to} via ${step.mechanism})`,
855
+ })
856
+ continue
857
+ }
858
+
859
+ // `calls` claims the site lives in the source construct. Informational
860
+ // so existing models can be reclassified without failing their audits.
861
+ if (callsSiteOutsideFrom(step, fromComponent)) {
862
+ const fromFile = fromComponent?.file?.trim()
863
+ findings.push({
864
+ kind: 'step_site_outside_from',
865
+ severity: 'info',
866
+ trailId: trail.id,
867
+ step: stepIndex,
868
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: calls site is in ${step.file}${step.symbol ? ` (${step.symbol})` : ''}, outside ${step.from}${fromFile ? ` (${fromFile})` : ''}; use mechanism "uses" or model the caller and change "from".`,
869
+ })
870
+ }
871
+
872
+ try {
873
+ const content = await deps.readFile(repoRoot, step.file)
874
+ const currentHash = hashContentRange(
875
+ content,
876
+ span.startLine,
877
+ span.endLine,
878
+ )
879
+ if (currentHash === span.contentHash) {
880
+ stepsVerified++
881
+ } else {
882
+ stepsStale++
883
+ findings.push({
884
+ kind: 'step_span_stale',
885
+ severity: 'info',
886
+ trailId: trail.id,
887
+ step: stepIndex,
888
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: step span changed since verification (lines ${span.startLine}-${span.endLine} in ${step.file})`,
889
+ })
890
+ }
891
+
892
+ // The resolved site construct is the caller/via frame. Verify it
893
+ // independently: the range must be a real declaration, the hash
894
+ // fresh, and the seam line inside it.
895
+ if (step.site) {
896
+ const site = step.site
897
+ const siteHash = hashContentRange(
898
+ content,
899
+ site.span.startLine,
900
+ site.span.endLine,
901
+ )
902
+ if (siteHash !== site.span.contentHash) {
903
+ findings.push({
904
+ kind: 'step_site_stale',
905
+ severity: 'info',
906
+ trailId: trail.id,
907
+ step: stepIndex,
908
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: site construct ${site.symbol} changed since it was captured (lines ${site.span.startLine}-${site.span.endLine} in ${step.file}).`,
909
+ })
910
+ }
911
+ const resolvedSite = await deps
912
+ .enclosingDeclaration({
913
+ repoRoot,
914
+ file: step.file,
915
+ line: site.span.startLine,
916
+ })
917
+ .catch(() => null)
918
+ if (
919
+ !resolvedSite ||
920
+ resolvedSite.symbol !== site.symbol ||
921
+ resolvedSite.startLine !== site.span.startLine ||
922
+ resolvedSite.endLine !== site.span.endLine
923
+ ) {
924
+ findings.push({
925
+ kind: 'step_site_mismatch',
926
+ severity: 'info',
927
+ trailId: trail.id,
928
+ step: stepIndex,
929
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: site construct ${site.symbol} does not resolve to ${step.file}:${site.span.startLine}-${site.span.endLine}${resolvedSite ? ` (found ${resolvedSite.symbol} at ${resolvedSite.startLine}-${resolvedSite.endLine})` : ''}.`,
930
+ })
931
+ }
932
+ if (
933
+ step.span &&
934
+ !(
935
+ site.span.startLine <= step.span.startLine &&
936
+ step.span.endLine <= site.span.endLine
937
+ )
938
+ ) {
939
+ findings.push({
940
+ kind: 'step_site_mismatch',
941
+ severity: 'info',
942
+ trailId: trail.id,
943
+ step: stepIndex,
944
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: site construct ${site.symbol} (${site.span.startLine}-${site.span.endLine}) does not contain the seam (${step.span.startLine}-${step.span.endLine}).`,
945
+ })
946
+ }
947
+ }
948
+
949
+ // The target construct lives in its own repo/file.
950
+ if (step.target) {
951
+ const target = step.target
952
+ const targetRoot = target.purl?.trim()
953
+ ? graphifyProvider.resolveRepoRoot(target.purl)
954
+ : null
955
+ if (targetRoot) {
956
+ try {
957
+ const targetContent = await deps.readFile(targetRoot, target.file)
958
+ if (target.span) {
959
+ const targetHash = hashContentRange(
960
+ targetContent,
961
+ target.span.startLine,
962
+ target.span.endLine,
963
+ )
964
+ if (targetHash !== target.span.contentHash) {
965
+ findings.push({
966
+ kind: 'step_target_stale',
967
+ severity: 'info',
968
+ trailId: trail.id,
969
+ step: stepIndex,
970
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: target construct ${target.symbol} changed since it was captured (lines ${target.span.startLine}-${target.span.endLine} in ${target.file}).`,
971
+ })
972
+ }
973
+ }
974
+ const resolvedTarget = await deps.declarationForSymbol({
975
+ repoRoot: targetRoot,
976
+ file: target.file,
977
+ symbol: target.symbol,
978
+ })
979
+ if (!resolvedTarget) {
980
+ findings.push({
981
+ kind: 'step_target_mismatch',
982
+ severity: 'info',
983
+ trailId: trail.id,
984
+ step: stepIndex,
985
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: target construct ${target.symbol} does not resolve in ${target.file}.`,
986
+ })
987
+ } else if (
988
+ target.span &&
989
+ (resolvedTarget.startLine !== target.span.startLine ||
990
+ resolvedTarget.endLine !== target.span.endLine)
991
+ ) {
992
+ findings.push({
993
+ kind: 'step_target_mismatch',
994
+ severity: 'info',
995
+ trailId: trail.id,
996
+ step: stepIndex,
997
+ message: `Trail "${trail.title}" step ${stepIndex + 1}: target construct ${target.symbol} resolves to ${resolvedTarget.startLine}-${resolvedTarget.endLine}, but the step claims ${target.span.startLine}-${target.span.endLine}.`,
998
+ })
999
+ }
1000
+ } catch {
1001
+ // Target checkout/file unreadable — reported by the repo/file
1002
+ // lanes (or simply not available locally).
1003
+ }
1004
+ }
1005
+ }
1006
+ } catch {
1007
+ // File doesn't exist or can't be read — already covered by
1008
+ // mechanical checks.
1009
+ continue
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ const summary = {
1015
+ components: model.components.length,
1016
+ filesVerified,
1017
+ symbolsVerified,
1018
+ declarationsFresh,
1019
+ constructsMatched,
1020
+ signaturesMatched,
1021
+ anchorsExact,
1022
+ graphifyConfirmed: anchorsExact,
1023
+ externalsSkipped,
1024
+ proposedSkipped,
1025
+ stepsProposed,
1026
+ missingFiles: missingFiles.length,
1027
+ missingSymbols,
1028
+ trailFailures: 0,
1029
+ stepsUnconfirmed,
1030
+ stepsStale,
1031
+ stepsVerified,
1032
+ staleDeclarations,
1033
+ constructMismatches,
1034
+ signatureMismatches,
1035
+ weakAnchors,
1036
+ unresolved,
1037
+ ok: okComponents,
1038
+ modulesClaimed: boundary.summary.modulesClaimed,
1039
+ moduleFileOk: boundary.summary.moduleFileOk,
1040
+ moduleFileMismatch: boundary.summary.moduleFileMismatch,
1041
+ processNestsChecked: boundary.summary.processNestsChecked,
1042
+ processNestOk: boundary.summary.processNestOk,
1043
+ processNestDisagree: boundary.summary.processNestDisagree,
1044
+ processRequired: boundary.summary.processRequired,
1045
+ processClaimed: boundary.summary.processClaimed,
1046
+ processMissing: boundary.summary.processMissing,
1047
+ }
1048
+
1049
+ const needsUpdate = findings.some((f) => f.severity === 'error')
1050
+
1051
+ const report: SubsystemModelAuditReport = {
1052
+ graphId,
1053
+ title: model.title,
1054
+ checkedAt: (deps.now?.() ?? new Date()).toISOString(),
1055
+ needsUpdate,
1056
+ summary,
1057
+ checks,
1058
+ boundaryChecks: boundary.checks,
1059
+ findings,
1060
+ }
1061
+
1062
+ const graphify = await graphifyProvider.readiness(model)
1063
+ const fingerprint = await buildAuditFingerprint(
1064
+ model,
1065
+ graphify,
1066
+ deps.resolveGraphifySlot,
1067
+ )
1068
+ try {
1069
+ await deps.persistReport(graphId, report, fingerprint)
1070
+ } catch (err) {
1071
+ warn(
1072
+ `[audit] failed to persist report for ${graphId}: ${
1073
+ err instanceof Error ? err.message : String(err)
1074
+ }`,
1075
+ )
1076
+ }
1077
+
1078
+ // Provenance: a full pass earns the verified pin, but only against a clean
1079
+ // referenced state.
1080
+ if (classifyAuditReport(report) === 'fully_verified') {
1081
+ try {
1082
+ if (await deps.referencedFilesClean(model.components, model.trails)) {
1083
+ const commits = await deps.capturePurlCommits(model.components)
1084
+ await deps.stampVerifiedCommits(graphId, commits)
1085
+ }
1086
+ } catch (err) {
1087
+ warn(
1088
+ `[audit] failed to stamp verified commits for ${graphId}: ${
1089
+ err instanceof Error ? err.message : String(err)
1090
+ }`,
1091
+ )
1092
+ }
1093
+ }
1094
+
1095
+ return { ok: true, report, fingerprint }
1096
+ } catch (err) {
1097
+ return { ok: false, error: err instanceof Error ? err.message : String(err) }
1098
+ }
1099
+ }