-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathllm_test.go
More file actions
451 lines (409 loc) · 14.8 KB
/
Copy pathllm_test.go
File metadata and controls
451 lines (409 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package llmcontext
import (
"context"
"fmt"
"strings"
"testing"
"unicode/utf8"
"github.com/enola-labs/enola/internal/facts"
)
func makeSnapshot(ff []facts.Fact, insights []facts.Insight) *facts.Snapshot {
return &facts.Snapshot{
Meta: facts.SnapshotMeta{
GeneratedAt: "2024-01-01T00:00:00Z",
Duration: "1s",
FactCount: len(ff),
InsightCount: len(insights),
},
Facts: ff,
Insights: insights,
}
}
func TestTokenBudgetEnforcement(t *testing.T) {
// Create a snapshot with enough facts to generate long content
var ff []facts.Fact
for i := 0; i < 50; i++ {
ff = append(ff, facts.Fact{
Kind: facts.KindModule,
Name: strings.Repeat("module_", 10) + string(rune('A'+i%26)),
Props: map[string]any{
"language": "go",
},
})
}
snapshot := makeSnapshot(ff, nil)
// Small token budget (100 tokens = 400 chars) — enough for truncation logic
// to work (maxChars-100 must be positive; see BUG note below)
r := New(100)
artifacts, err := r.Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render: %v", err)
}
if len(artifacts) != 1 {
t.Fatalf("expected 1 artifact, got %d", len(artifacts))
}
content := string(artifacts[0].Content)
hasTruncation := strings.Contains(content, "[Truncated in:") || strings.Contains(content, "[Omitted:")
if !hasTruncation {
t.Error("expected truncation or omission marker in output")
}
// Content should be within budget (400 chars + truncation/omission message)
maxExpected := 100*4 + 80
if len(content) > maxExpected {
t.Errorf("content length %d exceeds expected truncated size %d", len(content), maxExpected)
}
}
func TestDetectDominantLanguage(t *testing.T) {
tests := []struct {
name string
facts []facts.Fact
wantLang string
}{
{
"go dominant",
[]facts.Fact{
{Kind: facts.KindModule, Props: map[string]any{"language": "go"}},
{Kind: facts.KindModule, Props: map[string]any{"language": "go"}},
{Kind: facts.KindModule, Props: map[string]any{"language": "go"}},
{Kind: facts.KindModule, Props: map[string]any{"language": "typescript"}},
},
"go",
},
{
"no modules",
nil,
"",
},
{
"single language",
[]facts.Fact{
{Kind: facts.KindModule, Props: map[string]any{"language": "swift"}},
},
"swift",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
snapshot := makeSnapshot(tt.facts, nil)
got := detectDominantLanguage(snapshot)
if got != tt.wantLang {
t.Errorf("detectDominantLanguage = %q, want %q", got, tt.wantLang)
}
})
}
}
func TestRender_EmptySnapshot(t *testing.T) {
snapshot := makeSnapshot(nil, nil)
r := New(4000)
artifacts, err := r.Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render: %v", err)
}
if len(artifacts) != 1 {
t.Fatalf("expected 1 artifact, got %d", len(artifacts))
}
content := string(artifacts[0].Content)
if !strings.Contains(content, "# Architecture Snapshot") {
t.Error("expected Architecture Snapshot header")
}
if !strings.Contains(content, "_No modules detected._") {
t.Error("expected 'No modules detected' fallback")
}
if !strings.Contains(content, "_No entry points detected._") {
t.Error("expected 'No entry points detected' fallback")
}
}
func TestCrossRepo_RendersDependencyTable(t *testing.T) {
ff := []facts.Fact{
{Kind: facts.KindService, Name: "svc-alpha", Repo: "svc-alpha",
Relations: []facts.Relation{{Kind: facts.RelDependsOn, Target: "svc-beta"}}},
{Kind: facts.KindService, Name: "svc-beta", Repo: "svc-beta"},
{Kind: facts.KindDependency, Name: "svc-alpha -> svc-beta", Repo: "svc-alpha",
Props: map[string]any{
"type": "cross_repo", "via": []string{"http"},
"endpoint_count": 1, "endpoints": []string{"GET /api/items/{id}"},
}},
{Kind: facts.KindDependency, Name: "svc-alpha -> lib-core", Repo: "svc-alpha",
Props: map[string]any{
"type": "cross_repo", "via": []string{"import"},
"import_count": 1, "import_samples": []string{"lib-core/money/converter"},
}},
}
content := string(mustRender(t, makeSnapshot(ff, nil)))
if !strings.Contains(content, "## Cross-Repo Dependencies") {
t.Fatalf("missing Cross-Repo Dependencies section:\n%s", content)
}
for _, want := range []string{
"`svc-alpha` | `svc-beta` | http",
"GET /api/items/{id}",
"`svc-alpha` | `lib-core` | import",
"lib-core/money/converter",
} {
if !strings.Contains(content, want) {
t.Errorf("cross-repo table missing %q in:\n%s", want, content)
}
}
}
func TestCrossRepo_OmittedWhenNoEdges(t *testing.T) {
content := string(mustRender(t, makeSnapshot([]facts.Fact{{Kind: facts.KindModule, Name: "m"}}, nil)))
if strings.Contains(content, "Cross-Repo Dependencies") {
t.Errorf("cross-repo section should be omitted for single-repo snapshots:\n%s", content)
}
}
func mustRender(t *testing.T, snapshot *facts.Snapshot) []byte {
t.Helper()
artifacts, err := New(16000).Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render: %v", err)
}
if len(artifacts) != 1 {
t.Fatalf("expected 1 artifact, got %d", len(artifacts))
}
return artifacts[0].Content
}
func TestRiskZones_IncludesCyclesAndViolations(t *testing.T) {
insights := []facts.Insight{
{Title: "Architecture pattern: hexagonal", Confidence: 0.8, Description: "Detected hexagonal"},
{Title: "Cyclic dependency detected (3 modules)", Confidence: 1.0, Description: "A -> B -> C -> A"},
{Title: "Layer violation: domain -> presentation", Confidence: 0.8, Description: "Domain imports presentation"},
}
snapshot := makeSnapshot(nil, insights)
r := New(4000)
artifacts, err := r.Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render: %v", err)
}
content := string(artifacts[0].Content)
// Cycle and violation should appear in Risk Zones
if !strings.Contains(content, "Cyclic dependency") {
t.Error("expected Cyclic dependency in Risk Zones")
}
if !strings.Contains(content, "Layer violation") {
t.Error("expected Layer violation in Risk Zones")
}
// Architecture pattern should NOT appear in Risk Zones section
// It appears in the Architecture Pattern section instead
riskIdx := strings.Index(content, "## Risk Zones")
if riskIdx >= 0 {
riskSection := content[riskIdx:]
nextSection := strings.Index(riskSection[1:], "## ")
if nextSection > 0 {
riskSection = riskSection[:nextSection+1]
}
if strings.Contains(riskSection, "Architecture pattern") {
t.Error("Architecture pattern insight should NOT appear in Risk Zones")
}
}
}
func TestCriticalModules_FanInFanOut(t *testing.T) {
ff := []facts.Fact{
{Kind: facts.KindModule, Name: "lib-core"},
{Kind: facts.KindModule, Name: "a"},
{Kind: facts.KindModule, Name: "b"},
{Kind: facts.KindModule, Name: "c"},
}
// a, b, c all import lib-core → lib-core has fanIn=3
for _, src := range []string{"a", "b", "c"} {
ff = append(ff, facts.Fact{
Kind: facts.KindDependency,
File: src + "/file.go",
Relations: []facts.Relation{
{Kind: facts.RelImports, Target: "lib-core"},
},
})
}
snapshot := makeSnapshot(ff, nil)
r := New(4000)
artifacts, err := r.Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render: %v", err)
}
content := string(artifacts[0].Content)
if !strings.Contains(content, "`lib-core`") {
t.Error("expected lib-core module in Critical Modules table")
}
// lib-core has fanIn=3, fanOut=0, score=3 → "low" criticality
if !strings.Contains(content, "| 3 | 0 |") {
t.Error("expected lib-core to have fanIn=3, fanOut=0")
}
}
// renderWithCoverage renders a minimal snapshot whose only extraction-quality
// signal is the given cross-repo coverage summary. A nil summary is the
// single-repo shape: coverageSummary returns nil when there are no service nodes.
func renderWithCoverage(t *testing.T, cov *facts.CoverageSummary) string {
t.Helper()
snapshot := makeSnapshot(nil, nil)
snapshot.Meta.Coverage = cov
return string(mustRender(t, snapshot))
}
// lineWith returns the first rendered line containing substr, or "" if none does.
func lineWith(content, substr string) string {
for _, line := range strings.Split(content, "\n") {
if strings.Contains(line, substr) {
return line
}
}
return ""
}
// A connected service resolves at least one outbound edge, so it is not a coverage
// gap — yet any call site it could not resolve still lands in UnresolvedEdges. That
// is the normal healthy multi-repo shape, and it must not hide the count.
func TestExtractionQuality_UnresolvedEdgesWithoutGaps(t *testing.T) {
content := renderWithCoverage(t, &facts.CoverageSummary{
ServicesTotal: 4, CoverageGaps: 0, UnresolvedEdges: 23, ExternalEdges: 2,
})
unresolved := lineWith(content, "Unresolved outbound edges")
if !strings.Contains(unresolved, "**23**") {
t.Errorf("unresolved-edge count not rendered; got line %q in:\n%s", unresolved, content)
}
if !strings.Contains(unresolved, "⚠️") {
t.Errorf("unresolved edges are an internal blind spot and must be flagged; got %q", unresolved)
}
external := lineWith(content, "external hosts")
if !strings.Contains(external, "**2**") {
t.Errorf("external-edge count not rendered; got line %q in:\n%s", external, content)
}
// External call sites are expected, not a blind spot: flagging them would invite
// exactly the misreading this section exists to prevent.
if strings.Contains(external, "⚠️") {
t.Errorf("external edges must not be flagged as a warning; got %q", external)
}
if strings.Contains(content, "coverage gaps") {
t.Errorf("no gaps in this snapshot, yet a gaps line rendered:\n%s", content)
}
if !strings.Contains(content, "These are extraction limits") {
t.Errorf("unresolved edges are an extraction limit; footer missing in:\n%s", content)
}
}
func TestExtractionQuality_GapsStillRender(t *testing.T) {
content := renderWithCoverage(t, &facts.CoverageSummary{
ServicesTotal: 2, CoverageGaps: 1, UnresolvedEdges: 348,
})
if gaps := lineWith(content, "Cross-repo coverage gaps"); !strings.Contains(gaps, "**1**") {
t.Errorf("gap count not rendered; got line %q in:\n%s", gaps, content)
}
if unresolved := lineWith(content, "Unresolved outbound edges"); !strings.Contains(unresolved, "**348**") {
t.Errorf("unresolved count not rendered alongside gaps; got line %q in:\n%s", unresolved, content)
}
if strings.Contains(content, "external hosts") {
t.Errorf("no external edges in this snapshot, yet a line rendered:\n%s", content)
}
if !strings.Contains(content, "These are extraction limits") {
t.Errorf("footer missing in:\n%s", content)
}
}
// Clean cross-repo coverage stays quiet: the section header still renders (Coverage
// is non-nil), but nothing warns.
func TestExtractionQuality_CleanCoverageQuiet(t *testing.T) {
content := renderWithCoverage(t, &facts.CoverageSummary{ServicesTotal: 4})
if !strings.Contains(content, "## Extraction Quality") {
t.Fatalf("section should render whenever Coverage is non-nil:\n%s", content)
}
for _, unwanted := range []string{
"coverage gaps", "Unresolved outbound edges", "external hosts", "These are extraction limits",
} {
if strings.Contains(content, unwanted) {
t.Errorf("clean coverage must not render %q in:\n%s", unwanted, content)
}
}
}
// A single-repo snapshot has no service nodes, so Coverage is nil and there is no
// receipt to report on at all.
func TestExtractionQuality_SingleRepoNoCoverage(t *testing.T) {
content := renderWithCoverage(t, nil)
if strings.Contains(content, "## Extraction Quality") {
t.Errorf("section should be absent with no receipt and no coverage:\n%s", content)
}
}
// bigRepoMapSnapshot returns a snapshot whose Repository Map alone overruns any
// small token budget — the shape of a real multi-repo cluster.
func bigRepoMapSnapshot(modules int, cov *facts.CoverageSummary) *facts.Snapshot {
var ff []facts.Fact
for i := 0; i < modules; i++ {
ff = append(ff, facts.Fact{
Kind: facts.KindModule,
Name: fmt.Sprintf("service/%03d/%s", i, strings.Repeat("segment_", 4)),
Props: map[string]any{"language": "go"},
})
}
snapshot := makeSnapshot(ff, nil)
snapshot.Meta.FilesSeen = 5552
snapshot.Meta.FilesParsed = 2870
snapshot.Meta.Coverage = cov
return snapshot
}
// The Extraction Quality preface is the signal an agent uses to calibrate how far to
// trust the graph, and it is worth more than the tail of a module table. An earlier
// oversized section must not starve it — which is exactly what happened on a 4-repo
// snapshot, where the whole section vanished behind "[Truncated in: Repository Map]".
func TestRender_ExtractionQualitySurvivesTruncatedRepoMap(t *testing.T) {
const maxTokens = 1000
snapshot := bigRepoMapSnapshot(400, &facts.CoverageSummary{
ServicesTotal: 4, CoverageGaps: 0, UnresolvedEdges: 23, ExternalEdges: 2,
})
artifacts, err := New(maxTokens).Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render: %v", err)
}
content := string(artifacts[0].Content)
if !strings.Contains(content, "[Truncated in: Repository Map]") {
t.Fatalf("test is not exercising truncation; Repository Map fit the budget:\n%s", content)
}
if !strings.Contains(content, "## Extraction Quality") {
t.Errorf("Extraction Quality starved by an earlier oversized section:\n%s", content)
}
if !strings.Contains(content, "**23**") {
t.Errorf("unresolved-edge count lost to truncation:\n%s", content)
}
// The reservation must come out of the budget, not be added on top of it.
if limit := maxTokens*4 + 100; len(content) > limit {
t.Errorf("content length %d exceeds budget %d", len(content), limit)
}
}
// The budget is a byte count, but the content is UTF-8: a warning glyph or a
// non-ASCII identifier must never be cut in half into invalid UTF-8.
func TestCutAt_NeverSplitsRune(t *testing.T) {
s := "map: `ünïcode/módule` ⚠️ tail"
for n := 0; n <= len(s); n++ {
got := cutAt(s, n)
if !utf8.ValidString(got) {
t.Errorf("cutAt(%q, %d) = %q, which is not valid UTF-8", s, n, got)
}
if len(got) > n {
t.Errorf("cutAt(%q, %d) returned %d bytes, over the limit", s, n, len(got))
}
}
}
// The cut point moves with the budget, so sweep it: some budget lands mid-rune in a
// non-ASCII module name, and the artifact must stay valid UTF-8 at every one.
func TestRender_TruncatedOutputIsValidUTF8(t *testing.T) {
snapshot := bigRepoMapSnapshot(400, nil)
for i := range snapshot.Facts {
snapshot.Facts[i].Name = fmt.Sprintf("sérvice/%03d/%s", i, strings.Repeat("ø", 20))
}
for tokens := 200; tokens <= 400; tokens++ {
artifacts, err := New(tokens).Render(context.Background(), snapshot)
if err != nil {
t.Fatalf("Render(%d): %v", tokens, err)
}
if !utf8.Valid(artifacts[0].Content) {
t.Fatalf("truncation at maxTokens=%d produced invalid UTF-8", tokens)
}
}
}
func TestFileDir(t *testing.T) {
tests := []struct {
input string
want string
}{
{"src/foo/bar.go", "src/foo"},
{"file.go", "."},
{"a/b/c/d.go", "a/b/c"},
}
for _, tt := range tests {
got := fileDir(tt.input)
if got != tt.want {
t.Errorf("fileDir(%q) = %q, want %q", tt.input, got, tt.want)
}
}
}