weavatrix 0.2.18 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +102 -93
  2. package/SECURITY.md +13 -31
  3. package/bin/weavatrix-mcp.mjs +2 -1
  4. package/docs/adr/0001-v0.3-offline-online-split.md +9 -7
  5. package/docs/releases/v0.2.19.md +33 -0
  6. package/docs/releases/v0.3.0.md +43 -0
  7. package/package.json +9 -3
  8. package/skill/SKILL.md +34 -59
  9. package/src/analysis/architecture/contract-storage.js +2 -2
  10. package/src/analysis/audit-extensions.js +60 -0
  11. package/src/analysis/duplicate-groups.js +13 -2
  12. package/src/analysis/duplicates.compute.js +7 -2
  13. package/src/analysis/health-capabilities.js +2 -1
  14. package/src/analysis/internal-audit/supply-chain.js +17 -2
  15. package/src/analysis/jvm-artifact-index.js +87 -0
  16. package/src/analysis/jvm-dependency-evidence.js +31 -8
  17. package/src/analysis/transport-contracts.js +78 -11
  18. package/src/analysis/transport-runtime-evidence.js +155 -0
  19. package/src/child-env.js +2 -2
  20. package/src/extension/local-services.mjs +75 -0
  21. package/src/graph/internal-builder.langs.js +2 -0
  22. package/src/graph/repo-registry.js +2 -2
  23. package/src/mcp/catalog.mjs +47 -21
  24. package/src/mcp/evidence/duplicate-member-order.mjs +1 -1
  25. package/src/mcp/evidence-snapshot.health.mjs +2 -2
  26. package/src/mcp/extension-api.mjs +77 -0
  27. package/src/mcp/health/audit-format.mjs +11 -1
  28. package/src/mcp/health/audit.mjs +10 -7
  29. package/src/mcp/health/duplicates.mjs +5 -3
  30. package/src/mcp/sync-payload.mjs +1 -1
  31. package/src/mcp/tools-actions.mjs +1 -8
  32. package/src/mcp/tools-architecture.mjs +2 -2
  33. package/src/mcp/tools-company.mjs +4 -2
  34. package/src/mcp-runtime.mjs +2 -0
  35. package/src/mcp-server.mjs +28 -17
  36. package/src/security/advisory-store.js +133 -181
  37. package/src/security/malware-scoring.js +4 -0
  38. package/src/security/registry-sig.rules.js +4 -3
  39. package/src/security/rust-advisory-report.js +60 -0
  40. package/docs/releases/v0.2.18.md +0 -41
  41. package/src/mcp/actions/advisories.mjs +0 -17
  42. package/src/mcp/actions/graph-sync.mjs +0 -195
  43. package/src/mcp/actions/hosted-architecture.mjs +0 -57
