weavatrix 0.2.13 → 0.2.15

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 (145) hide show
  1. package/README.md +99 -39
  2. package/SECURITY.md +2 -2
  3. package/docs/releases/v0.2.15.md +37 -0
  4. package/package.json +2 -2
  5. package/skill/SKILL.md +57 -38
  6. package/src/analysis/architecture/contract-graph.js +119 -0
  7. package/src/analysis/architecture/contract-schema.js +110 -0
  8. package/src/analysis/architecture/contract-storage.js +35 -0
  9. package/src/analysis/architecture/contract-verification.js +168 -0
  10. package/src/analysis/architecture-contract.js +16 -343
  11. package/src/analysis/change-classification/diff-parser.js +103 -0
  12. package/src/analysis/change-classification/options.js +40 -0
  13. package/src/analysis/change-classification/symbol-classifier.js +177 -0
  14. package/src/analysis/change-classification.js +120 -519
  15. package/src/analysis/dead-code-review/policy.js +23 -0
  16. package/src/analysis/dead-code-review.js +9 -19
  17. package/src/analysis/dep-check.js +14 -71
  18. package/src/analysis/dep-rules.js +10 -303
  19. package/src/analysis/dependency/conventions.js +16 -0
  20. package/src/analysis/dependency/scoped-dependencies.js +45 -0
  21. package/src/analysis/dependency/source-references.js +21 -0
  22. package/src/analysis/duplicates.tokenize.js +12 -2
  23. package/src/analysis/endpoints/common.js +62 -0
  24. package/src/analysis/endpoints/extract.js +107 -0
  25. package/src/analysis/endpoints/inventory.js +84 -0
  26. package/src/analysis/endpoints/mounts.js +129 -0
  27. package/src/analysis/endpoints-java.js +80 -3
  28. package/src/analysis/endpoints.js +3 -448
  29. package/src/analysis/git-history/analytics.js +177 -0
  30. package/src/analysis/git-history/collector.js +109 -0
  31. package/src/analysis/git-history/options.js +68 -0
  32. package/src/analysis/git-history.js +128 -577
  33. package/src/analysis/health-capabilities.js +82 -0
  34. package/src/analysis/http-contracts/analysis.js +169 -0
  35. package/src/analysis/http-contracts/client-call-detection.js +81 -0
  36. package/src/analysis/http-contracts/client-call-parser.js +255 -0
  37. package/src/analysis/http-contracts/graph-context.js +143 -0
  38. package/src/analysis/http-contracts/matching.js +61 -0
  39. package/src/analysis/http-contracts/shared.js +86 -0
  40. package/src/analysis/http-contracts.js +6 -822
  41. package/src/analysis/internal-audit/dependency-health.js +111 -0
  42. package/src/analysis/internal-audit/python-manifests.js +65 -0
  43. package/src/analysis/internal-audit/repo-files.js +55 -0
  44. package/src/analysis/internal-audit/supply-chain.js +132 -0
  45. package/src/analysis/internal-audit.collect.js +5 -106
  46. package/src/analysis/internal-audit.reach.js +20 -0
  47. package/src/analysis/internal-audit.run.js +114 -200
  48. package/src/analysis/jvm-dependency-evidence.js +69 -0
  49. package/src/analysis/source-correctness/retry-patterns.js +93 -0
  50. package/src/analysis/source-correctness.js +225 -0
  51. package/src/analysis/structure/dependency-graph.js +156 -0
  52. package/src/analysis/structure/findings.js +142 -0
  53. package/src/analysis/task-retrieval.js +3 -14
  54. package/src/graph/builder/go-receiver-resolution.js +112 -0
  55. package/src/graph/builder/js/queries.js +48 -0
  56. package/src/graph/builder/lang-go.js +89 -4
  57. package/src/graph/builder/lang-js.js +4 -44
  58. package/src/graph/builder/pass2-resolution.js +68 -0
  59. package/src/graph/freshness-probe.js +2 -1
  60. package/src/graph/incremental-refresh.js +3 -2
  61. package/src/graph/internal-builder.build.js +22 -183
  62. package/src/graph/internal-builder.pass2.js +161 -0
  63. package/src/graph/internal-builder.resolvers.js +2 -105
  64. package/src/graph/resolvers/rust.js +117 -0
  65. package/src/mcp/actions/advisories.mjs +18 -0
  66. package/src/mcp/actions/graph-lifecycle.mjs +148 -0
  67. package/src/mcp/actions/graph-sync.mjs +195 -0
  68. package/src/mcp/actions/hosted-architecture.mjs +57 -0
  69. package/src/mcp/architecture-bootstrap.mjs +168 -0
  70. package/src/mcp/architecture-starter.mjs +234 -0
  71. package/src/mcp/catalog.mjs +20 -6
  72. package/src/mcp/evidence/bun-lock-graph.mjs +209 -0
  73. package/src/mcp/evidence/duplicate-member-order.mjs +8 -0
  74. package/src/mcp/evidence/package-graph-common.mjs +115 -0
  75. package/src/mcp/evidence/package-lock-graph.mjs +92 -0
  76. package/src/mcp/evidence-snapshot.duplicates.mjs +3 -7
  77. package/src/mcp/evidence-snapshot.package-graph.mjs +5 -474
  78. package/src/mcp/git-output.mjs +10 -0
  79. package/src/mcp/graph/context-core.mjs +111 -0
  80. package/src/mcp/graph/context-seeds.mjs +197 -0
  81. package/src/mcp/graph/context-state.mjs +86 -0
  82. package/src/mcp/graph/reverse-reach.mjs +42 -0
  83. package/src/mcp/graph/tools-core.mjs +143 -0
  84. package/src/mcp/graph/tools-query.mjs +223 -0
  85. package/src/mcp/graph-context.mjs +4 -496
  86. package/src/mcp/health/audit-format.mjs +172 -0
  87. package/src/mcp/health/audit.mjs +171 -0
  88. package/src/mcp/health/dead-code.mjs +110 -0
  89. package/src/mcp/health/duplicates.mjs +83 -0
  90. package/src/mcp/health/endpoints.mjs +42 -0
  91. package/src/mcp/health/structure.mjs +219 -0
  92. package/src/mcp/runtime-version.mjs +32 -0
  93. package/src/mcp/server/auto-refresh.mjs +66 -0
  94. package/src/mcp/server/runtime-config.mjs +43 -0
  95. package/src/mcp/server/shutdown.mjs +40 -0
  96. package/src/mcp/sync/evidence-architecture.mjs +54 -0
  97. package/src/mcp/sync/evidence-common.mjs +88 -0
  98. package/src/mcp/sync/evidence-duplicates.mjs +97 -0
  99. package/src/mcp/sync/evidence-health.mjs +56 -0
  100. package/src/mcp/sync/evidence-packages.mjs +95 -0
  101. package/src/mcp/sync/payload-common.mjs +97 -0
  102. package/src/mcp/sync/payload-v2.mjs +53 -0
  103. package/src/mcp/sync/payload-v3.mjs +79 -0
  104. package/src/mcp/sync-evidence.mjs +7 -402
  105. package/src/mcp/sync-payload.mjs +10 -244
  106. package/src/mcp/tools-actions.mjs +18 -414
  107. package/src/mcp/tools-architecture.mjs +18 -70
  108. package/src/mcp/tools-context.mjs +56 -15
  109. package/src/mcp/tools-endpoints.mjs +4 -1
  110. package/src/mcp/tools-graph.mjs +17 -331
  111. package/src/mcp/tools-health.mjs +24 -705
  112. package/src/mcp/tools-impact-change.mjs +2 -38
  113. package/src/mcp/tools-impact.mjs +2 -43
  114. package/src/mcp-server.mjs +35 -146
  115. package/src/path-classification.js +14 -0
  116. package/src/precision/lsp-client/constants.js +12 -0
  117. package/src/precision/lsp-client/environment.js +20 -0
  118. package/src/precision/lsp-client/errors.js +15 -0
  119. package/src/precision/lsp-client/lifecycle.js +127 -0
  120. package/src/precision/lsp-client/message-parser.js +81 -0
  121. package/src/precision/lsp-client/protocol.js +212 -0
  122. package/src/precision/lsp-client/registry.js +58 -0
  123. package/src/precision/lsp-client/repo-uri.js +60 -0
  124. package/src/precision/lsp-client/stdio-client.js +151 -0
  125. package/src/precision/lsp-client.js +10 -682
  126. package/src/precision/lsp-overlay/build.js +238 -0
  127. package/src/precision/lsp-overlay/contract.js +61 -0
  128. package/src/precision/lsp-overlay/reference-results.js +108 -0
  129. package/src/precision/lsp-overlay/semantic-inputs.js +62 -0
  130. package/src/precision/lsp-overlay/source-session.js +134 -0
  131. package/src/precision/lsp-overlay/store.js +150 -0
  132. package/src/precision/lsp-overlay/target-index.js +147 -0
  133. package/src/precision/lsp-overlay/target-query.js +55 -0
  134. package/src/precision/lsp-overlay.js +11 -868
  135. package/src/precision/typescript-lsp-provider.js +12 -682
  136. package/src/precision/typescript-provider/client.js +69 -0
  137. package/src/precision/typescript-provider/discovery.js +124 -0
  138. package/src/precision/typescript-provider/project-host.js +249 -0
  139. package/src/precision/typescript-provider/project-safety.js +161 -0
  140. package/src/precision/typescript-provider/reference-usage.js +53 -0
  141. package/src/security/malware-heuristics.sweep.js +1 -1
  142. package/src/security/registry-sig.classify.js +2 -1
  143. package/src/security/registry-sig.rules.js +3 -3
  144. package/src/version.js +7 -0
  145. package/docs/releases/v0.2.13.md +0 -48
