@principal-ai/subsystems-core 0.52.0 → 0.53.1

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 (220) 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 +10 -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 +17 -0
  123. package/dist/infra/index.d.ts.map +1 -0
  124. package/dist/infra/index.js +30 -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/observe.d.ts +102 -0
  131. package/dist/infra/observe.d.ts.map +1 -0
  132. package/dist/infra/observe.js +347 -0
  133. package/dist/infra/observe.js.map +1 -0
  134. package/dist/infra/terraform.d.ts +41 -0
  135. package/dist/infra/terraform.d.ts.map +1 -0
  136. package/dist/infra/terraform.js +208 -0
  137. package/dist/infra/terraform.js.map +1 -0
  138. package/dist/infra/types.d.ts +107 -0
  139. package/dist/infra/types.d.ts.map +1 -0
  140. package/dist/infra/types.js +47 -0
  141. package/dist/infra/types.js.map +1 -0
  142. package/dist/infra/wrangler.d.ts +32 -0
  143. package/dist/infra/wrangler.d.ts.map +1 -0
  144. package/dist/infra/wrangler.js +177 -0
  145. package/dist/infra/wrangler.js.map +1 -0
  146. package/dist/node.d.ts +3 -0
  147. package/dist/node.d.ts.map +1 -1
  148. package/dist/node.js +4 -1
  149. package/dist/node.js.map +1 -1
  150. package/dist/storage/topic-reference-links.d.ts +3 -3
  151. package/dist/storage/topic-reference-links.d.ts.map +1 -1
  152. package/dist/storage/topic-reference-links.js +23 -8
  153. package/dist/storage/topic-reference-links.js.map +1 -1
  154. package/dist/storage/topic-share.d.ts +69 -0
  155. package/dist/storage/topic-share.d.ts.map +1 -0
  156. package/dist/storage/topic-share.js +67 -0
  157. package/dist/storage/topic-share.js.map +1 -0
  158. package/dist/storage/topic-types.d.ts +5 -1
  159. package/dist/storage/topic-types.d.ts.map +1 -1
  160. package/dist/types/subsystem-model.d.ts +59 -0
  161. package/dist/types/subsystem-model.d.ts.map +1 -1
  162. package/dist/types/subsystem-model.js +50 -1
  163. package/dist/types/subsystem-model.js.map +1 -1
  164. package/dist/validation.d.ts.map +1 -1
  165. package/dist/validation.js +25 -2
  166. package/dist/validation.js.map +1 -1
  167. package/package.json +22 -2
  168. package/schemas/subsystem-model.schema.json +35 -19
  169. package/src/audit/boundary.ts +447 -0
  170. package/src/audit/c4.ts +70 -0
  171. package/src/audit/engine.ts +1099 -0
  172. package/src/audit/fixes.ts +192 -0
  173. package/src/audit/graphify-provider.test.ts +58 -0
  174. package/src/audit/graphify-provider.ts +77 -0
  175. package/src/audit/hash.ts +58 -0
  176. package/src/audit/index.ts +34 -0
  177. package/src/audit/local-graphify.test.ts +163 -0
  178. package/src/audit/local-graphify.ts +354 -0
  179. package/src/audit/paths.ts +25 -0
  180. package/src/audit/pure.ts +91 -0
  181. package/src/audit/report-logic.test.ts +145 -0
  182. package/src/audit/report-logic.ts +245 -0
  183. package/src/audit/report.ts +207 -0
  184. package/src/audit/trail.ts +77 -0
  185. package/src/audit/verification.ts +104 -0
  186. package/src/audit/verify/component.ts +760 -0
  187. package/src/audit/verify/declarations.ts +284 -0
  188. package/src/audit/verify/grammar.ts +57 -0
  189. package/src/audit/verify/index.ts +41 -0
  190. package/src/audit/verify/parser.ts +124 -0
  191. package/src/audit/verify/span.ts +478 -0
  192. package/src/graphify/anchor.ts +206 -0
  193. package/src/graphify/consolidated.ts +298 -0
  194. package/src/graphify/construct.ts +153 -0
  195. package/src/graphify/ids.ts +48 -0
  196. package/src/graphify/index.ts +16 -0
  197. package/src/graphify/resolve.ts +115 -0
  198. package/src/graphify/signature.ts +354 -0
  199. package/src/graphify/types.ts +164 -0
  200. package/src/index.ts +11 -0
  201. package/src/infra/c4.ts +146 -0
  202. package/src/infra/index.ts +36 -0
  203. package/src/infra/infra.test.ts +360 -0
  204. package/src/infra/jsonc.ts +70 -0
  205. package/src/infra/observe.test.ts +202 -0
  206. package/src/infra/observe.ts +451 -0
  207. package/src/infra/terraform.ts +251 -0
  208. package/src/infra/types.ts +136 -0
  209. package/src/infra/wrangler.ts +203 -0
  210. package/src/node.ts +3 -0
  211. package/src/storage/topic-reference-links.test.ts +7 -1
  212. package/src/storage/topic-reference-links.ts +24 -8
  213. package/src/storage/topic-share.test.ts +91 -0
  214. package/src/storage/topic-share.ts +118 -0
  215. package/src/storage/topic-types.ts +3 -1
  216. package/src/storage/topicStore.test.ts +1 -0
  217. package/src/types/subsystem-model.test.ts +52 -2
  218. package/src/types/subsystem-model.ts +104 -0
  219. package/src/validation.test.ts +71 -7
  220. package/src/validation.ts +27 -2
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Local Graphify cache reader shared by audit hosts.
3
+ *
4
+ * A subsystem audit must use the graph for the *current* HEAD(+dirty) slot,
5
+ * not a stale fallback. This module owns the on-disk layout and git probe so a
6
+ * CLI host and Studio compute identical slot keys and fingerprints from the
7
+ * same `~/.principal/graphify-graphs` store.
8
+ *
9
+ * The transport stays swappable: this is a read-only local-cache provider. A
10
+ * host may supply `ensureCurrent` (Studio builds caches, an MCP daemon would
11
+ * build remotely); when omitted, missing slots are reported explicitly rather
12
+ * than fabricated.
13
+ */
14
+
15
+ import { spawnSync } from 'node:child_process'
16
+ import { createHash } from 'node:crypto'
17
+ import { existsSync, readFileSync, statSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { join } from 'node:path'
20
+ import type { AuditGraphifySlot } from './engine'
21
+ import type {
22
+ GraphifyAuditEnsureResult,
23
+ GraphifyAuditModel,
24
+ GraphifyAuditProvider,
25
+ GraphifyAuditReadiness,
26
+ GraphifyAuditSnapshot,
27
+ } from './graphify-provider'
28
+ import { cacheGraphifyAuditProvider } from './graphify-provider'
29
+ import { isRepoPurl, purlRepoKey } from './paths'
30
+
31
+ const GIT_STDOUT_MAX_BYTES = 32 * 1024 * 1024
32
+ const UNTRACKED_HASH_MAX_BYTES = 1_048_576
33
+ const GIT_PROBE_TTL_MS = 2000
34
+
35
+ /** Absolute root of the graphify cache. `PRINCIPAL_GRAPHIFY_GRAPHS_HOME` overrides it. */
36
+ export function localGraphifyStoreRoot(): string {
37
+ const override = process.env['PRINCIPAL_GRAPHIFY_GRAPHS_HOME']?.trim()
38
+ return override ? override : join(homedir(), '.principal', 'graphify-graphs')
39
+ }
40
+
41
+ /** Filesystem-safe directory name for a purl repo key. */
42
+ export function sanitizePurlDirName(purlKey: string): string {
43
+ const stripped = purlKey.replace(/^pkg:/i, '')
44
+ const cleaned = stripped
45
+ .replace(/[^a-zA-Z0-9._-]+/g, '-')
46
+ .replace(/-+/g, '-')
47
+ .replace(/^-|-$/g, '')
48
+ .toLowerCase()
49
+ return cleaned || 'unknown'
50
+ }
51
+
52
+ /** Slot folder: clean `headSha`, or `headSha+dirtyHash` when dirty. */
53
+ export function cacheSlotKey(
54
+ headSha: string,
55
+ dirtyHash: string | null,
56
+ ): string {
57
+ return dirtyHash ? `${headSha}+${dirtyHash}` : headSha
58
+ }
59
+
60
+ function slotDir(
61
+ storeRoot: string,
62
+ purlKey: string,
63
+ headSha: string,
64
+ dirtyHash: string | null,
65
+ ): string {
66
+ return join(
67
+ storeRoot,
68
+ sanitizePurlDirName(purlKey),
69
+ cacheSlotKey(headSha, dirtyHash),
70
+ )
71
+ }
72
+
73
+ function gitStdout(repoRoot: string, args: string[]): string | null {
74
+ const proc = spawnSync('git', ['-C', repoRoot, ...args], {
75
+ encoding: 'utf8',
76
+ maxBuffer: GIT_STDOUT_MAX_BYTES,
77
+ stdio: ['ignore', 'pipe', 'ignore'],
78
+ })
79
+ if (proc.status !== 0) return null
80
+ return (proc.stdout ?? '').slice(0, GIT_STDOUT_MAX_BYTES)
81
+ }
82
+
83
+ function computeDirtyHash(
84
+ status: string,
85
+ diff: string,
86
+ untrackedRaw: string,
87
+ repoRoot: string,
88
+ ): string {
89
+ const hasher = createHash('sha256')
90
+ hasher.update('status\0')
91
+ hasher.update(status)
92
+ hasher.update('\0diff\0')
93
+ hasher.update(diff)
94
+ hasher.update('\0untracked\0')
95
+ if (untrackedRaw) {
96
+ const paths = untrackedRaw.split('\0').filter(Boolean)
97
+ paths.sort()
98
+ for (const rel of paths) {
99
+ hasher.update(rel)
100
+ hasher.update('\0')
101
+ const abs = join(repoRoot, rel)
102
+ try {
103
+ const st = statSync(abs)
104
+ if (!st.isFile()) {
105
+ hasher.update(`dir:${st.size}\0`)
106
+ continue
107
+ }
108
+ hasher.update(`size:${st.size}\0`)
109
+ if (st.size <= UNTRACKED_HASH_MAX_BYTES) {
110
+ hasher.update(readFileSync(abs))
111
+ } else {
112
+ hasher.update(`mtime:${Math.floor(st.mtimeMs)}\0`)
113
+ }
114
+ } catch {
115
+ hasher.update('missing\0')
116
+ }
117
+ hasher.update('\0')
118
+ }
119
+ }
120
+ return hasher.digest('hex').slice(0, 16)
121
+ }
122
+
123
+ interface GitProbe {
124
+ at: number
125
+ headSha: string | null
126
+ dirtyHash: string | null
127
+ }
128
+
129
+ export interface LocalGraphifyConfig {
130
+ /** Resolve a purl repo key to a local checkout root. */
131
+ resolveRepoRoot(purl: string): string | null
132
+ /** Override the cache root (also settable via env). */
133
+ storeRoot?: string
134
+ /**
135
+ * Optional build hook. When omitted, `ensureCurrent` reports missing slots
136
+ * explicitly instead of extracting a graph.
137
+ */
138
+ ensureCurrent?: (
139
+ model: GraphifyAuditModel,
140
+ ) => Promise<GraphifyAuditEnsureResult>
141
+ }
142
+
143
+ export interface CurrentLocalGraphifySlot {
144
+ purlKey: string
145
+ repoRoot: string
146
+ headSha: string
147
+ dirtyHash: string | null
148
+ slotKey: string
149
+ cached: { path: string; builtAt?: string } | null
150
+ }
151
+
152
+ /** A read-only view of the local graphify cache for one audit host. */
153
+ export class LocalGraphifyCache {
154
+ private readonly probes = new Map<string, GitProbe>()
155
+
156
+ constructor(private readonly config: LocalGraphifyConfig) {}
157
+
158
+ private root(): string {
159
+ return this.config.storeRoot?.trim() || localGraphifyStoreRoot()
160
+ }
161
+
162
+ resolveRepoRoot(purl: string): string | null {
163
+ return this.config.resolveRepoRoot(purl)
164
+ }
165
+
166
+ private probe(repoRoot: string): GitProbe {
167
+ const cached = this.probes.get(repoRoot)
168
+ if (cached && Date.now() - cached.at < GIT_PROBE_TTL_MS) return cached
169
+ const headSha = gitStdout(repoRoot, ['rev-parse', 'HEAD'])?.trim() || null
170
+ const status = gitStdout(repoRoot, ['status', '--porcelain=v1'])
171
+ let dirtyHash: string | null = null
172
+ if (headSha && status?.trim()) {
173
+ const diff =
174
+ gitStdout(repoRoot, ['diff', 'HEAD', '--binary']) ?? ''
175
+ const untrackedRaw =
176
+ gitStdout(repoRoot, [
177
+ 'ls-files',
178
+ '-z',
179
+ '--others',
180
+ '--exclude-standard',
181
+ ]) ?? ''
182
+ dirtyHash = computeDirtyHash(status, diff, untrackedRaw, repoRoot)
183
+ }
184
+ const probe: GitProbe = { at: Date.now(), headSha, dirtyHash }
185
+ this.probes.set(repoRoot, probe)
186
+ return probe
187
+ }
188
+
189
+ /** Resolve the exact current-HEAD(+dirty) slot for a purl. */
190
+ async currentSlot(
191
+ purl: string,
192
+ options?: { repoRoot?: string },
193
+ ): Promise<CurrentLocalGraphifySlot | null> {
194
+ const purlKey = purlRepoKey(purl)
195
+ if (!purlKey) return null
196
+ const repoRoot =
197
+ options?.repoRoot?.trim() || this.config.resolveRepoRoot(purlKey)
198
+ if (!repoRoot || !existsSync(repoRoot)) return null
199
+ const { headSha, dirtyHash } = this.probe(repoRoot)
200
+ if (!headSha) return null
201
+ const slotKey = cacheSlotKey(headSha, dirtyHash)
202
+ const dir = slotDir(this.root(), purlKey, headSha, dirtyHash)
203
+ const graphPath = join(dir, 'graph.json')
204
+ const metaPath = join(dir, 'meta.json')
205
+ let cached: CurrentLocalGraphifySlot['cached'] = null
206
+ if (existsSync(graphPath) && existsSync(metaPath)) {
207
+ try {
208
+ const meta = JSON.parse(
209
+ readFileSync(metaPath, 'utf8'),
210
+ ) as { builtAt?: string }
211
+ cached = { path: graphPath, builtAt: meta.builtAt }
212
+ } catch {
213
+ /* treat as missing */
214
+ }
215
+ }
216
+ return {
217
+ purlKey,
218
+ repoRoot,
219
+ headSha,
220
+ dirtyHash,
221
+ slotKey,
222
+ cached,
223
+ }
224
+ }
225
+
226
+ /** Fingerprint input: the current slot key + when that slot was built. */
227
+ async resolveGraphifySlot(
228
+ purl: string,
229
+ options?: { repoRoot?: string },
230
+ ): Promise<AuditGraphifySlot | null> {
231
+ const slot = await this.currentSlot(purl, options)
232
+ if (!slot) return null
233
+ return { slotKey: slot.slotKey, builtAt: slot.cached?.builtAt }
234
+ }
235
+
236
+ async readiness(
237
+ model: GraphifyAuditModel,
238
+ buildingPurls?: ReadonlySet<string>,
239
+ ): Promise<GraphifyAuditReadiness> {
240
+ const seen = new Set<string>()
241
+ const statuses: GraphifyAuditReadiness['purls'] = []
242
+ for (const component of model.components) {
243
+ const key = purlRepoKey(component.purl)
244
+ if (!key || !isRepoPurl(key) || seen.has(key)) continue
245
+ seen.add(key)
246
+ const repoRoot = this.config.resolveRepoRoot(key) ?? undefined
247
+ if (buildingPurls?.has(key)) {
248
+ statuses.push({ purl: key, status: 'building', repoRoot })
249
+ continue
250
+ }
251
+ const slot = await this.currentSlot(key, { repoRoot })
252
+ if (!slot) {
253
+ statuses.push({ purl: key, status: 'unavailable' })
254
+ continue
255
+ }
256
+ statuses.push({
257
+ purl: key,
258
+ status: slot.cached ? 'ready' : 'missing',
259
+ repoRoot: slot.repoRoot,
260
+ })
261
+ }
262
+ statuses.sort((a, b) => a.purl.localeCompare(b.purl))
263
+ const all = statuses.map((p) => p.status)
264
+ let status: GraphifyAuditReadiness['status']
265
+ if (all.length === 0) status = 'unavailable'
266
+ else if (all.includes('building')) status = 'running'
267
+ else if (all.every((s) => s === 'ready')) status = 'possible'
268
+ else if (all.includes('ready')) status = 'partial'
269
+ else if (all.includes('missing')) status = 'not_ready'
270
+ else status = 'unavailable'
271
+ return { status, purls: statuses }
272
+ }
273
+
274
+ async loadGraph(
275
+ purl: string,
276
+ options?: { repoRoot?: string },
277
+ ): Promise<GraphifyAuditSnapshot | null> {
278
+ const slot = await this.currentSlot(purl, options)
279
+ if (!slot?.cached) return null
280
+ try {
281
+ const graph = JSON.parse(
282
+ readFileSync(slot.cached.path, 'utf8'),
283
+ ) as { nodes?: unknown[]; links?: unknown[]; edges?: unknown[] }
284
+ if (!Array.isArray(graph.nodes)) return null
285
+ const edges = graph.links ?? graph.edges ?? []
286
+ return {
287
+ nodes: graph.nodes,
288
+ edges: Array.isArray(edges) ? edges : [],
289
+ }
290
+ } catch {
291
+ return null
292
+ }
293
+ }
294
+
295
+ /** Read-only default: report missing current slots instead of building. */
296
+ async ensureCurrent(
297
+ model: GraphifyAuditModel,
298
+ ): Promise<GraphifyAuditEnsureResult> {
299
+ if (this.config.ensureCurrent) {
300
+ return this.config.ensureCurrent(model)
301
+ }
302
+ const ensured: string[] = []
303
+ const failed: GraphifyAuditEnsureResult['failed'] = []
304
+ const seen = new Set<string>()
305
+ for (const component of model.components) {
306
+ const key = purlRepoKey(component.purl)
307
+ if (!key || !isRepoPurl(key) || seen.has(key)) continue
308
+ seen.add(key)
309
+ const slot = await this.currentSlot(key)
310
+ if (slot?.cached) {
311
+ ensured.push(key)
312
+ } else if (!slot) {
313
+ failed.push({
314
+ purl: key,
315
+ error:
316
+ 'no local checkout for this purl — register the repo in Alexandria',
317
+ })
318
+ } else {
319
+ failed.push({
320
+ purl: key,
321
+ error: `no graphify cache for the current HEAD(+dirty) slot ${slot.slotKey} — build it in Subsystems Studio or via an MCP Graphify provider`,
322
+ })
323
+ }
324
+ }
325
+ return { ensured, failed }
326
+ }
327
+
328
+ /** The GraphifyAuditProvider port, with per-pass snapshot caching. */
329
+ provider(): GraphifyAuditProvider {
330
+ return cacheGraphifyAuditProvider({
331
+ ensureCurrent: (model) => this.ensureCurrent(model),
332
+ readiness: (model, building) => this.readiness(model, building),
333
+ resolveRepoRoot: (purl) => this.config.resolveRepoRoot(purl),
334
+ loadGraph: (purl, options) => this.loadGraph(purl, options),
335
+ })
336
+ }
337
+ }
338
+
339
+ /** Convenience factory: a cached provider + fingerprint resolver for one host. */
340
+ export function createLocalGraphifyAuditProvider(
341
+ config: LocalGraphifyConfig,
342
+ ): GraphifyAuditProvider & {
343
+ resolveGraphifySlot(
344
+ purl: string,
345
+ options?: { repoRoot?: string },
346
+ ): Promise<AuditGraphifySlot | null>
347
+ } {
348
+ const cache = new LocalGraphifyCache(config)
349
+ const provider = cache.provider()
350
+ return Object.assign(provider, {
351
+ resolveGraphifySlot: (purl: string, options?: { repoRoot?: string }) =>
352
+ cache.resolveGraphifySlot(purl, options),
353
+ })
354
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Purl helpers shared by the audit engine.
3
+ *
4
+ * A component's `file` is relative to its own repo, identified by the purl
5
+ * repo key (fragment stripped). These are pure string helpers so the engine
6
+ * can group claims by repository without depending on a viewer package.
7
+ */
8
+
9
+ /** Normalize a purl to its repo key: fragment and surrounding whitespace stripped. */
10
+ export function purlRepoKey(purl: string | undefined): string | undefined {
11
+ if (!purl) return undefined
12
+ const base = purl.split('#')[0]?.trim()
13
+ return base || undefined
14
+ }
15
+
16
+ /**
17
+ * True when a purl identifies a code repo checkout a host can resolve
18
+ * locally. `external:` and other pseudo-purls are stable identities, not
19
+ * checkouts.
20
+ */
21
+ export function isRepoPurl(purl: string | undefined): boolean {
22
+ const key = purlRepoKey(purl)
23
+ if (!key) return false
24
+ return /^pkg:github\//i.test(key)
25
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Browser-safe audit exports.
3
+ *
4
+ * The audit engine and source hashing are Node-only (filesystem, crypto). This
5
+ * barrel holds the pure policy, types, and report rules so the main package
6
+ * entry can re-export them without pulling Node built-ins into a browser
7
+ * bundle. Node consumers use `./audit` for the full surface.
8
+ */
9
+
10
+ export {
11
+ cacheGraphifyAuditProvider,
12
+ type GraphifyAuditModel,
13
+ type GraphifyAuditEnsureResult,
14
+ type GraphifyAuditPurlReadiness,
15
+ type GraphifyAuditReadiness,
16
+ type GraphifyAuditSnapshot,
17
+ type GraphifyAuditProvider,
18
+ } from './graphify-provider'
19
+ export type {
20
+ AuditSpanFreshness,
21
+ SubsystemModelAuditFindingKind,
22
+ SubsystemModelAuditSeverity,
23
+ SubsystemModelAuditFix,
24
+ SubsystemModelAuditFixGroup,
25
+ SubsystemModelAuditFinding,
26
+ SubsystemModelAuditCheck,
27
+ SubsystemModelAuditBoundaryCheck,
28
+ SubsystemModelAuditReport,
29
+ SubsystemVerificationLane,
30
+ VerificationLaneStatus,
31
+ SubsystemModelVerificationLayer,
32
+ SubsystemModelVerification,
33
+ } from './report'
34
+ export {
35
+ auditBoundaryFields,
36
+ auditProcessBacking,
37
+ auditProcessVerification,
38
+ dropUnbackedMissing,
39
+ moduleAgreesWithFile,
40
+ normalizeBoundaryPath,
41
+ requiresProcess,
42
+ type BoundaryAuditFinding,
43
+ type BoundaryAuditResult,
44
+ type BoundaryCheckKind,
45
+ type BoundaryCheckVerdict,
46
+ type BoundaryComponentCheck,
47
+ } from './boundary'
48
+ export {
49
+ verifyProcessBoundaries,
50
+ type C4AuditElement,
51
+ type C4AuditElementState,
52
+ type C4ProcessBoundaryStatus,
53
+ type C4ProcessVerification,
54
+ } from './c4'
55
+ export {
56
+ adoptGraphifyDeclarationRefFixFromVerify,
57
+ adoptGraphifyFileFixFromVerify,
58
+ adoptGraphifySignatureFixFromVerify,
59
+ adoptTreeSitterSpanFixFromVerify,
60
+ installedDependencyPackage,
61
+ isAdoptableEmptyClaimedSignature,
62
+ storeTypeStale,
63
+ storeTypeUndeclared,
64
+ verificationFailureDiagnostic,
65
+ verificationUnavailableFinding,
66
+ type InstalledDependency,
67
+ } from './fixes'
68
+ export { isRepoPurl, purlRepoKey } from './paths'
69
+ export {
70
+ auditFixGroups,
71
+ auditIssueCount,
72
+ auditHasIssues,
73
+ auditHasPartialGaps,
74
+ classifyAuditReport,
75
+ isVerifiedConstructCheck,
76
+ summarizeVerification,
77
+ summarizeLanes,
78
+ type SubsystemModelAuditVerdict,
79
+ } from './report-logic'
80
+ export { callsSiteOutsideFrom, unconnectedComponentFindings } from './trail'
81
+ export type {
82
+ AuditAnchorCandidate,
83
+ AuditAnchorCheck,
84
+ AuditComponentVerification,
85
+ AuditConstructCheck,
86
+ AuditDeclarationCheck,
87
+ AuditFileCheck,
88
+ AuditFileSuggestion,
89
+ AuditSignatureCheck,
90
+ AuditSignatureTypes,
91
+ } from './verification'
@@ -0,0 +1,145 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import {
3
+ auditFixGroups,
4
+ auditIssueCount,
5
+ classifyAuditReport,
6
+ summarizeLanes,
7
+ summarizeVerification,
8
+ } from './report-logic'
9
+ import type {
10
+ SubsystemModelAuditCheck,
11
+ SubsystemModelAuditReport,
12
+ } from './report'
13
+
14
+ function check(overrides: Partial<SubsystemModelAuditCheck> = {}): SubsystemModelAuditCheck {
15
+ return {
16
+ componentAlias: 'component',
17
+ fileExists: true,
18
+ symbolDeclared: true,
19
+ graphify: 'confirmed',
20
+ verdict: 'ok',
21
+ constructMatch: true,
22
+ signature: 'match',
23
+ declarationFreshness: 'full',
24
+ ...overrides,
25
+ }
26
+ }
27
+
28
+ function report(
29
+ overrides: Partial<SubsystemModelAuditReport> = {},
30
+ ): SubsystemModelAuditReport {
31
+ return {
32
+ graphId: 'model',
33
+ title: 'model',
34
+ checkedAt: '2026-01-01T00:00:00.000Z',
35
+ needsUpdate: false,
36
+ summary: {
37
+ components: 0,
38
+ filesVerified: 0,
39
+ symbolsVerified: 0,
40
+ declarationsFresh: 0,
41
+ constructsMatched: 0,
42
+ signaturesMatched: 0,
43
+ anchorsExact: 0,
44
+ graphifyConfirmed: 0,
45
+ externalsSkipped: 0,
46
+ missingFiles: 0,
47
+ missingSymbols: 0,
48
+ trailFailures: 0,
49
+ stepsUnconfirmed: 0,
50
+ stepsStale: 0,
51
+ stepsVerified: 0,
52
+ staleDeclarations: 0,
53
+ constructMismatches: 0,
54
+ signatureMismatches: 0,
55
+ weakAnchors: 0,
56
+ unresolved: 0,
57
+ ok: 0,
58
+ modulesClaimed: 0,
59
+ moduleFileOk: 0,
60
+ moduleFileMismatch: 0,
61
+ processNestsChecked: 0,
62
+ processNestOk: 0,
63
+ processNestDisagree: 0,
64
+ processRequired: 0,
65
+ processClaimed: 0,
66
+ processMissing: 0,
67
+ },
68
+ checks: [],
69
+ findings: [],
70
+ ...overrides,
71
+ }
72
+ }
73
+
74
+ describe('audit report logic', () => {
75
+ test('classifies issues before gaps and counts error findings', () => {
76
+ expect(classifyAuditReport(report())).toBe('fully_verified')
77
+ expect(
78
+ classifyAuditReport(
79
+ report({
80
+ findings: [{ kind: 'repo_unresolved', severity: 'info', message: 'missing repo' }],
81
+ }),
82
+ ),
83
+ ).toBe('partially_verified')
84
+ const issue = report({
85
+ needsUpdate: true,
86
+ findings: [{ kind: 'missing_file', severity: 'error', message: 'missing file' }],
87
+ })
88
+ expect(classifyAuditReport(issue)).toBe('issues')
89
+ expect(auditIssueCount(issue)).toBe(1)
90
+ })
91
+
92
+ test('derives claim and lane coverage from checks and findings', () => {
93
+ const value = report({
94
+ summary: { ...report().summary, components: 1, stepsVerified: 1 },
95
+ checks: [check()],
96
+ boundaryChecks: [
97
+ {
98
+ componentAlias: 'component',
99
+ kind: 'module_file',
100
+ verdict: 'gap',
101
+ },
102
+ ],
103
+ })
104
+ const verification = summarizeVerification(value)
105
+ expect(verification.verified).toBe(1)
106
+ expect(verification.open).toBe(1)
107
+ expect(verification.byLayer.boundary.open).toBe(1)
108
+ expect(summarizeLanes(value, { hasTrails: true })).toEqual({
109
+ construct: 'verified',
110
+ 'static-topology': 'partial',
111
+ 'dynamic-topology': 'none',
112
+ trail: 'verified',
113
+ })
114
+ })
115
+
116
+ test('groups deterministic fixes by kind', () => {
117
+ const value = report({
118
+ findings: [
119
+ {
120
+ kind: 'construct_span_capturable',
121
+ severity: 'info',
122
+ message: 'capture span',
123
+ fix: {
124
+ id: 'adopt_tree_sitter_span',
125
+ label: 'Capture span',
126
+ declarationSpan: { startLine: 1, endLine: 2, contentHash: 'hash' },
127
+ },
128
+ },
129
+ {
130
+ kind: 'construct_span_capturable',
131
+ severity: 'info',
132
+ message: 'capture another span',
133
+ fix: {
134
+ id: 'adopt_tree_sitter_span',
135
+ label: 'Capture span',
136
+ declarationSpan: { startLine: 3, endLine: 4, contentHash: 'hash' },
137
+ },
138
+ },
139
+ ],
140
+ })
141
+ expect(auditFixGroups(value)).toEqual([
142
+ { fixId: 'adopt_tree_sitter_span', count: 2 },
143
+ ])
144
+ })
145
+ })