@@ -1,195 +0,0 @@
1
- import {createHash} from 'node:crypto'
2
- import {readFileSync, statSync} from 'node:fs'
3
- import {graphStaleness} from '../graph-context.mjs'
4
- import {graphHomeDir, graphOutDirForRepo} from '../../graph/layout.js'
5
- import {registerRepository, repositoryRecord} from '../../graph/repo-registry.js'
6
- import {createSyncPayload, createSyncPayloadV3, MAX_SYNC_BODY_BYTES} from '../sync-payload.mjs'
7
- import {createEvidenceSnapshot} from '../evidence-snapshot.mjs'
8
- import {toolResult} from '../tool-result.mjs'
9
-
10
- const MAX_SYNC_GRAPH_FILE_BYTES = 64 * 1024 * 1024
11
- const SYNC_PREVIEW_TTL_MS = 5 * 60 * 1000
12
- const MAX_SYNC_PREVIEWS = 4
13
- const syncPreviews = new Map()
14
-
15
- function syncRepoLabel(repoRoot) {
16
- const basename = String(repoRoot || '').replace(/[\\/]+$/, '').split(/[\\/]/).pop() || 'repo'
17
- const safe = basename.normalize('NFKC').replace(/[^a-z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '')
18
- return (safe || 'repo').slice(0, 128)
19
- }
20
-
21
- export function syncDestination(raw) {
22
- let url
23
- try { url = new URL(raw) } catch { throw new Error('WEAVATRIX_SYNC_URL is invalid') }
24
- if (!['http:', 'https:'].includes(url.protocol)) throw new Error('WEAVATRIX_SYNC_URL must use HTTPS (or HTTP for loopback development)')
25
- if (url.username || url.password) throw new Error('WEAVATRIX_SYNC_URL must not contain embedded credentials; use WEAVATRIX_SYNC_TOKEN')
26
- if (url.hash) throw new Error('WEAVATRIX_SYNC_URL must not contain a fragment')
27
- const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname.toLowerCase())
28
- if (url.protocol !== 'https:' && !loopback) throw new Error('WEAVATRIX_SYNC_URL must use HTTPS unless the destination is loopback')
29
- const display = `${url.origin}${url.pathname}${url.search ? ' (query redacted)' : ''}`
30
- return {url: url.toString(), display}
31
- }
32
-
33
- function pruneSyncPreviews(now = Date.now()) {
34
- for (const [token, preview] of syncPreviews) if (preview.expiresAt <= now) syncPreviews.delete(token)
35
- while (syncPreviews.size >= MAX_SYNC_PREVIEWS) syncPreviews.delete(syncPreviews.keys().next().value)
36
- }
37
-
38
- function confirmationToken({url, repositoryId, payloadVersion, bodyHash}) {
39
- return createHash('sha256')
40
- .update(`weavatrix-sync-preview-v1\0${url}\0${repositoryId}\0${payloadVersion}\0${bodyHash}`)
41
- .digest('hex').slice(0, 24)
42
- }
43
-
44
- function syncSectionSummary(payload) {
45
- if (payload.syncPayloadV !== 3) return 'graph topology only (explicit V2 compatibility mode)'
46
- const sections = payload.evidence?.sections || {}
47
- const names = Object.entries(sections).map(([name, section]) => `${name}:${section?.state || section?.verdict || 'included'}`)
48
- return names.join(', ') || 'bounded architecture/health/stack/package/duplicate evidence'
49
- }
50
-
51
- function syncPreviewText(preview, {expired = false} = {}) {
52
- return [
53
- `SYNC PREVIEW${expired ? ' (the supplied confirmation was missing, expired, or did not match)' : ''} — no network request was made.`,
54
- `Destination: ${preview.destinationDisplay}.`,
55
- `Repository: ${preview.repoName}; opaque repository UUID: ${preview.repositoryId}.`,
56
- `Payload V${preview.payload.syncPayloadV}: ${preview.payload.nodes.length} nodes / ${preview.payload.links.length} edges, ${Math.round(preview.bodyBytes / 1024)} KB; body SHA-256 ${preview.bodyHash.slice(0, 12)}.`,
57
- `Payload fields: ${Object.keys(preview.payload).sort().join(', ')}.`,
58
- `Included sections: ${syncSectionSummary(preview.payload)}.`,
59
- 'Excluded by the wire allowlist: source bodies, snippets, absolute host paths, environment values, credentials, Git remotes, and unknown fields.',
60
- `After the user approves this exact destination and summary, call sync_graph again within 5 minutes with dry_run:false and confirm_token: "${preview.token}".`,
61
- ].join('\n')
62
- }
63
-
64
- async function sendSyncPreview(preview, timeoutMs) {
65
- try {
66
- const res = await fetch(preview.url, {
67
- method: 'POST',
68
- headers: {
69
- 'content-type': 'application/json',
70
- 'x-weavatrix-payload-version': String(preview.payload.syncPayloadV),
71
- 'x-weavatrix-repo': preview.repoName,
72
- 'x-weavatrix-repository-id': preview.repositoryId,
73
- ...(process.env.WEAVATRIX_SYNC_TOKEN ? {authorization: `Bearer ${process.env.WEAVATRIX_SYNC_TOKEN}`} : {}),
74
- },
75
- body: preview.body,
76
- signal: AbortSignal.timeout(timeoutMs),
77
- })
78
- if (!res.ok) {
79
- const accepted = res.headers?.get?.('x-weavatrix-accept-payload-versions')
80
- const compatibility = (res.status === 415 || res.status === 422) && accepted
81
- ? ` Endpoint accepts payload version(s) ${accepted}; create and approve a new V2 preview only if graph-only sync is intentional.`
82
- : ''
83
- return `Sync endpoint ${preview.destinationDisplay} answered HTTP ${res.status} — graph NOT accepted.${compatibility}`
84
- }
85
- syncPreviews.delete(preview.token)
86
- const evidenceNote = preview.payload.syncPayloadV === 3
87
- ? ` + evidence ${preview.payload.evidence?.snapshotHash?.slice(0, 12) || 'unknown'}`
88
- : ''
89
- return `Graph for ${preview.repoName} (${preview.payload.nodes.length} nodes / ${preview.payload.links.length} edges${evidenceNote}, ${Math.round(preview.bodyBytes / 1024)} KB) pushed to approved destination ${preview.destinationDisplay}.`
90
- } catch (error) {
91
- return `Sync failed: ${error.message} — the graph stays local; the approved preview remains retryable until it expires.`
92
- }
93
- }
94
-
95
- async function buildSyncPreview(g, args, ctx) {
96
- const configuredUrl = process.env.WEAVATRIX_SYNC_URL
97
- if (!configuredUrl) {
98
- return 'Graph sync is not configured (optional feature). Set WEAVATRIX_SYNC_URL to the upload endpoint'
99
- + ' (and WEAVATRIX_SYNC_TOKEN for bearer auth) in the MCP registration env, then call again.'
100
- }
101
- let destination
102
- try { destination = syncDestination(configuredUrl) }
103
- catch (error) { return `Graph sync is not configured safely: ${error.message}.` }
104
- if (!g) return 'No graph loaded — build one first (open_repo / rebuild_graph).'
105
- let raw
106
- try {
107
- const size = statSync(ctx.graphPath).size
108
- if (size > MAX_SYNC_GRAPH_FILE_BYTES) {
109
- return `Cannot sync: graph.json is ${Math.ceil(size / 1024 / 1024)} MB; the local safety limit is ${MAX_SYNC_GRAPH_FILE_BYTES / 1024 / 1024} MB.`
110
- }
111
- raw = JSON.parse(readFileSync(ctx.graphPath, 'utf8'))
112
- } catch (e) { return `Cannot read ${ctx.graphPath}: ${e.message}` }
113
- const requestedVersion = Number(args.payload_version) === 2 ? 2 : 3
114
- let payload
115
- try {
116
- if (requestedVersion === 2) {
117
- payload = createSyncPayload(raw)
118
- } else {
119
- if (!ctx.repoRoot) return 'Cannot build evidence: no repository root is active.'
120
- if (graphStaleness(ctx).stale) {
121
- return 'Cannot sync evidence from a stale graph. Run rebuild_graph, then call sync_graph again.'
122
- }
123
- const evidence = await createEvidenceSnapshot({repoRoot: ctx.repoRoot, graph: raw})
124
- payload = createSyncPayloadV3(raw, evidence)
125
- }
126
- } catch (e) {
127
- return `Cannot sync: ${e.message}. Run rebuild_graph once before sync_graph.`
128
- }
129
- const body = JSON.stringify(payload)
130
- const bodyBytes = Buffer.byteLength(body)
131
- if (bodyBytes > MAX_SYNC_BODY_BYTES) {
132
- return `Cannot sync: payload is ${Math.ceil(bodyBytes / 1024)} KB; the hosted safety limit is ${MAX_SYNC_BODY_BYTES / 1024} KB. Narrow the graph scope and rebuild before retrying.`
133
- }
134
- const repoName = syncRepoLabel(ctx.repoRoot)
135
- const registry = repositoryRecord(ctx.repoRoot, graphHomeDir())
136
- || registerRepository({repoPath: ctx.repoRoot, graphDir: graphOutDirForRepo(ctx.repoRoot), graphHome: graphHomeDir()})
137
- const bodyHash = createHash('sha256').update(body).digest('hex')
138
- const token = confirmationToken({url: destination.url, repositoryId: registry.repositoryId, payloadVersion: payload.syncPayloadV, bodyHash})
139
- const preview = {
140
- token, url: destination.url, destinationDisplay: destination.display,
141
- graphPath: ctx.graphPath, repoName, repositoryId: registry.repositoryId,
142
- payload, body, bodyBytes, bodyHash, expiresAt: Date.now() + SYNC_PREVIEW_TTL_MS,
143
- }
144
- syncPreviews.set(token, preview)
145
- return preview
146
- }
147
-
148
- function previewResult(preview, {expired = false} = {}) {
149
- if (typeof preview === 'string') return preview
150
- return toolResult(syncPreviewText(preview, {expired}), {
151
- status: 'PREVIEW_READY', networkRequestMade: false,
152
- destination: preview.destinationDisplay, repository: preview.repoName,
153
- repositoryId: preview.repositoryId, payloadVersion: preview.payload.syncPayloadV,
154
- nodes: preview.payload.nodes.length, links: preview.payload.links.length,
155
- bodyBytes: preview.bodyBytes, bodyHash: preview.bodyHash,
156
- payloadFields: Object.keys(preview.payload).sort(), sections: syncSectionSummary(preview.payload),
157
- expiresAt: new Date(preview.expiresAt).toISOString(), confirmToken: preview.token,
158
- }, {completeness: {status: 'COMPLETE', reason: 'exact allowlisted payload serialized locally; no network request made'}})
159
- }
160
-
161
- // Build the exact upload body and approval token without any network request. Kept separate from the
162
- // mutating tool so safety layers and humans can approve a local preview without authorizing egress.
163
- export async function tPreviewSyncGraph(g, args, ctx) {
164
- pruneSyncPreviews()
165
- return previewResult(await buildSyncPreview(g, args, ctx))
166
- }
167
-
168
- // Push the exact payload previously approved through preview_sync. The old dry_run form remains a
169
- // compatibility alias for one release, but can never send unless dry_run:false and the token matches.
170
- export async function tSyncGraph(g, args, ctx) {
171
- if (args.dry_run !== false) {
172
- pruneSyncPreviews()
173
- const preview = await buildSyncPreview(g, args, ctx)
174
- if (typeof preview === 'string') return preview
175
- const suppliedToken = String(args.confirm_token || '').trim()
176
- const exact = suppliedToken && suppliedToken === preview.token
177
- return `${syncPreviewText(preview, {expired: !!suppliedToken && !exact})}${exact ? '\nConfirmation token recognized, but dry_run is still true; no network request was made.' : ''}`
178
- }
179
- const configuredUrl = process.env.WEAVATRIX_SYNC_URL
180
- if (!configuredUrl) return 'Graph sync is not configured (optional feature). Set WEAVATRIX_SYNC_URL first.'
181
- let destination
182
- try { destination = syncDestination(configuredUrl) }
183
- catch (error) { return `Graph sync is not configured safely: ${error.message}.` }
184
- pruneSyncPreviews()
185
- const suppliedToken = String(args.confirm_token || '').trim()
186
- const approved = suppliedToken ? syncPreviews.get(suppliedToken) : null
187
- if (approved && approved.expiresAt > Date.now()
188
- && approved.url === destination.url && approved.graphPath === ctx.graphPath) {
189
- const timeoutMs = Math.min(120000, Math.max(1000, Number(args.timeout_ms) || 30000))
190
- return sendSyncPreview(approved, timeoutMs)
191
- }
192
- const preview = await buildSyncPreview(g, args, ctx)
193
- return typeof preview === 'string' ? preview : syncPreviewText(preview, {expired: true})
194
- }
195
-
@@ -1,57 +0,0 @@
1
- import {writeCachedArchitectureContract} from '../../analysis/architecture-contract.js'
2
- import {graphHomeDir, graphOutDirForRepo} from '../../graph/layout.js'
3
- import {registerRepository, repositoryRecord} from '../../graph/repo-registry.js'
4
- import {toolResult} from '../tool-result.mjs'
5
- const syncVersion = new URL(import.meta.url).search
6
- const {syncDestination} = await import(new URL(`./graph-sync.mjs${syncVersion}`, import.meta.url).href)
7
-
8
- export async function tPullArchitectureContract(g, args, ctx) {
9
- if (!ctx.repoRoot || !ctx.graphPath) return 'No active repository graph — open_repo first.'
10
- const syncUrl = process.env.WEAVATRIX_SYNC_URL
11
- const token = process.env.WEAVATRIX_SYNC_TOKEN
12
- if (!syncUrl || !token) return 'Hosted architecture pull is not configured. Use the hosted profile with WEAVATRIX_SYNC_URL and WEAVATRIX_SYNC_TOKEN, or keep .weavatrix/architecture.json locally.'
13
- let url
14
- try {
15
- const configured = process.env.WEAVATRIX_ARCHITECTURE_URL || new URL('/api/v1/architecture-contract', syncUrl).toString()
16
- url = syncDestination(configured).url
17
- } catch (error) { return `Hosted architecture pull is not configured safely: ${error.message}.` }
18
- const registry = repositoryRecord(ctx.repoRoot, graphHomeDir())
19
- || registerRepository({repoPath: ctx.repoRoot, graphDir: graphOutDirForRepo(ctx.repoRoot), graphHome: graphHomeDir()})
20
- const timeoutMs = Math.min(120000, Math.max(1000, Number(args.timeout_ms) || 30000))
21
- try {
22
- const res = await fetch(url, {
23
- headers: {authorization: `Bearer ${token}`, 'x-weavatrix-repository-id': registry.repositoryId},
24
- signal: AbortSignal.timeout(timeoutMs),
25
- })
26
- const body = await res.json().catch(() => null)
27
- if (!res.ok) {
28
- const serverCode = String(body?.error?.code || body?.state || '').toUpperCase()
29
- const state = res.status === 401 ? 'AUTH_REQUIRED'
30
- : res.status === 403 ? 'FORBIDDEN'
31
- : res.status === 404 && ['REPOSITORY_NOT_FOUND', 'NOT_FOUND'].includes(serverCode) ? 'REPOSITORY_NOT_REGISTERED'
32
- : res.status === 404 ? 'ENDPOINT_NOT_FOUND'
33
- : res.status === 409 ? 'REPOSITORY_NOT_READY'
34
- : 'HTTP_ERROR'
35
- const next = state === 'REPOSITORY_NOT_REGISTERED'
36
- ? 'The Hosted endpoint is reachable, but this UUID has not completed a preview-confirmed repository sync.'
37
- : state === 'ENDPOINT_NOT_FOUND'
38
- ? 'The configured architecture endpoint does not exist; verify WEAVATRIX_ARCHITECTURE_URL or the URL derived from WEAVATRIX_SYNC_URL.'
39
- : res.status === 401 || res.status === 403
40
- ? 'Check the hosted token and repository access; no local cache entry was changed.'
41
- : res.status === 409
42
- ? 'Sync/register this repository first, then create or pull its target contract.'
43
- : 'Check the hosted service status and configured endpoint before retrying.'
44
- return toolResult(`Hosted architecture pull: ${state} (HTTP ${res.status}). ${next} The previous local contract cache remains unchanged.`, {
45
- state, httpStatus: res.status, serverCode: serverCode || null, cacheChanged: false,
46
- })
47
- }
48
- if (body?.state === 'NOT_CONFIGURED' || !body?.contract) return toolResult(
49
- 'Hosted target architecture is NOT_CONFIGURED. Repository sync and authentication succeeded; define and save a target in the Architecture editor first.',
50
- {state: 'NOT_CONFIGURED', repositoryId: registry.repositoryId, cacheChanged: false},
51
- )
52
- const stored = writeCachedArchitectureContract(ctx.graphPath, body.contract)
53
- return `Pulled target architecture ${stored.contract.name} (${stored.contract.style}, ${stored.contract.enforcement}) into the local graph cache. get_architecture_contract and verify_architecture now use it.`
54
- } catch (error) {
55
- return `Hosted architecture pull failed: ${error.message}; the previous local contract, if any, remains active.`
56
- }
57
- }