@principal-ai/subsystems-core 0.51.4 → 0.51.5

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