@@ -0,0 +1,18 @@
1
+ import {refreshAdvisories, storeMeta, DEFAULT_STORE} from '../../security/advisory-store.js'
2
+ import {collectInstalled} from '../../security/installed.js'
3
+
4
+ export async function tRefreshAdvisories(g, args, ctx) {
5
+ if (!ctx.repoRoot) return 'No repo root — cannot collect installed packages.'
6
+ const {installed} = collectInstalled(ctx.repoRoot)
7
+ if (!installed.length) return 'No pinned packages found in lockfiles (npm/yarn/pip/poetry/uv/go) — nothing to query.'
8
+ const res = await refreshAdvisories({installed, repoKey: ctx.repoRoot, timeoutMs: Number(args.timeout_ms) || undefined})
9
+ if (res.ok === false) return `Advisory refresh failed: ${res.error}`
10
+ const meta = storeMeta()
11
+ return [
12
+ `Advisory store ${res.status === 'PARTIAL' ? 'partially refreshed' : 'refreshed'} from OSV.dev: ${res.queriedOk ?? res.queried}/${res.queried} package versions queried successfully, ${res.vulnerable} with known advisories (${res.fetched} advisory records fetched).`,
13
+ res.unsupported ? `${res.unsupported} packages skipped (ecosystem not OSV-queryable — npm/PyPI/Go only).` : null,
14
+ res.errors?.length ? `Partial: ${res.errors.length} request error(s), first: ${res.errors[0]}` : null,
15
+ `Store: ${DEFAULT_STORE} (${meta.advisoryCount} advisories, fetched ${meta.fetchedAt}). run_audit now reflects it — offline.`,
16
+ ].filter(Boolean).join('\n')
17
+ }
18
+
@@ -0,0 +1,148 @@
1
+ import {existsSync, readFileSync, realpathSync, statSync, writeFileSync} from 'node:fs'
2
+ import {dirname, isAbsolute, join} from 'node:path'
3
+ import {diffGraphs, formatGraphDiff, prevGraphPathFor} from '../graph-context.mjs'
4
+ import {buildGraphForRepo, defaultPrecisionMode} from '../../build-graph.js'
5
+ import {graphHomeDir, graphOutDirForModule, graphOutDirForRepo} from '../../graph/layout.js'
6
+ import {liveRepositoryRecords, registerRepository} from '../../graph/repo-registry.js'
7
+ import {precisionSemanticInputsMatch, readPrecisionOverlay} from '../../precision/lsp-overlay.js'
8
+
9
+ export async function tRebuildGraph(g, args, ctx) {
10
+ if (!ctx.repoRoot) return 'Rebuild needs the repo root (not provided to this server).'
11
+ const mode = ['no-tests', 'tests-only', 'full'].includes(args.mode)
12
+ ? args.mode
13
+ : ['no-tests', 'tests-only', 'full'].includes(g?.graphBuildMode) ? g.graphBuildMode : 'full'
14
+ const precision = args.precision === 'off' ? 'off' : args.precision === 'lsp' ? 'lsp' : (g?.graphPrecisionMode || defaultPrecisionMode())
15
+ const scope = String(args.scope || '').replace(/\\/g, '/').replace(/^\/+|\/+$/g, '')
16
+ if (scope) {
17
+ const scopedDir = graphOutDirForModule(ctx.repoRoot, scope)
18
+ const scoped = await buildGraphForRepo(ctx.repoRoot, {mode, scope, precision, outDir: scopedDir})
19
+ if (!scoped || !scoped.ok) return `Scoped graph build failed: ${(scoped && scoped.error) || 'unknown error'}`
20
+ return [
21
+ `Built an isolated scoped graph for ${scope} (${mode}). ${scoped.log || ''}.`,
22
+ `The active full-repository graph was not replaced, so this operation cannot report a false full→scope structural delta.`,
23
+ `Scoped graph: ${join(scopedDir, 'graph.json')}`,
24
+ ].join('\n')
25
+ }
26
+ // snapshot the outgoing state: bytes → graph.prev.json (for graph_diff later), struct → inline delta
27
+ let prevBytes = null
28
+ try { prevBytes = readFileSync(ctx.graphPath) } catch { /* first build — nothing to diff against */ }
29
+ let before = null
30
+ try { before = prevBytes ? JSON.parse(prevBytes.toString('utf8')) : null } catch { before = null }
31
+ const res = await buildGraphForRepo(ctx.repoRoot, {mode, scope: '', precision, outDir: ctx.graphPath ? dirname(ctx.graphPath) : undefined})
32
+ if (!res || !res.ok) return `Graph rebuild failed: ${(res && res.error) || 'unknown error'}`
33
+ if (prevBytes) { try { writeFileSync(prevGraphPathFor(ctx.graphPath), prevBytes) } catch { /* snapshot is best-effort */ } }
34
+ const fresh = ctx.reload() // refresh THIS server's in-memory graph so subsequent tool calls see the new graph
35
+ let afterStatic = null
36
+ try { afterStatic = JSON.parse(readFileSync(ctx.graphPath, 'utf8')) } catch { /* reload already reports the failure */ }
37
+ const beforeMode = ['full', 'no-tests', 'tests-only'].includes(before?.graphBuildMode) ? before.graphBuildMode : 'full'
38
+ const afterMode = ['full', 'no-tests', 'tests-only'].includes(afterStatic?.graphBuildMode) ? afterStatic.graphBuildMode : 'full'
39
+ const delta = before && afterStatic
40
+ ? beforeMode === afterMode
41
+ ? formatGraphDiff(diffGraphs(before, afterStatic))
42
+ : `Structural delta not computed: build mode changed from ${beforeMode} to ${afterMode}, so the node/edge universes are not comparable.`
43
+ : null
44
+ return [
45
+ `Rebuilt the graph (${mode}). ${res.log || ''}. In-memory graph reloaded — graph tools now reflect it.`,
46
+ delta
47
+ ].filter(Boolean).join('\n\n')
48
+ }
49
+
50
+ // Retarget this server at ANOTHER local repository at runtime — one weavatrix registration serves any
51
+ // repo. Loads <parent>/weavatrix-graphs/<name>/graph.json (the central layout graphs
52
+ // always live in), building it first when missing. On a failed load the previous repo stays active.
53
+ export async function tOpenRepo(g, args, ctx) {
54
+
55
+ const requestedPath = String(args.path || '').trim()
56
+ if (!requestedPath) return 'Provide "path" — an absolute path to a local repository folder.'
57
+ if (!isAbsolute(requestedPath)) return 'open_repo requires an absolute repository path.'
58
+ let repoPath
59
+ try { repoPath = realpathSync.native(requestedPath) } catch { return `Path not found: ${requestedPath}` }
60
+ try { if (!statSync(repoPath).isDirectory()) return `Not a directory: ${requestedPath}` } catch { return `Path not found: ${requestedPath}` }
61
+ if (!existsSync(join(repoPath, '.git'))) return `Not a Git repository: ${requestedPath}`
62
+ const graphPath = join(graphOutDirForRepo(repoPath), 'graph.json')
63
+ const graphExists = existsSync(graphPath)
64
+ const requestedMode = ['no-tests', 'tests-only', 'full'].includes(args.mode) ? args.mode : null
65
+ const requestedPrecision = ['lsp', 'off'].includes(args.precision) ? args.precision : null
66
+ let built = false
67
+ let upgrade = false
68
+ let schemaUpgrade = false
69
+ let precisionUpgrade = false
70
+ let savedMode = 'full'
71
+ let savedPrecision = defaultPrecisionMode()
72
+ if (graphExists) {
73
+ try {
74
+ const saved = JSON.parse(readFileSync(graphPath, 'utf8'))
75
+ savedMode = ['no-tests', 'tests-only', 'full'].includes(saved.graphBuildMode) ? saved.graphBuildMode : 'full'
76
+ savedPrecision = ['lsp', 'off'].includes(saved.graphPrecisionMode) ? saved.graphPrecisionMode : defaultPrecisionMode()
77
+ schemaUpgrade = !Number.isInteger(saved.edgeTypesV) || saved.edgeTypesV < 2
78
+ || !Number.isInteger(saved.edgeProvenanceV) || saved.edgeProvenanceV < 1
79
+ || !Number.isInteger(saved.extractorSchemaV) || saved.extractorSchemaV < 5
80
+ || !Number.isInteger(saved.reExportOccurrencesV) || saved.reExportOccurrencesV < 1
81
+ || !Number.isInteger(saved.symbolSpacesV) || saved.symbolSpacesV < 1
82
+ || !Number.isInteger(saved.physicalFileLocV) || saved.physicalFileLocV < 1
83
+ if (savedPrecision === 'lsp') {
84
+ const overlay = readPrecisionOverlay(graphPath, saved)
85
+ precisionUpgrade = !overlay || (typeof overlay.semanticInputFingerprint === 'string'
86
+ && !precisionSemanticInputsMatch(overlay, repoPath, saved))
87
+ }
88
+ upgrade = schemaUpgrade || precisionUpgrade
89
+ } catch {
90
+ upgrade = true
91
+ }
92
+ }
93
+ const modeMismatch = graphExists && requestedMode != null && requestedMode !== savedMode
94
+ const precisionMismatch = graphExists && requestedPrecision != null && requestedPrecision !== savedPrecision
95
+ if (!graphExists || upgrade || modeMismatch || precisionMismatch) {
96
+ if (args.build === false) {
97
+ if (modeMismatch && !upgrade) {
98
+ return `The existing graph for ${repoPath} was built in ${savedMode}, but ${requestedMode} was requested. Re-call without build:false to rebuild it before switching.`
99
+ }
100
+ if (precisionMismatch && !upgrade) {
101
+ return `The existing graph for ${repoPath} uses semantic precision ${savedPrecision}, but ${requestedPrecision} was requested. Re-call without build:false to rebuild it before switching.`
102
+ }
103
+ return upgrade
104
+ ? precisionUpgrade && !schemaUpgrade
105
+ ? `The existing graph for ${repoPath} lacks current revision-matched semantic precision evidence. Re-call without build:false to refresh it before switching.`
106
+ : `The existing graph for ${repoPath} predates current graph metadata (typed edges, provenance, or physical file LOC). Re-call without build:false to upgrade it before switching.`
107
+ : `No graph yet for ${repoPath} (expected at ${graphPath}). Re-call without build:false to build one — large repos can take minutes.`
108
+ }
109
+ const mode = requestedMode || (graphExists ? savedMode : 'full')
110
+ const precision = requestedPrecision || (graphExists ? savedPrecision : defaultPrecisionMode())
111
+ const res = await buildGraphForRepo(repoPath, {mode, scope: '', precision})
112
+ if (!res || !res.ok) return `Graph build failed for ${repoPath}: ${(res && res.error) || 'unknown error'}`
113
+ built = true
114
+ }
115
+ const prev = {graphPath: ctx.graphPath, repoRoot: ctx.repoRoot}
116
+ ctx.graphPath = graphPath
117
+ ctx.repoRoot = repoPath
118
+ const loaded = ctx.reload()
119
+ if (!loaded) {
120
+ ctx.graphPath = prev.graphPath
121
+ ctx.repoRoot = prev.repoRoot
122
+ ctx.reload()
123
+ return `Failed to load ${graphPath} — still targeting the previous repo (${prev.repoRoot || 'none'}).`
124
+ }
125
+ registerRepository({repoPath, graphDir: graphOutDirForRepo(repoPath), graphHome: graphHomeDir()})
126
+ const buildNote = built ? (upgrade ? ' (graph upgraded to current edge/precision metadata)' : modeMismatch ? ' (graph rebuilt in the requested mode)' : precisionMismatch ? ' (semantic precision mode updated)' : ' (graph built fresh)') : ''
127
+ return [
128
+ `Opened ${repoPath}${buildNote}: ${loaded.nodes.length} nodes / ${loaded.links.length} edges. All tools now target this repo.`,
129
+ `Graph: ${graphPath}`,
130
+ `Build mode: ${loaded.graphBuildMode || 'full'}`,
131
+ `Semantic precision: ${loaded.precision?.state || 'UNAVAILABLE'} (${loaded.precision?.verifiedEdges || 0} EXACT_LSP edge(s))`,
132
+ ].join('\n')
133
+ }
134
+
135
+ // Sibling repos that already have a built graph in the central weavatrix-graphs folder — open_repo candidates.
136
+ export function tListKnownRepos(g, args, ctx) {
137
+ const root = graphHomeDir()
138
+ const norm = (p) => String(p).replace(/[\\/]+/g, '/').toLowerCase()
139
+ const rows = liveRepositoryRecords(root).map((record) => ({
140
+ ...record,
141
+ builtAt: statSync(join(record.graphDir, 'graph.json')).mtime.toISOString(),
142
+ }))
143
+ if (!rows.length) return `No registered graphs under ${root}. Build a repository once with open_repo or rebuild_graph.`
144
+ return [
145
+ `Known repositories (${rows.length}) in ${root}:`,
146
+ ...rows.map((r) => ` ${norm(r.repoPath) === norm(ctx.repoRoot) ? '»' : ' '} ${r.label} [${r.repositoryId}] — graph built ${r.builtAt} (${r.repoPath})`),
147
+ ].join('\n')
148
+ }
@@ -0,0 +1,195 @@
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
+
@@ -0,0 +1,57 @@
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
+ }
@@ -0,0 +1,168 @@
1
+ // Explicit two-step local architecture bootstrap. Preview is pure; approval writes only the exact
2
+ // previewed contract with a short-lived one-time token and never overwrites an active policy.
3
+ import {createHash, randomBytes} from 'node:crypto'
4
+ import {existsSync, mkdirSync, writeFileSync} from 'node:fs'
5
+ import {join} from 'node:path'
6
+ import {
7
+ loadArchitectureContract, normalizeArchitectureContract, verifyArchitecture,
8
+ } from '../analysis/architecture-contract.js'
9
+ import {createRepoBoundary} from '../repo-path.js'
10
+ import {detectRepoStack} from '../scan/discover.js'
11
+ import {toolResult} from './tool-result.mjs'
12
+
13
+ const version = new URL(import.meta.url).search
14
+ const starter = await import(new URL(`./architecture-starter.mjs${version}`, import.meta.url).href)
15
+ const {createArchitectureStarter, proposeObservedDependencyDirections} = starter
16
+
17
+ const PREVIEW_TTL_MS = 5 * 60_000
18
+ const previews = new Map()
19
+
20
+ const stackIds = (repoRoot) => {
21
+ try {
22
+ const stack = detectRepoStack(repoRoot)
23
+ return ['languages', 'runtimes', 'tests', 'infra', 'deploy']
24
+ .flatMap((category) => Array.isArray(stack?.[category]) ? stack[category] : [])
25
+ .map((item) => String(item?.id || '')).filter(Boolean)
26
+ } catch { return [] }
27
+ }
28
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex')
29
+
30
+ function currentFingerprints(verification) {
31
+ return [...verification.new, ...verification.existing]
32
+ .map((item) => item.fingerprint).sort((a, b) => a.localeCompare(b))
33
+ }
34
+
35
+ function baselineMetrics(verification) {
36
+ return Object.fromEntries(['runtimeCycles', 'violations', 'componentDependencies', 'mappedComponents']
37
+ .map((key) => [key, verification.metrics?.[key]])
38
+ .filter(([, value]) => Number.isFinite(value)))
39
+ }
40
+
41
+ function materializeCandidate(candidate, verification, baselineMode) {
42
+ if (baselineMode !== 'accept-current') return normalizeArchitectureContract(candidate)
43
+ return normalizeArchitectureContract({
44
+ ...candidate,
45
+ ratchet: {baseline: {
46
+ fingerprints: currentFingerprints(verification),
47
+ metrics: baselineMetrics(verification),
48
+ }},
49
+ })
50
+ }
51
+
52
+ function activeContract(ctx) {
53
+ if (!ctx?.repoRoot) return {contract: null, source: null, error: 'no repository root is active'}
54
+ return loadArchitectureContract(ctx.repoRoot, ctx.graphPath)
55
+ }
56
+
57
+ function preview(g, args, ctx) {
58
+ const active = activeContract(ctx)
59
+ if (active.contract) return toolResult(
60
+ `Architecture bootstrap refused: an active contract already exists at ${active.source}.`,
61
+ {state: 'ALREADY_CONFIGURED', source: active.source, contractHash: active.contract.contractHash},
62
+ )
63
+ if (active.error) return toolResult(
64
+ `Architecture bootstrap refused: ${active.source || 'contract'} is invalid (${active.error}).`,
65
+ {state: 'ERROR', source: active.source, error: active.error},
66
+ )
67
+ const baselineMode = args?.baseline_mode === 'accept-current' ? 'accept-current' : 'none'
68
+ let candidate, starterProposal = null
69
+ try {
70
+ starterProposal = args?.candidate_contract ? null : createArchitectureStarter(g, ctx?.repoRoot)
71
+ candidate = args?.candidate_contract
72
+ ? normalizeArchitectureContract(args.candidate_contract)
73
+ : starterProposal.contract
74
+ } catch (error) {
75
+ return toolResult(`Candidate architecture contract is invalid: ${error.message}`, {state: 'INVALID', error: error.message})
76
+ }
77
+ const technologies = stackIds(ctx?.repoRoot)
78
+ const candidateVerification = verifyArchitecture({graph: g, contract: candidate, technologies})
79
+ const materializedContract = materializeCandidate(candidate, candidateVerification, baselineMode)
80
+ const materializedVerification = verifyArchitecture({graph: g, contract: materializedContract, technologies})
81
+ const contents = `${JSON.stringify(materializedContract, null, 2)}\n`
82
+ const contentHash = sha256(contents)
83
+ const token = randomBytes(12).toString('hex')
84
+ const expiresAt = new Date(Date.now() + PREVIEW_TTL_MS).toISOString()
85
+ previews.set(token, {
86
+ repoRoot: String(ctx?.repoRoot || ''), graphPath: String(ctx?.graphPath || ''),
87
+ contract: materializedContract, contents, contentHash,
88
+ verificationHash: materializedVerification.verificationHash,
89
+ expiresAt: Date.parse(expiresAt),
90
+ })
91
+ return toolResult([
92
+ `Architecture bootstrap PREVIEW only; no file was written. Candidate verification: ${candidateVerification.status}.`,
93
+ baselineMode === 'accept-current'
94
+ ? `Explicit accept-current baseline would record ${currentFingerprints(candidateVerification).length} current finding fingerprint(s).`
95
+ : 'No current findings were added to the baseline.',
96
+ `Review the materialized contract and then approve with confirm_token "${token}" before ${expiresAt}.`,
97
+ ].join('\n'), {
98
+ state: 'PREVIEW', wrote: false, baselineMode,
99
+ candidateVerification, materializedVerification, materializedContract,
100
+ observedDependencyProposals: proposeObservedDependencyDirections(g, materializedContract.components),
101
+ budgetProposals: starterProposal?.budgetProposals || [],
102
+ starterMethodology: starterProposal?.methodology,
103
+ patch: {operation: 'create', path: '.weavatrix/architecture.json', contentHash, contents},
104
+ confirmToken: token, expiresAt,
105
+ })
106
+ }
107
+
108
+ function approve(g, args, ctx) {
109
+ const token = String(args?.confirm_token || '')
110
+ const pending = previews.get(token)
111
+ if (!pending) return toolResult(
112
+ 'Architecture approval refused: run a fresh preview and provide its exact confirm_token.',
113
+ {state: 'CONFIRMATION_REQUIRED', wrote: false},
114
+ )
115
+ previews.delete(token)
116
+ if (pending.expiresAt < Date.now()) return toolResult(
117
+ 'Architecture approval refused: the preview expired; run preview again.',
118
+ {state: 'PREVIEW_EXPIRED', wrote: false},
119
+ )
120
+ if (pending.repoRoot !== String(ctx?.repoRoot || '') || pending.graphPath !== String(ctx?.graphPath || '')) {
121
+ return toolResult('Architecture approval refused: the active repository changed after preview.', {
122
+ state: 'REPOSITORY_CHANGED', wrote: false,
123
+ })
124
+ }
125
+ const active = activeContract(ctx)
126
+ if (active.contract || active.error) return toolResult(
127
+ `Architecture approval refused: ${active.source || 'a contract'} appeared or changed after preview.`,
128
+ {state: active.error ? 'ERROR' : 'ALREADY_CONFIGURED', wrote: false, source: active.source, error: active.error || undefined},
129
+ )
130
+ const verification = verifyArchitecture({
131
+ graph: g, contract: pending.contract, technologies: stackIds(ctx?.repoRoot),
132
+ })
133
+ if (verification.verificationHash !== pending.verificationHash) return toolResult(
134
+ 'Architecture approval refused: graph evidence changed after preview; review a fresh preview.',
135
+ {state: 'GRAPH_CHANGED', wrote: false, previewVerificationHash: pending.verificationHash, currentVerificationHash: verification.verificationHash},
136
+ )
137
+ const boundary = createRepoBoundary(ctx?.repoRoot)
138
+ if (!boundary.root) return toolResult('Architecture approval refused: the repository boundary is unavailable.', {
139
+ state: 'PATH_REFUSED', wrote: false,
140
+ })
141
+ try { mkdirSync(join(boundary.root, '.weavatrix'), {recursive: true}) }
142
+ catch (error) { return toolResult(`Architecture approval could not create its policy directory: ${error.message}`, {
143
+ state: 'WRITE_FAILED', wrote: false, error: error.message,
144
+ }) }
145
+ const policyDirectory = boundary.resolve('.weavatrix')
146
+ if (!policyDirectory.ok) return toolResult('Architecture approval refused: the policy directory resolves outside the active repository.', {
147
+ state: 'PATH_REFUSED', wrote: false,
148
+ })
149
+ const targetPath = join(policyDirectory.path, 'architecture.json')
150
+ if (existsSync(targetPath)) return toolResult('Architecture approval refused: the target contract already exists.', {
151
+ state: 'ALREADY_CONFIGURED', wrote: false, source: '.weavatrix/architecture.json',
152
+ })
153
+ try {
154
+ writeFileSync(targetPath, pending.contents, {encoding: 'utf8', flag: 'wx'})
155
+ } catch (error) {
156
+ return toolResult(`Architecture approval failed without overwriting policy: ${error.message}`, {
157
+ state: 'WRITE_FAILED', wrote: false, error: error.message,
158
+ })
159
+ }
160
+ return toolResult(
161
+ `Architecture contract approved and created at .weavatrix/architecture.json (${pending.contentHash.slice(0, 12)}).`,
162
+ {state: 'APPROVED', wrote: true, source: '.weavatrix/architecture.json', contentHash: pending.contentHash, contract: pending.contract, verification},
163
+ )
164
+ }
165
+
166
+ export function tBootstrapArchitecture(g, args = {}, ctx) {
167
+ return args.action === 'approve' ? approve(g, args, ctx) : preview(g, args, ctx)
168
+ }