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