weavatrix 0.2.12 → 0.2.14
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.
- package/README.md +90 -21
- package/SECURITY.md +2 -2
- package/docs/releases/v0.2.14.md +93 -0
- package/package.json +2 -2
- package/skill/SKILL.md +108 -43
- package/src/analysis/allowed-test-runner.js +20 -9
- package/src/analysis/architecture/contract-graph.js +119 -0
- package/src/analysis/architecture/contract-schema.js +110 -0
- package/src/analysis/architecture/contract-storage.js +35 -0
- package/src/analysis/architecture/contract-verification.js +168 -0
- package/src/analysis/architecture-contract.js +16 -343
- package/src/analysis/change-classification/diff-parser.js +103 -0
- package/src/analysis/change-classification/options.js +40 -0
- package/src/analysis/change-classification/symbol-classifier.js +177 -0
- package/src/analysis/change-classification.js +120 -519
- package/src/analysis/dead-code-review/policy.js +23 -0
- package/src/analysis/dead-code-review.js +9 -19
- package/src/analysis/dep-check.js +10 -57
- package/src/analysis/dep-rules.js +10 -303
- package/src/analysis/dependency/scoped-dependencies.js +40 -0
- package/src/analysis/endpoints/common.js +62 -0
- package/src/analysis/endpoints/extract.js +107 -0
- package/src/analysis/endpoints/inventory.js +84 -0
- package/src/analysis/endpoints/mounts.js +129 -0
- package/src/analysis/endpoints-java.js +80 -3
- package/src/analysis/endpoints.js +3 -448
- package/src/analysis/git-history/analytics.js +177 -0
- package/src/analysis/git-history/collector.js +109 -0
- package/src/analysis/git-history/options.js +68 -0
- package/src/analysis/git-history.js +128 -577
- package/src/analysis/health-capabilities.js +82 -0
- package/src/analysis/http-contracts/analysis.js +169 -0
- package/src/analysis/http-contracts/client-call-detection.js +81 -0
- package/src/analysis/http-contracts/client-call-parser.js +255 -0
- package/src/analysis/http-contracts/graph-context.js +143 -0
- package/src/analysis/http-contracts/matching.js +61 -0
- package/src/analysis/http-contracts/shared.js +86 -0
- package/src/analysis/http-contracts.js +6 -822
- package/src/analysis/internal-audit/dependency-health.js +111 -0
- package/src/analysis/internal-audit/python-manifests.js +65 -0
- package/src/analysis/internal-audit/repo-files.js +55 -0
- package/src/analysis/internal-audit/supply-chain.js +132 -0
- package/src/analysis/internal-audit.collect.js +5 -106
- package/src/analysis/internal-audit.run.js +113 -200
- package/src/analysis/jvm-dependency-evidence.js +69 -0
- package/src/analysis/source-correctness/retry-patterns.js +93 -0
- package/src/analysis/source-correctness.js +225 -0
- package/src/analysis/structure/dependency-graph.js +156 -0
- package/src/analysis/structure/findings.js +142 -0
- package/src/graph/builder/go-receiver-resolution.js +112 -0
- package/src/graph/builder/js/queries.js +48 -0
- package/src/graph/builder/lang-go.js +89 -4
- package/src/graph/builder/lang-js.js +4 -44
- package/src/graph/builder/pass2-resolution.js +68 -0
- package/src/graph/freshness-probe.js +2 -1
- package/src/graph/incremental-refresh.js +3 -2
- package/src/graph/internal-builder.build.js +22 -183
- package/src/graph/internal-builder.pass2.js +161 -0
- package/src/graph/internal-builder.resolvers.js +2 -105
- package/src/graph/resolvers/rust.js +117 -0
- package/src/mcp/actions/advisories.mjs +18 -0
- package/src/mcp/actions/graph-lifecycle.mjs +148 -0
- package/src/mcp/actions/graph-sync.mjs +195 -0
- package/src/mcp/actions/hosted-architecture.mjs +57 -0
- package/src/mcp/architecture-bootstrap.mjs +168 -0
- package/src/mcp/architecture-starter.mjs +234 -0
- package/src/mcp/catalog.mjs +22 -6
- package/src/mcp/evidence/bun-lock-graph.mjs +209 -0
- package/src/mcp/evidence/package-graph-common.mjs +115 -0
- package/src/mcp/evidence/package-lock-graph.mjs +92 -0
- package/src/mcp/evidence-snapshot.package-graph.mjs +5 -474
- package/src/mcp/graph/context-core.mjs +111 -0
- package/src/mcp/graph/context-seeds.mjs +208 -0
- package/src/mcp/graph/context-state.mjs +86 -0
- package/src/mcp/graph/tools-core.mjs +143 -0
- package/src/mcp/graph/tools-query.mjs +223 -0
- package/src/mcp/graph-context.mjs +4 -496
- package/src/mcp/health/audit-format.mjs +172 -0
- package/src/mcp/health/audit.mjs +171 -0
- package/src/mcp/health/dead-code.mjs +110 -0
- package/src/mcp/health/duplicates.mjs +83 -0
- package/src/mcp/health/endpoints.mjs +42 -0
- package/src/mcp/health/structure.mjs +219 -0
- package/src/mcp/runtime-version.mjs +32 -0
- package/src/mcp/server/auto-refresh.mjs +66 -0
- package/src/mcp/server/runtime-config.mjs +43 -0
- package/src/mcp/server/shutdown.mjs +40 -0
- package/src/mcp/sync/evidence-architecture.mjs +54 -0
- package/src/mcp/sync/evidence-common.mjs +88 -0
- package/src/mcp/sync/evidence-duplicates.mjs +100 -0
- package/src/mcp/sync/evidence-health.mjs +56 -0
- package/src/mcp/sync/evidence-packages.mjs +95 -0
- package/src/mcp/sync/payload-common.mjs +97 -0
- package/src/mcp/sync/payload-v2.mjs +53 -0
- package/src/mcp/sync/payload-v3.mjs +79 -0
- package/src/mcp/sync-evidence.mjs +7 -402
- package/src/mcp/sync-payload.mjs +10 -244
- package/src/mcp/tools-actions.mjs +18 -414
- package/src/mcp/tools-architecture.mjs +18 -70
- package/src/mcp/tools-context.mjs +56 -15
- package/src/mcp/tools-endpoints.mjs +4 -1
- package/src/mcp/tools-graph.mjs +17 -330
- package/src/mcp/tools-health.mjs +24 -705
- package/src/mcp/tools-verified-change.mjs +12 -4
- package/src/mcp-server.mjs +49 -146
- package/src/precision/lsp-client/constants.js +12 -0
- package/src/precision/lsp-client/environment.js +20 -0
- package/src/precision/lsp-client/errors.js +15 -0
- package/src/precision/lsp-client/lifecycle.js +127 -0
- package/src/precision/lsp-client/message-parser.js +81 -0
- package/src/precision/lsp-client/protocol.js +212 -0
- package/src/precision/lsp-client/registry.js +58 -0
- package/src/precision/lsp-client/repo-uri.js +60 -0
- package/src/precision/lsp-client/stdio-client.js +151 -0
- package/src/precision/lsp-client.js +10 -682
- package/src/precision/lsp-overlay/build.js +238 -0
- package/src/precision/lsp-overlay/contract.js +61 -0
- package/src/precision/lsp-overlay/reference-results.js +108 -0
- package/src/precision/lsp-overlay/semantic-inputs.js +62 -0
- package/src/precision/lsp-overlay/source-session.js +134 -0
- package/src/precision/lsp-overlay/store.js +150 -0
- package/src/precision/lsp-overlay/target-index.js +147 -0
- package/src/precision/lsp-overlay/target-query.js +55 -0
- package/src/precision/lsp-overlay.js +11 -868
- package/src/precision/typescript-lsp-provider.js +12 -682
- package/src/precision/typescript-provider/client.js +69 -0
- package/src/precision/typescript-provider/discovery.js +124 -0
- package/src/precision/typescript-provider/project-host.js +249 -0
- package/src/precision/typescript-provider/project-safety.js +161 -0
- package/src/precision/typescript-provider/reference-usage.js +53 -0
- package/src/version.js +7 -0
- package/docs/releases/v0.2.12.md +0 -45
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import {spawnSync} from 'node:child_process'
|
|
2
|
+
import {summarizeFindings} from '../../analysis/findings.js'
|
|
3
|
+
import {childProcessEnv} from '../../child-env.js'
|
|
4
|
+
import {createPathClassifier, hasPathClass} from '../../path-classification.js'
|
|
5
|
+
|
|
6
|
+
const SEVERITY_RANK = {critical: 0, high: 1, medium: 2, low: 3, info: 4}
|
|
7
|
+
const AUDIT_NON_PRODUCT_CLASSES = ['test', 'e2e', 'generated', 'mock', 'story', 'docs', 'benchmark', 'temp']
|
|
8
|
+
|
|
9
|
+
export function formatAuditFinding(f) {
|
|
10
|
+
const where = f.file ? ` (${f.file}${f.symbol ? ` ${f.symbol}` : ''})` : f.package ? ` (pkg ${f.package}${f.version ? `@${f.version}` : ''}${f.manifest ? `; ${f.manifest}` : ''})` : ''
|
|
11
|
+
const verification = f.verification?.evidenceModel
|
|
12
|
+
? `\n verification: ${f.verification.evidenceModel}; manifest ${f.verification.manifestDeclaration?.status || 'N/A'}; indexed imports ${f.verification.indexedSourceImports?.status || 'N/A'}; decision ${f.verification.decision || 'REVIEW_REQUIRED'}`
|
|
13
|
+
: ''
|
|
14
|
+
return ` [${f.severity}/${f.confidence || '?'}] ${f.rule}: ${f.title}${where}${f.reason ? `\n reason: ${f.reason}` : ''}${verification}${f.cycleRoute ? `\n route: ${f.cycleRoute}` : ''}${f.fixHint ? `\n fix: ${f.fixHint}` : ''}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const auditFindingPaths = (finding) => {
|
|
18
|
+
const paths = []
|
|
19
|
+
if (finding?.file) paths.push(String(finding.file))
|
|
20
|
+
if (Array.isArray(finding?.files)) paths.push(...finding.files.map(String))
|
|
21
|
+
if (finding?.cycleRoute) paths.push(...String(finding.cycleRoute).split(/\s*(?:→|→|->)\s*/))
|
|
22
|
+
return [...new Set(paths.map((file) => file.replace(/\\/g, '/').trim()).filter(Boolean))]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function auditFindingPathScope(findings, {includeClassified = false, repoRoot = null} = {}) {
|
|
26
|
+
const all = Array.isArray(findings) ? findings : []
|
|
27
|
+
if (includeClassified) return {findings: all, suppressed: 0}
|
|
28
|
+
const classifier = createPathClassifier(repoRoot)
|
|
29
|
+
const cache = new Map()
|
|
30
|
+
const classified = (file) => {
|
|
31
|
+
if (!cache.has(file)) cache.set(file, classifier.explain(file, {content: ''}))
|
|
32
|
+
const info = cache.get(file)
|
|
33
|
+
return info?.excluded || AUDIT_NON_PRODUCT_CLASSES.some((name) => hasPathClass(info, name))
|
|
34
|
+
}
|
|
35
|
+
const kept = all.filter((finding) => {
|
|
36
|
+
const paths = auditFindingPaths(finding)
|
|
37
|
+
return !paths.length || paths.some((file) => !classified(file))
|
|
38
|
+
})
|
|
39
|
+
return {findings: kept, suppressed: all.length - kept.length}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const DEPENDENCY_AUDIT_RULES = new Set(['unused-dep', 'missing-dep', 'duplicate-dep', 'unresolved-import', 'lockfile-drift'])
|
|
43
|
+
export const isDependencyAuditFinding = (finding) => DEPENDENCY_AUDIT_RULES.has(String(finding?.rule || ''))
|
|
44
|
+
|
|
45
|
+
export const auditFilter = (audit, args, findings = audit.findings, repoRoot = null) => {
|
|
46
|
+
const minSev = SEVERITY_RANK[args.min_severity] ?? 4
|
|
47
|
+
const category = args.category ? String(args.category) : null
|
|
48
|
+
return auditFindingPathScope(findings, {includeClassified: args.include_classified === true, repoRoot}).findings
|
|
49
|
+
.filter((finding) => (SEVERITY_RANK[finding.severity] ?? 4) <= minSev)
|
|
50
|
+
.filter((finding) => !category || (category === 'dependencies' ? isDependencyAuditFinding(finding) : finding.category === category))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const auditChecksLine = (audit) => {
|
|
54
|
+
const check = (name, state) => `${name} ${state?.status || 'ERROR'}${state?.detail ? ` — ${state.detail}` : ''}`
|
|
55
|
+
return `Checks: ${check('OSV', audit.checks?.osv)}; ${check('malware', audit.checks?.malware)}. A NOT_CHECKED/PARTIAL/ERROR check is incomplete or unknown, never a clean zero.`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const auditCapabilityLines = (audit) => {
|
|
59
|
+
const matrix = audit.healthCapabilities || {}
|
|
60
|
+
const rows = [
|
|
61
|
+
['structure', 'structure'],
|
|
62
|
+
['dependencies', 'dependencies'],
|
|
63
|
+
['runtimeCorrectness', 'runtime correctness'],
|
|
64
|
+
['concurrency', 'concurrency'],
|
|
65
|
+
['advisories', 'advisories'],
|
|
66
|
+
['malware', 'malware'],
|
|
67
|
+
['coverage', 'coverage'],
|
|
68
|
+
]
|
|
69
|
+
const lines = ['Health capability matrix (status/completeness):']
|
|
70
|
+
for (const [key, label] of rows) {
|
|
71
|
+
const item = matrix[key]
|
|
72
|
+
lines.push(` ${label}: ${item?.status || 'NOT_CHECKED'}/${item?.completeness || 'PARTIAL'} — ${item?.detail || 'Capability evidence was not reported.'}`)
|
|
73
|
+
}
|
|
74
|
+
return lines
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const auditDependencyCoverageLines = (deps) => {
|
|
78
|
+
const ecosystems = Object.values(deps.ecosystems || {}).filter((item) => item?.present)
|
|
79
|
+
const verification = Object.entries(deps.verificationCoverage || {})
|
|
80
|
+
return [
|
|
81
|
+
ecosystems.length
|
|
82
|
+
? `Dependency ecosystems: ${ecosystems.map((item) => `${item.ecosystem} ${item.status}/${item.completeness} (${item.manifests?.length || 0} manifest(s), ${item.declared || 0} declaration(s))`).join('; ')}.`
|
|
83
|
+
: 'Dependency ecosystems: no supported or unsupported dependency manifest was discovered.',
|
|
84
|
+
verification.length
|
|
85
|
+
? `Dependency verification coverage: ${verification.map(([ecosystem, state]) => `${ecosystem} ${state}`).join('; ')}. Per-finding evidence: ${deps.perFindingVerification ? 'AVAILABLE' : 'UNAVAILABLE'}.`
|
|
86
|
+
: 'Dependency verification coverage: NOT_CHECKED; no manifest evidence was available.',
|
|
87
|
+
]
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const auditDependencySummaryLine = (audit, deps) => {
|
|
91
|
+
const ecosystems = Object.values(deps.ecosystems || {}).filter((item) => item?.present)
|
|
92
|
+
const checked = ecosystems.filter((item) => item.status === 'CHECKED')
|
|
93
|
+
const unsupported = ecosystems.filter((item) => item.status === 'NOT_SUPPORTED')
|
|
94
|
+
if (!ecosystems.length || deps.status === 'NOT_CHECKED') {
|
|
95
|
+
return 'Dependency manifests: NOT_CHECKED — no dependency manifest was discovered; manifest-to-import verification did not run and no dependency verdict was produced.'
|
|
96
|
+
}
|
|
97
|
+
if (!checked.length && unsupported.length) {
|
|
98
|
+
const manifests = unsupported.reduce((total, item) => total + (item.manifests?.length || 0), 0)
|
|
99
|
+
const declared = unsupported.reduce((total, item) => total + (item.declared || 0), 0)
|
|
100
|
+
const names = unsupported.map((item) => item.ecosystem).join(', ')
|
|
101
|
+
return `Dependency manifests: ${deps.status || 'PARTIAL'} — discovered ${declared} declaration(s) in ${manifests} ${names} manifest(s), but package-to-artifact verification is NOT_SUPPORTED; no unused, missing, or duplicate-declaration verdict was produced for those ecosystems.`
|
|
102
|
+
}
|
|
103
|
+
if (checked.length && unsupported.length) {
|
|
104
|
+
const checkedManifests = checked.reduce((total, item) => total + (item.manifests?.length || 0), 0)
|
|
105
|
+
const checkedDeclared = checked.reduce((total, item) => total + (item.declared || 0), 0)
|
|
106
|
+
const unsupportedManifests = unsupported.reduce((total, item) => total + (item.manifests?.length || 0), 0)
|
|
107
|
+
const unsupportedDeclared = unsupported.reduce((total, item) => total + (item.declared || 0), 0)
|
|
108
|
+
const checkedNames = checked.map((item) => item.ecosystem).join(', ')
|
|
109
|
+
const unsupportedNames = unsupported.map((item) => item.ecosystem).join(', ')
|
|
110
|
+
return `Dependency manifests: ${deps.status || 'PARTIAL'} — checked ${checkedDeclared} declaration(s) across ${checkedManifests} supported manifest(s) (${checkedNames}); inventoried ${unsupportedDeclared} declaration(s) across ${unsupportedManifests} unsupported manifest(s) (${unsupportedNames}), where package-to-artifact verification is NOT_SUPPORTED. Supported-ecosystem findings: unused ${deps.unused ?? 'unknown'}, missing ${deps.missing ?? 'unknown'}, duplicate declarations ${deps.duplicateDeclarations ?? 'unknown'}.`
|
|
111
|
+
}
|
|
112
|
+
return `Dependency manifests: ${deps.status || 'UNKNOWN'} — checked ${deps.declared ?? audit.scanned.manifestDeps ?? 0} declared package(s) against ${deps.importRecords ?? audit.scanned.externalImports ?? 0} external import record(s); unused ${deps.unused ?? 'unknown'}, missing ${deps.missing ?? 'unknown'}, duplicate declarations ${deps.duplicateDeclarations ?? 'unknown'}.`
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const auditConventionLines = (audit) => {
|
|
116
|
+
const entries = audit.conventionReachability?.entries || []
|
|
117
|
+
if (!entries.length) return []
|
|
118
|
+
return [
|
|
119
|
+
`Convention reachability: ${audit.conventionReachability.count} framework-managed file(s) are external entry points, not orphan/dead findings${audit.conventionReachability.truncated ? ' (evidence capped)' : ''}:`,
|
|
120
|
+
...entries.slice(0, 5).map((entry) => ` [${entry.confidence}] ${entry.file} — ${entry.marker}: ${entry.reason}`),
|
|
121
|
+
audit.conventionReachability.count > 5 ? ` … +${audit.conventionReachability.count - 5} more in bounded JSON result data` : null,
|
|
122
|
+
].filter((line) => line != null)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export const formatOrdinaryAudit = (audit, args, findings = audit.findings, heading = null, repoRoot = null) => {
|
|
126
|
+
const max = Math.max(1, Math.min(100, Number(args.max_findings) || 30))
|
|
127
|
+
const pathScope = auditFindingPathScope(findings, {includeClassified: args.include_classified === true, repoRoot})
|
|
128
|
+
const filtered = auditFilter(audit, args, pathScope.findings, repoRoot)
|
|
129
|
+
const shown = filtered.slice(0, max)
|
|
130
|
+
const summary = summarizeFindings(pathScope.findings)
|
|
131
|
+
const sev = summary.bySeverity
|
|
132
|
+
const bycat = summary.byCategory
|
|
133
|
+
const deps = audit.dependencyReport || {}
|
|
134
|
+
return [
|
|
135
|
+
heading,
|
|
136
|
+
`Internal audit of ${audit.repo} (${audit.scanned.files} files, ${audit.scanned.symbols} symbols, ${audit.scanned.externalImports} external imports; malware scan: ${audit.scanned.malwareScanMode}).`,
|
|
137
|
+
...auditConventionLines(audit),
|
|
138
|
+
auditDependencySummaryLine(audit, deps),
|
|
139
|
+
...auditDependencyCoverageLines(deps),
|
|
140
|
+
...auditCapabilityLines(audit),
|
|
141
|
+
`Scoped severity: critical ${sev.critical}, high ${sev.high}, medium ${sev.medium}, low ${sev.low}, info ${sev.info}. Scoped categories: unused ${bycat.unused}, structure ${bycat.structure}, vulnerability ${bycat.vulnerability}, malware ${bycat.malware}.`,
|
|
142
|
+
pathScope.suppressed ? `Path policy: production-first; suppressed ${pathScope.suppressed} finding(s) whose evidence is entirely test/e2e/generated/mock/story/docs/benchmark/temp or explicitly excluded. Pass include_classified:true to include them.` : 'Path policy: production-first; no classified-only findings were suppressed.',
|
|
143
|
+
`Repository-level ${auditChecksLine(audit)}`,
|
|
144
|
+
'',
|
|
145
|
+
`Showing ${shown.length} of ${filtered.length} finding(s)${args.category ? ` in category "${args.category}"` : ''}${args.min_severity ? ` at ≥${args.min_severity}` : ''}:`,
|
|
146
|
+
...shown.map(formatAuditFinding),
|
|
147
|
+
filtered.length > shown.length ? ` … +${filtered.length - shown.length} more (raise max_findings or filter by category/min_severity)` : null,
|
|
148
|
+
].filter((line) => line != null).join('\n')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export const gitUntracked = (repoRoot) => {
|
|
152
|
+
const result = spawnSync('git', ['-C', repoRoot, 'ls-files', '--others', '--exclude-standard'], {
|
|
153
|
+
encoding: 'utf8', timeout: 8000, maxBuffer: 2 * 1024 * 1024, env: childProcessEnv(), windowsHide: true,
|
|
154
|
+
})
|
|
155
|
+
if (result.status !== 0) return {
|
|
156
|
+
ok: false,
|
|
157
|
+
files: [],
|
|
158
|
+
error: String(result.stderr || result.error?.message || 'git ls-files failed').trim(),
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
ok: true,
|
|
162
|
+
files: String(result.stdout || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean),
|
|
163
|
+
error: null,
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export const pathsFromClassification = (classification) => [...new Set(classification.files
|
|
168
|
+
.flatMap((file) => [file.oldPath, file.newPath])
|
|
169
|
+
.filter((file) => file && file !== '(diff unavailable)'))]
|
|
170
|
+
.sort((left, right) => left.localeCompare(right))
|
|
171
|
+
|
|
172
|
+
export const formatDebtFinding = (finding, state) => ` [${state}] ${formatAuditFinding(finding).trimStart()}`
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import {rawGraph, effectiveRawGraph} from '../graph-context.mjs'
|
|
2
|
+
import {runInternalAudit} from '../../analysis/internal-audit.js'
|
|
3
|
+
import {classifyChangeImpact} from '../../analysis/change-classification.js'
|
|
4
|
+
import {
|
|
5
|
+
compareAuditDebt,
|
|
6
|
+
normalizeAuditScopeFiles,
|
|
7
|
+
scopeAuditFindings,
|
|
8
|
+
} from '../../analysis/audit-debt.js'
|
|
9
|
+
import {buildInternalGraph} from '../../graph/internal-builder.js'
|
|
10
|
+
import {resolveGitCommit, withGitRefCheckout} from '../../analysis/git-ref-graph.js'
|
|
11
|
+
import {filterGraphForMode} from '../../graph/graph-filter.js'
|
|
12
|
+
import {toolResult} from '../tool-result.mjs'
|
|
13
|
+
const auditFormatVersion = new URL(import.meta.url).search
|
|
14
|
+
const {
|
|
15
|
+
auditFilter,
|
|
16
|
+
formatDebtFinding,
|
|
17
|
+
formatOrdinaryAudit,
|
|
18
|
+
gitUntracked,
|
|
19
|
+
pathsFromClassification,
|
|
20
|
+
} = await import(new URL(`./audit-format.mjs${auditFormatVersion}`, import.meta.url).href)
|
|
21
|
+
|
|
22
|
+
async function runAuditWithBaseline(args, ctx, currentGraph) {
|
|
23
|
+
const resolved = resolveGitCommit(ctx.repoRoot, args.base_ref)
|
|
24
|
+
if (!resolved.ok) return toolResult(`Audit baseline unavailable: ${resolved.error}.`, {
|
|
25
|
+
status: 'INVALID', comparison: {status: 'UNAVAILABLE', reason: resolved.error}, findings: [],
|
|
26
|
+
}, {completeness: {status: 'PARTIAL', reason: resolved.error}})
|
|
27
|
+
|
|
28
|
+
let currentAudit
|
|
29
|
+
try {
|
|
30
|
+
currentAudit = await runInternalAudit(ctx.repoRoot, {
|
|
31
|
+
graph: currentGraph,
|
|
32
|
+
skipMalwareScan: !args.include_malware_scan,
|
|
33
|
+
})
|
|
34
|
+
} catch (error) {
|
|
35
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
36
|
+
return toolResult(`Audit failed while building the current graph: ${reason}`, {
|
|
37
|
+
status: 'ERROR', comparison: {status: 'UNAVAILABLE', reason}, findings: [],
|
|
38
|
+
}, {completeness: {status: 'PARTIAL', reason}})
|
|
39
|
+
}
|
|
40
|
+
if (!currentAudit.ok) return toolResult(`Audit failed: ${currentAudit.error}`, {
|
|
41
|
+
status: 'ERROR', comparison: {status: 'UNAVAILABLE', reason: currentAudit.error}, findings: [],
|
|
42
|
+
}, {completeness: {status: 'PARTIAL', reason: currentAudit.error}})
|
|
43
|
+
|
|
44
|
+
const normalized = normalizeAuditScopeFiles(args.changed_files)
|
|
45
|
+
if (!normalized.ok) return toolResult(`Audit scope invalid: ${normalized.error}.`, {
|
|
46
|
+
status: 'INVALID', comparison: {status: 'UNAVAILABLE', reason: normalized.error}, findings: [],
|
|
47
|
+
}, {completeness: {status: 'PARTIAL', reason: normalized.error}})
|
|
48
|
+
let changedFiles = normalized.files
|
|
49
|
+
let completeChangeSet = false
|
|
50
|
+
let scopeSource = 'explicit changed_files'
|
|
51
|
+
let changeEvidence = null
|
|
52
|
+
if (changedFiles == null) {
|
|
53
|
+
completeChangeSet = true
|
|
54
|
+
const untracked = gitUntracked(ctx.repoRoot)
|
|
55
|
+
if (!untracked.ok) {
|
|
56
|
+
return toolResult(`Audit comparison stopped: untracked-file discovery failed (${untracked.error}). Pass changed_files explicitly to establish the scope.`, {
|
|
57
|
+
status: 'PARTIAL', comparison: {status: 'UNAVAILABLE', reason: untracked.error}, findings: [],
|
|
58
|
+
}, {completeness: {status: 'PARTIAL', reason: untracked.error}})
|
|
59
|
+
}
|
|
60
|
+
changeEvidence = classifyChangeImpact({
|
|
61
|
+
repoRoot: ctx.repoRoot,
|
|
62
|
+
graph: currentGraph,
|
|
63
|
+
base: resolved.commit,
|
|
64
|
+
files: untracked.files,
|
|
65
|
+
})
|
|
66
|
+
if (!changeEvidence.ok || changeEvidence.bounds?.truncated) {
|
|
67
|
+
const reason = changeEvidence.reasons.join(' ')
|
|
68
|
+
return toolResult(`Audit comparison stopped: changed-file derivation against ${resolved.ref} was incomplete. ${reason} Pass changed_files explicitly to establish a complete scope.`, {
|
|
69
|
+
status: 'PARTIAL', comparison: {status: 'UNAVAILABLE', reason}, findings: [], changeEvidence,
|
|
70
|
+
}, {completeness: {status: 'PARTIAL', reason}})
|
|
71
|
+
}
|
|
72
|
+
changedFiles = pathsFromClassification(changeEvidence)
|
|
73
|
+
if (changedFiles.length > 500) {
|
|
74
|
+
const reason = `derived changed-file scope contains ${changedFiles.length} files, above the 500-file comparison bound`
|
|
75
|
+
return toolResult(`Audit comparison stopped: ${reason}. Pass a narrower explicit changed_files scope.`, {
|
|
76
|
+
status: 'PARTIAL', comparison: {status: 'UNAVAILABLE', reason}, findings: [], changeEvidence,
|
|
77
|
+
}, {completeness: {status: 'PARTIAL', reason}})
|
|
78
|
+
}
|
|
79
|
+
scopeSource = `git diff ${resolved.commit.slice(0, 12)}…working-tree`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const baseline = await withGitRefCheckout(ctx.repoRoot, resolved.commit, async (checkout) => {
|
|
83
|
+
let graph = await buildInternalGraph(checkout)
|
|
84
|
+
const currentMode = ['full', 'no-tests', 'tests-only'].includes(currentGraph?.graphBuildMode)
|
|
85
|
+
? currentGraph.graphBuildMode : 'full'
|
|
86
|
+
if (currentMode !== 'full') graph = filterGraphForMode(graph, currentMode, {repoRoot: checkout})
|
|
87
|
+
graph.graphBuildMode = currentMode
|
|
88
|
+
graph.graphBuildScope = ''
|
|
89
|
+
return runInternalAudit(checkout, {graph, skipMalwareScan: true})
|
|
90
|
+
})
|
|
91
|
+
if (!baseline.ok || !baseline.value?.ok) {
|
|
92
|
+
const reason = baseline.error || baseline.value?.error || 'baseline audit failed'
|
|
93
|
+
return toolResult(`Audit baseline unavailable: ${reason}.`, {
|
|
94
|
+
status: 'ERROR', comparison: {status: 'UNAVAILABLE', reason}, findings: [],
|
|
95
|
+
}, {completeness: {status: 'PARTIAL', reason}})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const comparison = compareAuditDebt(currentAudit, baseline.value, changedFiles, {completeChangeSet})
|
|
99
|
+
const mode = ['new', 'existing', 'all'].includes(args.debt) ? args.debt : 'new'
|
|
100
|
+
const selectedRaw = mode === 'new' ? comparison.new : mode === 'existing' ? comparison.existing : comparison.all
|
|
101
|
+
const selected = auditFilter(currentAudit, args, selectedRaw, ctx.repoRoot)
|
|
102
|
+
const max = Math.max(1, Math.min(100, Number(args.max_findings) || 30))
|
|
103
|
+
const shown = selected.slice(0, max)
|
|
104
|
+
const optional = comparison.optional.checks.map((check) => `${check.name.toUpperCase()} UNCOMPARABLE (current ${check.current}; baseline ${check.baseline})`).join('; ')
|
|
105
|
+
const stateOf = (finding) => mode === 'all' ? finding.debtState : mode
|
|
106
|
+
const fixedShown = auditFilter(baseline.value, args, comparison.fixed, ctx.repoRoot).slice(0, Math.min(10, max))
|
|
107
|
+
const text = [
|
|
108
|
+
`${mode.toUpperCase()} DEBT — deterministic internal audit vs ${resolved.ref} (${resolved.commit.slice(0, 12)})`,
|
|
109
|
+
`Changed scope: ${changedFiles.length} file(s) from ${scopeSource}${changedFiles.length ? ` — ${changedFiles.slice(0, 12).join(', ')}${changedFiles.length > 12 ? ', …' : ''}` : ' — working tree matches the baseline'}.`,
|
|
110
|
+
`Scope comparison: ${comparison.totals.scope.new} new, ${comparison.totals.scope.existing} existing, ${comparison.totals.scope.fixed} fixed deterministic finding(s). Repository totals: ${comparison.totals.repository.new} new, ${comparison.totals.repository.existing} existing, ${comparison.totals.repository.fixed} fixed.`,
|
|
111
|
+
`Optional checks: ${optional}. Supply-chain findings are not assigned new/existing/fixed state from a source-only checkout.`,
|
|
112
|
+
'',
|
|
113
|
+
`Showing ${shown.length} of ${selected.length} ${mode} finding(s) after filters:`,
|
|
114
|
+
...shown.map((finding) => formatDebtFinding(finding, stateOf(finding))),
|
|
115
|
+
selected.length > shown.length ? ` … +${selected.length - shown.length} more` : null,
|
|
116
|
+
'',
|
|
117
|
+
`Fixed in this changed scope: ${comparison.fixed.length}${fixedShown.length ? ' (sample below)' : ''}.`,
|
|
118
|
+
...fixedShown.map((finding) => formatDebtFinding(finding, 'fixed')),
|
|
119
|
+
].filter((line) => line != null).join('\n')
|
|
120
|
+
return toolResult(text, {
|
|
121
|
+
status: 'COMPLETE',
|
|
122
|
+
mode: 'baseline-comparison',
|
|
123
|
+
debt: mode,
|
|
124
|
+
baseline: {ref: resolved.ref, commit: resolved.commit},
|
|
125
|
+
scope: {files: changedFiles, source: scopeSource},
|
|
126
|
+
comparison: {
|
|
127
|
+
status: 'COMPLETE',
|
|
128
|
+
scope: comparison.scope,
|
|
129
|
+
totals: comparison.totals,
|
|
130
|
+
new: comparison.new,
|
|
131
|
+
existing: comparison.existing,
|
|
132
|
+
fixed: comparison.fixed,
|
|
133
|
+
optional: comparison.optional,
|
|
134
|
+
},
|
|
135
|
+
findings: selected,
|
|
136
|
+
changeEvidence,
|
|
137
|
+
}, {
|
|
138
|
+
page: {shown: shown.length, total: selected.length, capped: shown.length < selected.length},
|
|
139
|
+
completeness: {status: 'COMPLETE'},
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Full internal health audit: dead code + unused exports, dependency findings (npm/go/py missing &
|
|
144
|
+
// unused deps), structure (import cycles / orphans / boundary rules), supply-chain (offline OSV
|
|
145
|
+
// advisories, typosquat, lockfile drift), optional malware heuristics.
|
|
146
|
+
export async function tRunAudit(g, args, ctx) {
|
|
147
|
+
if (!ctx.repoRoot) return 'Audit needs the repo root (not provided to this server).'
|
|
148
|
+
if (args.base_ref) return runAuditWithBaseline(args, ctx, rawGraph(ctx))
|
|
149
|
+
const audit = await runInternalAudit(ctx.repoRoot, {
|
|
150
|
+
graph: effectiveRawGraph(ctx),
|
|
151
|
+
skipMalwareScan: !args.include_malware_scan, // greps installed packages — slow, so opt-in
|
|
152
|
+
})
|
|
153
|
+
if (!audit.ok) return `Audit failed: ${audit.error}`
|
|
154
|
+
if (Array.isArray(args.changed_files)) {
|
|
155
|
+
const normalized = normalizeAuditScopeFiles(args.changed_files)
|
|
156
|
+
if (!normalized.ok) return `Changed-scope audit invalid: ${normalized.error}.`
|
|
157
|
+
const scoped = scopeAuditFindings(audit.findings, normalized.files)
|
|
158
|
+
const text = formatOrdinaryAudit(audit, args, scoped,
|
|
159
|
+
`CHANGED-SCOPE ONLY — ${normalized.files.length} explicitly supplied file(s); no baseline was provided, so these findings are not classified as new, existing, or fixed.`, ctx.repoRoot)
|
|
160
|
+
return toolResult(text, {
|
|
161
|
+
status: 'COMPLETE',
|
|
162
|
+
mode: 'changed-scope',
|
|
163
|
+
scope: {files: normalized.files, source: 'explicit changed_files'},
|
|
164
|
+
comparison: {status: 'UNAVAILABLE', reason: 'base_ref was not provided; changed-scope is not a new-debt claim'},
|
|
165
|
+
findings: auditFilter(audit, args, scoped, ctx.repoRoot),
|
|
166
|
+
}, {completeness: {status: 'COMPLETE'}})
|
|
167
|
+
}
|
|
168
|
+
return formatOrdinaryAudit(audit, args, audit.findings, null, ctx.repoRoot)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Named module clusters: graph communities labeled by their dominant folder instead of bare numbers.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import {effectiveRawGraph} from '../graph-context.mjs'
|
|
2
|
+
import {computeDeadCodeReview} from '../../analysis/dead-code-review.js'
|
|
3
|
+
import {
|
|
4
|
+
collectNonRuntimeRoots,
|
|
5
|
+
collectPackageScopes,
|
|
6
|
+
collectSourceTexts,
|
|
7
|
+
readRepoJson,
|
|
8
|
+
} from '../../analysis/internal-audit.collect.js'
|
|
9
|
+
import {entryFiles} from '../../analysis/internal-audit.reach.js'
|
|
10
|
+
import {createPathClassifier} from '../../path-classification.js'
|
|
11
|
+
import {createRepoBoundary} from '../../repo-path.js'
|
|
12
|
+
import {readCachedSymbolPrecisionEvidence} from '../../precision/symbol-query.js'
|
|
13
|
+
import {toolResult} from '../tool-result.mjs'
|
|
14
|
+
|
|
15
|
+
export function tFindDeadCode(g, args, ctx) {
|
|
16
|
+
if (!ctx.repoRoot) return 'Dead-code review needs the repo root (not provided to this server).'
|
|
17
|
+
const effectiveGraph = effectiveRawGraph(ctx)
|
|
18
|
+
const pointEvidence = readCachedSymbolPrecisionEvidence({repoRoot: ctx.repoRoot, graphPath: ctx.graphPath, graph: effectiveGraph})
|
|
19
|
+
const graph = {
|
|
20
|
+
...effectiveGraph,
|
|
21
|
+
precisionReferenceSymbols: [...new Set([
|
|
22
|
+
...(effectiveGraph.precisionReferenceSymbols || []),
|
|
23
|
+
...pointEvidence.referenceSymbols,
|
|
24
|
+
])],
|
|
25
|
+
precisionProductionReferenceSymbols: [...new Set([
|
|
26
|
+
...(effectiveGraph.precisionProductionReferenceSymbols || []),
|
|
27
|
+
...pointEvidence.productionReferenceSymbols,
|
|
28
|
+
])],
|
|
29
|
+
precisionTestReferenceSymbols: [...new Set([
|
|
30
|
+
...(effectiveGraph.precisionTestReferenceSymbols || []),
|
|
31
|
+
...pointEvidence.testReferenceSymbols,
|
|
32
|
+
])],
|
|
33
|
+
precisionNoReferenceSymbols: [...new Set([
|
|
34
|
+
...(effectiveGraph.precisionNoReferenceSymbols || []),
|
|
35
|
+
...pointEvidence.noReferenceSymbols,
|
|
36
|
+
])],
|
|
37
|
+
}
|
|
38
|
+
const boundary = createRepoBoundary(ctx.repoRoot)
|
|
39
|
+
const pkg = readRepoJson(boundary, 'package.json') || {}
|
|
40
|
+
const rules = readRepoJson(boundary, '.weavatrix-deps.json') || {}
|
|
41
|
+
const sources = collectSourceTexts(ctx.repoRoot, graph)
|
|
42
|
+
const dynamicTargets = new Set((graph.externalImports || [])
|
|
43
|
+
.filter((entry) => entry?.dynamic && entry?.target)
|
|
44
|
+
.map((entry) => String(entry.target).replace(/\\/g, '/')))
|
|
45
|
+
const frameworkEvidence = []
|
|
46
|
+
const entries = entryFiles(graph, collectPackageScopes(ctx.repoRoot, pkg), dynamicTargets, {
|
|
47
|
+
declaredEntries: rules.entrypoints || rules.entries || [],
|
|
48
|
+
sources,
|
|
49
|
+
conventionEvidence: frameworkEvidence,
|
|
50
|
+
})
|
|
51
|
+
for (const root of collectNonRuntimeRoots(ctx.repoRoot, rules)) {
|
|
52
|
+
for (const file of sources.keys()) if (file === root || file.startsWith(`${root}/`)) entries.add(file)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const review = computeDeadCodeReview(graph, sources, {
|
|
56
|
+
entrySet: entries,
|
|
57
|
+
dynamicTargets,
|
|
58
|
+
frameworkEvidence,
|
|
59
|
+
pathClassifier: createPathClassifier(ctx.repoRoot),
|
|
60
|
+
includeTests: args.include_tests === true,
|
|
61
|
+
includeClassified: args.include_classified === true,
|
|
62
|
+
minConfidence: args.min_confidence,
|
|
63
|
+
path: args.path,
|
|
64
|
+
kinds: args.kinds,
|
|
65
|
+
})
|
|
66
|
+
const max = Math.max(1, Math.min(100, Number(args.top_n) || 30))
|
|
67
|
+
const shown = review.candidates.slice(0, max)
|
|
68
|
+
const counts = review.totals.byConfidence
|
|
69
|
+
const suppression = Object.entries(review.suppressed)
|
|
70
|
+
.filter(([, count]) => count)
|
|
71
|
+
.map(([name, count]) => `${name} ${count}`)
|
|
72
|
+
.join(', ')
|
|
73
|
+
const lines = shown.map((candidate, index) => {
|
|
74
|
+
const subject = candidate.kind === 'file'
|
|
75
|
+
? candidate.file
|
|
76
|
+
: `${candidate.owner ? `${candidate.owner}.` : ''}${candidate.symbol || candidate.id}`
|
|
77
|
+
const where = `${candidate.file}${candidate.line ? `:${candidate.line}` : ''}`
|
|
78
|
+
return [
|
|
79
|
+
`${index + 1}. [${candidate.confidence}/${candidate.evidenceTier}/${candidate.classification}] ${subject} (${where})`,
|
|
80
|
+
` evidence: ${candidate.evidence.map((item) => item.fact).join(' ')}`,
|
|
81
|
+
candidate.caveats.length ? ` caution: ${candidate.caveats.join(' ')}` : null,
|
|
82
|
+
` remaining: ${candidate.remainingChecks.join(' ')}`,
|
|
83
|
+
].filter(Boolean).join('\n')
|
|
84
|
+
})
|
|
85
|
+
const text = [
|
|
86
|
+
`Dead-code review: ${shown.length} of ${review.candidates.length} candidate(s) shown (high ${counts.high}, medium ${counts.medium}, low ${counts.low}).`,
|
|
87
|
+
`Evidence tiers: strong static ${review.totals.byEvidenceTier.strongStatic}, bounded static ${review.totals.byEvidenceTier.boundedStatic}, high uncertainty ${review.totals.byEvidenceTier.highUncertainty}.`,
|
|
88
|
+
`Verdict: REVIEW_REQUIRED. This is static evidence, never permission to auto-delete or bulk-delete.`,
|
|
89
|
+
suppression ? `Suppressed by current filters: ${suppression}.` : null,
|
|
90
|
+
review.suppressed.confidence ? 'Use min_confidence=low only when public/framework/dynamic candidates need explicit review.' : null,
|
|
91
|
+
'',
|
|
92
|
+
...(lines.length ? lines : ['No candidates matched the current production/path/kind/confidence filters.']),
|
|
93
|
+
'',
|
|
94
|
+
'Before removal: read_source, get_dependents, exact search, framework/config/manifest inspection, and the repository tests.',
|
|
95
|
+
].filter((line) => line != null).join('\n')
|
|
96
|
+
return toolResult(text, {
|
|
97
|
+
status: 'COMPLETE',
|
|
98
|
+
verdict: 'REVIEW_REQUIRED',
|
|
99
|
+
candidates: shown,
|
|
100
|
+
totals: review.totals,
|
|
101
|
+
suppressed: review.suppressed,
|
|
102
|
+
repoSignals: review.repoSignals,
|
|
103
|
+
policy: review.policy,
|
|
104
|
+
}, {
|
|
105
|
+
warnings: review.warnings,
|
|
106
|
+
page: {shown: shown.length, total: review.candidates.length, capped: shown.length < review.candidates.length},
|
|
107
|
+
completeness: {status: 'COMPLETE'},
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {computeDuplicates} from '../../analysis/duplicates.js'
|
|
2
|
+
import {analyzeDuplicateGroups} from '../../analysis/duplicate-groups.js'
|
|
3
|
+
|
|
4
|
+
const NON_PRODUCT_DUPLICATE_CLASSES = new Set(['generated', 'mock', 'story', 'docs', 'benchmark', 'temp'])
|
|
5
|
+
const fragmentEligible = (fragment, {tokMin, skipTests, includeClassified}) => {
|
|
6
|
+
if (fragment.n < tokMin) return false
|
|
7
|
+
const classes = new Set(fragment.classes || [])
|
|
8
|
+
if (skipTests && (fragment.test || classes.has('test') || classes.has('e2e'))) return false
|
|
9
|
+
if (!includeClassified && (fragment.excluded || [...classes].some((name) => NON_PRODUCT_DUPLICATE_CLASSES.has(name)))) return false
|
|
10
|
+
return true
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function tFindDuplicates(g, args, ctx) {
|
|
14
|
+
if (!ctx.repoRoot) return 'Duplicate scan needs the repo root (not provided to this server).'
|
|
15
|
+
const simMin = Math.min(100, Math.max(50, Number(args.min_similarity) || 80))
|
|
16
|
+
const tokMin = Math.min(400, Math.max(12, Number(args.min_tokens) || 50))
|
|
17
|
+
const mode = args.mode === 'strict' ? 'strict' : 'renamed'
|
|
18
|
+
const skipTests = args.include_tests ? false : true
|
|
19
|
+
const includeClassified = args.include_classified === true || args.include_non_product === true
|
|
20
|
+
const includeStrings = !!args.include_strings
|
|
21
|
+
// semantic mode: same-name symbols across files, ranked by size — LOW similarity is the signal
|
|
22
|
+
// (same name, drifted behavior). Token-clone pairing is skipped entirely.
|
|
23
|
+
if (args.mode === 'semantic') {
|
|
24
|
+
const data = computeDuplicates(ctx.repoRoot, ctx.graphPath, {nameTwins: true, minTokens: tokMin})
|
|
25
|
+
const frags = data.frags
|
|
26
|
+
const candidates = []
|
|
27
|
+
for (const twin of data.nameTwins || []) {
|
|
28
|
+
const allowed = new Set(twin.members.filter((i) => fragmentEligible(frags[i], {tokMin, skipTests, includeClassified})))
|
|
29
|
+
const pairs = (twin.pairs || []).filter((p) => allowed.has(p.a) && allowed.has(p.b))
|
|
30
|
+
if (!pairs.length) continue
|
|
31
|
+
const closest = pairs.slice().sort((a, b) => b.similarity - a.similarity)[0]
|
|
32
|
+
const farthest = pairs.slice().sort((a, b) => a.similarity - b.similarity)[0]
|
|
33
|
+
if (closest.similarity >= 85) candidates.push({kind: 'clone', label: twin.label, pair: closest})
|
|
34
|
+
if (farthest.similarity <= 45) candidates.push({kind: 'collision', label: twin.label, pair: farthest})
|
|
35
|
+
}
|
|
36
|
+
for (const item of candidates) item.tokens = frags[item.pair.a].n + frags[item.pair.b].n
|
|
37
|
+
candidates.sort((a, b) => {
|
|
38
|
+
if (a.kind !== b.kind) return a.kind === 'clone' ? -1 : 1
|
|
39
|
+
return a.kind === 'clone'
|
|
40
|
+
? b.pair.similarity - a.pair.similarity || b.tokens - a.tokens
|
|
41
|
+
: b.tokens - a.tokens || a.pair.similarity - b.pair.similarity
|
|
42
|
+
})
|
|
43
|
+
if (!candidates.length) return 'No actionable same-name pairs across files (semantic mode; ambiguous middle-similarity pairs are suppressed).'
|
|
44
|
+
const top = candidates.slice(0, Math.min(30, Math.max(1, Number(args.top_n) || 15)))
|
|
45
|
+
const lines = top.map((item, k) => {
|
|
46
|
+
const a = frags[item.pair.a]
|
|
47
|
+
const b = frags[item.pair.b]
|
|
48
|
+
const verdict = item.kind === 'clone'
|
|
49
|
+
? 'near-identical duplicate candidate — review, then extract shared logic if the contract is truly shared'
|
|
50
|
+
: 'name collision, not a duplicate — inspect only if these definitions should share a contract'
|
|
51
|
+
return [
|
|
52
|
+
`${k + 1}. "${item.label}" — ${item.pair.similarity}% similar; ${verdict}`,
|
|
53
|
+
` ${a.file}:${a.start}-${a.end} (${a.n} tok)`,
|
|
54
|
+
` ${b.file}:${b.start}-${b.end} (${b.n} tok)`,
|
|
55
|
+
].join('\n')
|
|
56
|
+
})
|
|
57
|
+
return `Found ${candidates.length} actionable same-name pair(s) across files (semantic mode; one closest clone and/or farthest collision per name). Top ${top.length}:\n\n${lines.join('\n\n')}\n\nThese are review candidates, not automatic refactors. Use read_source on both sites before changing code.`
|
|
58
|
+
}
|
|
59
|
+
const analysis = analyzeDuplicateGroups(ctx.repoRoot, ctx.graphPath, args)
|
|
60
|
+
const groups = analysis.groups
|
|
61
|
+
const smallPolicy = tokMin < 30 ? ' Small fragments below 30 tokens require at least 95% similarity and two shared bounded fingerprints.' : ''
|
|
62
|
+
const suppressed = analysis.suppressed
|
|
63
|
+
const suppressionNote = suppressed && !includeClassified
|
|
64
|
+
? ` ${suppressed} fragment(s) classified as tests/e2e/generated/mock/story/docs/benchmark/temp or matched by .weavatrix.json exclude were suppressed; pass include_classified:true (and include_tests:true for tests) to inspect them explicitly.`
|
|
65
|
+
: ''
|
|
66
|
+
const boilerplateNote = analysis.boilerplateSuppressed
|
|
67
|
+
? ` ${analysis.boilerplateSuppressed} all-router framework boilerplate group(s) were suppressed; pass include_boilerplate:true to inspect them.`
|
|
68
|
+
: ''
|
|
69
|
+
if (!groups.length) return `No clones at ≥${simMin}% similarity / ≥${tokMin} tokens (${mode} mode). Try lowering the thresholds.${smallPolicy}${suppressionNote}${boilerplateNote}`
|
|
70
|
+
const top = groups.slice(0, Math.min(30, Math.max(1, Number(args.top_n) || 15)))
|
|
71
|
+
const lines = top.map((grp, k) => {
|
|
72
|
+
const isStr = grp.members.some((f) => f.kind === 'string')
|
|
73
|
+
const head = `${k + 1}. ${grp.members.length}× "${grp.members[0].label}"${isStr ? ' [string literal]' : ''} — ≤${grp.maxSim}% similar, ${grp.tokens} duplicated tokens`
|
|
74
|
+
const sites = grp.members.slice(0, 8).map((f) => ` ${f.file}:${f.start}-${f.end}`)
|
|
75
|
+
return [head, ...sites].join('\n')
|
|
76
|
+
})
|
|
77
|
+
return `Found ${groups.length} clone group(s) (${mode} mode, ≥${simMin}%, ≥${tokMin} tok${includeStrings ? ', incl. large string literals' : ''}). Top ${top.length}:\n\n${lines.join('\n\n')}\n\nUse read_source on any two sites to compare, then extract shared logic.${smallPolicy}${suppressionNote}${boilerplateNote}`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Focused dead-code review queue. Unlike the broad run_audit surface, this includes functions and
|
|
81
|
+
// methods with bounded source-free evidence, and explicitly demotes framework/dynamic/public API
|
|
82
|
+
// candidates. It never returns an automatic-delete verdict.
|
|
83
|
+
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import {rawGraph} from '../graph-context.mjs'
|
|
2
|
+
import {analyzeEndpointInventory} from '../../analysis/endpoints.js'
|
|
3
|
+
import {toolResult} from '../tool-result.mjs'
|
|
4
|
+
|
|
5
|
+
export function tListEndpoints(g, args, ctx) {
|
|
6
|
+
if (!ctx.repoRoot) return 'Endpoint detection needs the repo root (not provided to this server).'
|
|
7
|
+
const graph = rawGraph(ctx)
|
|
8
|
+
const codeFiles = [...new Set(
|
|
9
|
+
(graph.nodes || [])
|
|
10
|
+
.filter((n) => !String(n.id).includes('#') && n.source_file && n.file_type === 'code')
|
|
11
|
+
.map((n) => n.source_file)
|
|
12
|
+
)]
|
|
13
|
+
const inventory = analyzeEndpointInventory(ctx.repoRoot, codeFiles)
|
|
14
|
+
let eps = inventory.endpoints
|
|
15
|
+
const method = args.method ? String(args.method).toUpperCase() : null
|
|
16
|
+
const path = args.path ? String(args.path) : null
|
|
17
|
+
if (method) eps = eps.filter((endpoint) => endpoint.method === method)
|
|
18
|
+
if (path) eps = eps.filter((endpoint) => endpoint.path === path || endpoint.path.endsWith(path))
|
|
19
|
+
if (!eps.length) return 'No HTTP endpoints detected in the indexed code files.'
|
|
20
|
+
const max = Math.max(1, Math.min(300, Number(args.max_results) || 100))
|
|
21
|
+
const shown = eps.slice(0, max)
|
|
22
|
+
const stats = inventory.stats
|
|
23
|
+
const text = [
|
|
24
|
+
`${eps.length} endpoint(s) matched${eps.length > shown.length ? `, showing ${shown.length}` : ''}. Inventory: ${stats.declaredRoutes} declaration(s); ${stats.reachableStaticRoutes} statically reachable composed route(s); ${stats.localDeclarations} local/root declaration candidate(s); ${stats.staticMounts} static router mount(s)${stats.truncated ? `; TRUNCATED at ${stats.maxEndpoints}` : ''}.`,
|
|
25
|
+
...shown.map((e) => {
|
|
26
|
+
const via = e.mountChain?.length
|
|
27
|
+
? `\n declared ${e.declaredPath} in ${e.file}${e.line ? `:${e.line}` : ''}; mount chain ${e.mountChain.map((mount) => `${mount.file}:${mount.line} ${mount.path}`).join(' → ')}`
|
|
28
|
+
: ''
|
|
29
|
+
const activation = e.conditional
|
|
30
|
+
? `; conditional default ${e.defaultActive === false ? 'inactive' : e.defaultActive === true ? 'active' : 'unknown'}`
|
|
31
|
+
: ''
|
|
32
|
+
return ` ${e.method.toUpperCase().padEnd(6)} ${e.path}${e.handler ? ` → ${e.handler}` : ''} (${e.file}${e.line ? `:${e.line}` : ''}; ${e.mountState}/${e.confidence}${activation})${via}`
|
|
33
|
+
}),
|
|
34
|
+
].join('\n')
|
|
35
|
+
return toolResult(text, {
|
|
36
|
+
filters: {method, path},
|
|
37
|
+
stats,
|
|
38
|
+
endpoints: shown,
|
|
39
|
+
page: {shown: shown.length, total: eps.length, truncated: eps.length > shown.length || stats.truncated},
|
|
40
|
+
}, {completeness: {status: stats.truncated ? 'PARTIAL' : 'COMPLETE', reason: stats.truncated ? `endpoint cap ${stats.maxEndpoints} reached` : 'all indexed code files scanned'}})
|
|
41
|
+
}
|
|
42
|
+
|