From e74fcc30983e169d5b46fde3cff2257af81834d4 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:19:03 +0100 Subject: [PATCH 01/10] fix(core): match component ids as whole tokens in component selection --- .../__tests__/match-component-id.test.ts | 29 +++++++++++++++ packages/core/src/providers/base-provider.ts | 37 ++++++++++++++++++- 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/providers/__tests__/match-component-id.test.ts diff --git a/packages/core/src/providers/__tests__/match-component-id.test.ts b/packages/core/src/providers/__tests__/match-component-id.test.ts new file mode 100644 index 00000000..78e9c0c7 --- /dev/null +++ b/packages/core/src/providers/__tests__/match-component-id.test.ts @@ -0,0 +1,29 @@ +import { describe, it, expect } from 'vitest'; +import { matchComponentId } from '../base-provider.js'; + +describe('matchComponentId', () => { + const ids = ['api', 'api-gateway', 'system.web']; + + it('prefers the exact id over a shorter prefix id', () => { + expect(matchComponentId('api-gateway', ids)).toBe('api-gateway'); + }); + + it('strips whitespace, backticks and quotes', () => { + expect(matchComponentId(' `api-gateway`\n', ids)).toBe('api-gateway'); + expect(matchComponentId('"api"', ids)).toBe('api'); + }); + + it('finds a whole-token id inside prose and picks the longest', () => { + expect(matchComponentId('The component is api-gateway.', ids)).toBe('api-gateway'); + expect(matchComponentId('I think api, not system.web', ids)).toBe('system.web'); + }); + + it('does not match inside a longer token', () => { + expect(matchComponentId('api-gateway-v2', ids)).toBeNull(); + expect(matchComponentId('myapi', ids)).toBeNull(); + }); + + it('returns null when nothing matches', () => { + expect(matchComponentId('unknown', ids)).toBeNull(); + }); +}); diff --git a/packages/core/src/providers/base-provider.ts b/packages/core/src/providers/base-provider.ts index 35ba2e43..5c230860 100644 --- a/packages/core/src/providers/base-provider.ts +++ b/packages/core/src/providers/base-provider.ts @@ -27,6 +27,37 @@ function debugLog(msg: string, data?: unknown): void { } } +function isIdChar(ch: string | undefined): boolean { + return ch !== undefined && /[A-Za-z0-9_.-]/.test(ch); +} + +export function matchComponentId(responseText: string, ids: string[]): string | null { + const reply = responseText + .trim() + .replace(/^[`'"]+|[`'"]+$/g, '') + .trim(); + if (ids.includes(reply)) return reply; + + let best: string | null = null; + for (const id of ids) { + if (id.length === 0 || (best !== null && id.length <= best.length)) continue; + let from = 0; + for (;;) { + const at = reply.indexOf(id, from); + if (at === -1) break; + const after = reply[at + id.length]; + // A trailing "." that ends a sentence is punctuation, not part of the id. + const afterOk = !isIdChar(after) || (after === '.' && !isIdChar(reply[at + id.length + 1])); + if (!isIdChar(reply[at - 1]) && afterOk) { + best = id; + break; + } + from = at + 1; + } + } + return best; +} + function formatDuration(startedAt: bigint): string { const elapsedMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000; if (elapsedMs < 1000) { @@ -96,8 +127,10 @@ export abstract class BaseProvider implements AIProvider { } debugLog('selectComponent raw response', responseText); - const matchedId = - data.components.map((c) => c.id).find((id) => responseText.includes(id)) ?? null; + const matchedId = matchComponentId( + responseText, + data.components.map((c) => c.id) + ); debugLog('selectComponent matched', matchedId); return matchedId; } From cfab14e48834f3d85072221a7ef19c0fb5fbc2c0 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:19:06 +0100 Subject: [PATCH 02/10] fix(core): raise Anthropic small output budget to 1500 tokens --- .../core/src/providers/anthropic/__tests__/provider.test.ts | 4 ++-- packages/core/src/providers/anthropic/provider.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/providers/anthropic/__tests__/provider.test.ts b/packages/core/src/providers/anthropic/__tests__/provider.test.ts index c40fc256..d318ebc4 100644 --- a/packages/core/src/providers/anthropic/__tests__/provider.test.ts +++ b/packages/core/src/providers/anthropic/__tests__/provider.test.ts @@ -120,7 +120,7 @@ describe('AnthropicProvider', () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: 'claude-haiku-4-5', - max_tokens: 600, + max_tokens: 1500, }) ); }); @@ -176,7 +176,7 @@ describe('AnthropicProvider', () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: 'claude-haiku-4-5', - max_tokens: 600, + max_tokens: 1500, }) ); }); diff --git a/packages/core/src/providers/anthropic/provider.ts b/packages/core/src/providers/anthropic/provider.ts index 81b636a2..40519877 100644 --- a/packages/core/src/providers/anthropic/provider.ts +++ b/packages/core/src/providers/anthropic/provider.ts @@ -11,7 +11,7 @@ import { import { ANTHROPIC_MODELS } from './models.js'; const MAX_TOKENS_BY_OUTPUT_SIZE = { - small: 600, + small: 1500, medium: 1500, large: 8192, } satisfies Record; From 9910bdfb8facbcc769699382b452890d8594d4b0 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:19:49 +0100 Subject: [PATCH 03/10] fix(core): match excludePaths on component path segments, not string prefix --- packages/core/src/adapters/likec4/__tests__/adapter.test.ts | 6 ++++++ packages/core/src/adapters/likec4/adapter.ts | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/core/src/adapters/likec4/__tests__/adapter.test.ts b/packages/core/src/adapters/likec4/__tests__/adapter.test.ts index 0db07f07..1dff7b60 100644 --- a/packages/core/src/adapters/likec4/__tests__/adapter.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/adapter.test.ts @@ -417,6 +417,12 @@ describe('LikeC4Adapter - Component Exclusion', () => { expect(findId(components, 'frontend')).toBeDefined(); }); + it('should not exclude sibling IDs that merely share a prefix', async () => { + await setupExclusion(['api']); + const components = adapter.extractComponents(); + expect(findId(components, 'api_gateway')).toBeDefined(); + }); + it('should handle hierarchical component IDs', async () => { await setupExclusion(['azure_infrastructure']); const components = adapter.extractComponents(); diff --git a/packages/core/src/adapters/likec4/adapter.ts b/packages/core/src/adapters/likec4/adapter.ts index a22e4f22..10baf0cc 100644 --- a/packages/core/src/adapters/likec4/adapter.ts +++ b/packages/core/src/adapters/likec4/adapter.ts @@ -43,7 +43,9 @@ export class LikeC4Adapter implements ArchitectureModelAdapter { const { excludePaths, excludeTags } = CONFIG.adapter.likec4; if (excludePaths.length > 0) { - const matchesPath = excludePaths.some((excludePath) => componentId.startsWith(excludePath)); + const matchesPath = excludePaths.some( + (excludePath) => componentId === excludePath || componentId.startsWith(`${excludePath}.`) + ); if (matchesPath) { return true; } From a5deac86e7118cf7cdbc81a6a07eaffb8e8a6b9d Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:20:16 +0100 Subject: [PATCH 04/10] fix(core): include kind when checking for duplicate relationships --- packages/core/src/adapters/base-patcher.ts | 4 +- .../deduplicate-relationships.test.ts | 46 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index e88312df..75b101eb 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -255,7 +255,9 @@ export abstract class BasePatcher implements ModelPatcher { return valid.filter((rel) => { const isDuplicate = existingRelationships.some( (existing) => - (existing.source === rel.source && existing.target === rel.target) || + (existing.source === rel.source && + existing.target === rel.target && + (rel.kind === undefined || existing.kind === rel.kind)) || (existing.bidirectional === true && existing.source === rel.target && existing.target === rel.source) diff --git a/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts b/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts new file mode 100644 index 00000000..addf4ddd --- /dev/null +++ b/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect } from 'vitest'; +import { LikeC4Patcher } from '../patcher.js'; +import type { PatchResult } from '../../model-patcher.js'; +import type { ModelRelationship } from '../../architecture-types.js'; + +class TestPatcher extends LikeC4Patcher { + public dedupe( + valid: { source: string; target: string; kind?: string; description: string }[], + existing: ModelRelationship[] + ) { + const skipped: PatchResult['skipped'] = []; + return { kept: this.deduplicateRelationships(valid, existing, skipped), skipped }; + } +} + +describe('deduplicateRelationships', () => { + const patcher = new TestPatcher(); + const rel = (kind?: string) => ({ source: 'api', target: 'db', kind, description: 'x' }); + + it('keeps a relationship whose kind differs from the existing one', () => { + const { kept } = patcher.dedupe([rel('async')], [{ source: 'api', target: 'db' }]); + expect(kept).toHaveLength(1); + }); + + it('drops a relationship with the same kind', () => { + const { kept, skipped } = patcher.dedupe( + [rel('async')], + [{ source: 'api', target: 'db', kind: 'async' }] + ); + expect(kept).toHaveLength(0); + expect(skipped).toHaveLength(1); + }); + + it('drops a kindless relationship when any relationship exists between the pair', () => { + const { kept } = patcher.dedupe([rel()], [{ source: 'api', target: 'db', kind: 'async' }]); + expect(kept).toHaveLength(0); + }); + + it('still honours bidirectional existing relationships', () => { + const { kept } = patcher.dedupe( + [{ source: 'db', target: 'api', description: 'x' }], + [{ source: 'api', target: 'db', bidirectional: true }] + ); + expect(kept).toHaveLength(0); + }); +}); From b5dbf0d8449206a6507b512b16b3d5a9464e1d53 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:20:36 +0100 Subject: [PATCH 05/10] fix(core): keep quoted text in Structurizr strings instead of stripping quotes --- .../structurizr/__tests__/patcher.test.ts | 21 ++++++++++++++++++ .../core/src/adapters/structurizr/patcher.ts | 22 ++++++++++++++----- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/packages/core/src/adapters/structurizr/__tests__/patcher.test.ts b/packages/core/src/adapters/structurizr/__tests__/patcher.test.ts index 015e34eb..03a02445 100644 --- a/packages/core/src/adapters/structurizr/__tests__/patcher.test.ts +++ b/packages/core/src/adapters/structurizr/__tests__/patcher.test.ts @@ -152,6 +152,27 @@ describe('StructurizrPatcher', () => { expect(result.insertedLines[0]).toBe(' user -> system "Accesses"'); }); + it('should keep quoted text as single quotes and collapse newlines', async () => { + mockReaddirSync.mockReturnValue(['workspace.dsl'] as unknown as ReturnType); + mockReadFileSync.mockReturnValue(SAMPLE_DSL); + + const rels: StructuredRelationship[] = [ + { source: 'user', target: 'system', kind: 'HT"TPS', description: 'Calls "v2" API\nnow' }, + ]; + + const result = await patcher.patch({ + modelPath: '/model', + relationships: rels, + existingRelationships: [], + componentIndex: makeIndex(['user', 'system']), + provider: makeProvider(), + }); + + expect(result?.insertedLines[0]).toBe( + ' user -> system "Calls \'v2\' API now" "HT\'TPS"' + ); + }); + it('should use deterministic fallback and insert before model closing brace', async () => { mockReaddirSync.mockReturnValue(['workspace.dsl'] as unknown as ReturnType); mockReadFileSync.mockReturnValue(SAMPLE_DSL); diff --git a/packages/core/src/adapters/structurizr/patcher.ts b/packages/core/src/adapters/structurizr/patcher.ts index 083ec717..f0eba001 100644 --- a/packages/core/src/adapters/structurizr/patcher.ts +++ b/packages/core/src/adapters/structurizr/patcher.ts @@ -6,6 +6,18 @@ import type { StructuredRelationship, NewComponent } from '../../analysis/analys import type { ModelRelationship } from '../architecture-types.js'; import type { DslValidationResult } from '../model-patcher.js'; +/** + * Escaping of `"` inside Structurizr strings is not documented, so quotes become `'` + * (keeps the text) rather than `\"`. Backslashes are dropped so one cannot escape the closing quote. + */ +function dslString(text: string): string { + return text + .replace(/\\/g, '') + .replace(/"/g, "'") + .replace(/\s*[\r\n]+\s*/g, ' ') + .trim(); +} + export class StructurizrPatcher extends BasePatcher { protected readonly formatName = 'StructurizrPatcher'; protected readonly formatId = 'structurizr'; @@ -20,17 +32,17 @@ export class StructurizrPatcher extends BasePatcher { _existing: ModelRelationship[] ): string[] { return unique.map((rel) => { - const desc = rel.description.replace(/"/g, ''); - const technology = rel.kind ? ` "${rel.kind.replace(/"/g, '')}"` : ''; + const desc = dslString(rel.description); + const technology = rel.kind ? ` "${dslString(rel.kind)}"` : ''; return ` ${rel.source} -> ${rel.target} "${desc}"${technology}`; }); } protected generateComponentDslLines(components: NewComponent[]): string[] { return components.map((comp) => { - const name = comp.name.replace(/"/g, ''); - const desc = (comp.description ?? '').replace(/"/g, ''); - const tech = comp.technology ? ` "${comp.technology.replace(/"/g, '')}"` : ''; + const name = dslString(comp.name); + const desc = dslString(comp.description ?? ''); + const tech = comp.technology ? ` "${dslString(comp.technology)}"` : ''; return ` ${comp.id} = ${comp.kind} "${name}" "${desc}"${tech}`; }); } From c2beac21fedf6334b90dfa195673d13bc5802e38 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:21:04 +0100 Subject: [PATCH 06/10] fix(core): enforce maxLinesPerDiff by dropping files past the line budget --- .../__tests__/platform-utils.test.ts | 33 +++++++++-- packages/core/src/platforms/platform-utils.ts | 56 ++++++++++++++----- 2 files changed, 72 insertions(+), 17 deletions(-) diff --git a/packages/core/src/platforms/__tests__/platform-utils.test.ts b/packages/core/src/platforms/__tests__/platform-utils.test.ts index 91f2a24e..f78ca692 100644 --- a/packages/core/src/platforms/__tests__/platform-utils.test.ts +++ b/packages/core/src/platforms/__tests__/platform-utils.test.ts @@ -37,13 +37,38 @@ describe('applyDiffTruncation', () => { expect(result.truncationReason).toContain('60 files found'); }); - it('keeps all files but marks truncated when line count exceeds limit', () => { - const files = [makeFile('big.ts', 6000)]; - const result = applyDiffTruncation(files, 6000); + it('drops trailing files once the line budget is exceeded', () => { + const files = [makeFile('a.ts', 3000), makeFile('b.ts', 1500), makeFile('c.ts', 1000)]; + const result = applyDiffTruncation(files, 5500); expect(result.wasTruncated).toBe(true); - expect(result.files).toHaveLength(1); + expect(result.files.map((f) => f.filename)).toEqual(['a.ts', 'b.ts']); expect(result.truncationReason).toContain('5000-line limit'); + expect(result.truncationReason).toContain('5500 lines found'); + expect(result.truncationReason).toContain('1 file was dropped'); + }); + + it('always keeps the first file and cuts its patch to the budget', () => { + const patch = Array.from({ length: 6000 }, (_, i) => `+line${String(i)}`).join('\n'); + const files = [{ ...makeFile('big.ts', 6000), patch }, makeFile('b.ts', 10)]; + const result = applyDiffTruncation(files, 6010); + expect(result.files).toHaveLength(1); + expect(result.files[0]?.patch?.split('\n')).toHaveLength(5000); + expect(result.truncationReason).toContain('1 file was dropped'); + }); + + it('keeps an oversized first file without a patch and still flags truncation', () => { + const result = applyDiffTruncation([makeFile('big.ts', 6000)], 6000); + expect(result.wasTruncated).toBe(true); expect(result.truncationReason).toContain('6000 lines found'); + expect(result.files).toHaveLength(1); + }); + + it('applies the line budget after the file-count limit', () => { + const files = Array.from({ length: 60 }, (_, i) => makeFile(`f${String(i)}.ts`, 200)); + const result = applyDiffTruncation(files, 12000); + expect(result.files).toHaveLength(25); + expect(result.truncationReason).toContain('50-file limit'); + expect(result.truncationReason).toContain('25 files were dropped'); }); }); diff --git a/packages/core/src/platforms/platform-utils.ts b/packages/core/src/platforms/platform-utils.ts index 5d612417..50cdfc4b 100644 --- a/packages/core/src/platforms/platform-utils.ts +++ b/packages/core/src/platforms/platform-utils.ts @@ -9,27 +9,57 @@ interface TruncationResult { truncationReason?: string; } +function applyLineBudget( + files: ChangeRequestFile[], + maxLines: number +): { files: ChangeRequestFile[]; dropped: number; patchTrimmed: boolean } { + const kept: ChangeRequestFile[] = []; + let used = 0; + let patchTrimmed = false; + for (const file of files) { + if (kept.length > 0 && used + file.changes > maxLines) break; + if (kept.length === 0 && file.changes > maxLines && file.patch !== undefined) { + // The first file always stays, but its patch is cut to the budget. + kept.push({ ...file, patch: file.patch.split('\n').slice(0, maxLines).join('\n') }); + patchTrimmed = true; + } else { + kept.push(file); + } + used += file.changes; + } + return { files: kept, dropped: files.length - kept.length, patchTrimmed }; +} + export function applyDiffTruncation( files: ChangeRequestFile[], totalLines: number ): TruncationResult { + const { maxFilesPerDiff, maxLinesPerDiff } = CONFIG.constraints; const totalFiles = files.length; + const reasons: string[] = []; + let kept = files; - if (totalFiles > CONFIG.constraints.maxFilesPerDiff) { - return { - files: files.slice(0, CONFIG.constraints.maxFilesPerDiff), - wasTruncated: true, - truncationReason: `Diff surpassed the ${String(CONFIG.constraints.maxFilesPerDiff)}-file limit (${String(totalFiles)} files found). Only the first ${String(CONFIG.constraints.maxFilesPerDiff)} files were analyzed.`, - }; + if (totalFiles > maxFilesPerDiff) { + kept = files.slice(0, maxFilesPerDiff); + reasons.push( + `Diff surpassed the ${String(maxFilesPerDiff)}-file limit (${String(totalFiles)} files found). Only the first ${String(maxFilesPerDiff)} files were analyzed.` + ); } - if (totalLines > CONFIG.constraints.maxLinesPerDiff) { - return { - files, - wasTruncated: true, - truncationReason: `Diff surpassed the ${String(CONFIG.constraints.maxLinesPerDiff)}-line limit (${String(totalLines)} lines found). Analysis may be partial.`, - }; + if (totalLines > maxLinesPerDiff) { + const budgeted = applyLineBudget(kept, maxLinesPerDiff); + kept = budgeted.files; + const header = `Diff surpassed the ${String(maxLinesPerDiff)}-line limit (${String(totalLines)} lines found).`; + if (budgeted.dropped > 0 || budgeted.patchTrimmed) { + reasons.push( + `${header} ${String(budgeted.dropped)} ${budgeted.dropped === 1 ? 'file was' : 'files were'} dropped${budgeted.patchTrimmed ? ' and the first file was cut to fit' : ''}.` + ); + } else { + reasons.push(`${header} Analysis may be partial.`); + } } - return { files, wasTruncated: false }; + + if (reasons.length === 0) return { files, wasTruncated: false }; + return { files: kept, wasTruncated: true, truncationReason: reasons.join(' ') }; } export function sanitizeErrorMessage(message: string): string { From 3a228df8c42560dd4f2ca220be19120fe07d96b6 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:22:20 +0100 Subject: [PATCH 07/10] fix(core): throw when a prompt template references a missing variable --- .../__tests__/template-engine.test.ts | 112 ++++++++++++++++++ packages/core/src/analysis/template-engine.ts | 21 +++- 2 files changed, 127 insertions(+), 6 deletions(-) create mode 100644 packages/core/src/analysis/__tests__/template-engine.test.ts diff --git a/packages/core/src/analysis/__tests__/template-engine.test.ts b/packages/core/src/analysis/__tests__/template-engine.test.ts new file mode 100644 index 00000000..8377ca81 --- /dev/null +++ b/packages/core/src/analysis/__tests__/template-engine.test.ts @@ -0,0 +1,112 @@ +import { describe, it, expect } from 'vitest'; +import { TemplateEngine } from '../template-engine.js'; +import type { + ComponentSelectionPromptVars, + DependencyExtractionPromptVars, + DriftAnalysisPromptVars, + ModelPatchPromptVars, +} from '../prompt-variables.js'; + +const dependencyVars: DependencyExtractionPromptVars = { + diff: 'DIFF_SENTINEL', + commit: { sha: 'sha123', message: 'msg', author: 'dev' }, + repository: { owner: 'org', repo: 'app', url: 'https://example.com/org/app' }, + componentsContext: 'CTX_SENTINEL', +}; + +const componentVars: ComponentSelectionPromptVars = { + components: 'COMPONENTS_SENTINEL', + files: 'FILES_SENTINEL', +}; + +const driftVars: DriftAnalysisPromptVars = { + changeContext: { + label: 'a pull request', + headerPrefix: 'PULL REQUEST', + refLabel: 'PR #1:', + inSuffix: ' IN THIS PR', + considerations: 'CONSIDERATIONS_SENTINEL', + }, + changeRequest: { + number: 1, + title: 'TITLE_SENTINEL', + author: 'AUTHOR_SENTINEL', + base: { ref: 'main' }, + head: { ref: 'feature' }, + stats: { commits: 2, additions: 3, deletions: 4, files_changed: 5 }, + descriptionSection: '', + }, + component: { + name: 'NAME_SENTINEL', + id: 'comp.id', + type: 'service', + description: 'None', + repository: 'Unknown', + tags: 'None', + }, + commitsSection: 'COMMITS_SENTINEL', + commitsNote: '', + allowedDeps: 'ALLOWED_SENTINEL', + dependents: 'DEPENDENTS_SENTINEL', + allComponentIds: 'IDS_SENTINEL', + allRelationships: 'RELS_SENTINEL', + filesSection: 'FILESSECTION_SENTINEL', + dependencyChangesSection: 'DEPCHANGES_SENTINEL', +}; + +const patchVars: ModelPatchPromptVars = { + fileContent: 'FILECONTENT_SENTINEL', + linesToInsert: 'LINES_SENTINEL', + modelFormat: 'likec4', + syntaxGuide: 'GUIDE_SENTINEL', +}; + +describe('TemplateEngine real templates', () => { + it.each([ + ['dependency-extraction', () => TemplateEngine.loadDependencyExtractionPrompt(dependencyVars)], + ['component-selection', () => TemplateEngine.loadComponentSelectionPrompt(componentVars)], + ['drift-analysis', () => TemplateEngine.loadDriftAnalysisPrompt(driftVars)], + ['model-patch', () => TemplateEngine.loadModelPatchPrompt(patchVars)], + ])('renders %s with no unresolved placeholders', (_name, render) => { + const output = render(); + expect(output).not.toMatch(/\{\{[^}]*\}\}/); + expect(output.length).toBeGreaterThan(0); + }); + + it('substitutes representative values', () => { + expect(TemplateEngine.loadDependencyExtractionPrompt(dependencyVars)).toContain( + 'DIFF_SENTINEL' + ); + expect(TemplateEngine.loadDriftAnalysisPrompt(driftVars)).toContain('DEPCHANGES_SENTINEL'); + expect(TemplateEngine.loadModelPatchPrompt(patchVars)).toContain('GUIDE_SENTINEL'); + }); + + it('loads the bundled LikeC4 syntax guide', () => { + expect(TemplateEngine.loadSyntaxGuide('likec4', 'likec4-syntax-guide').length).toBeGreaterThan( + 0 + ); + }); + + it('throws naming the template and key when a variable is missing', () => { + const { files: _files, ...incomplete } = componentVars; + expect(() => + TemplateEngine.loadComponentSelectionPrompt(incomplete as ComponentSelectionPromptVars) + ).toThrow(/component-selection.*files/); + }); + + it('throws for a missing nested key', () => { + const vars = { + ...driftVars, + changeRequest: { ...driftVars.changeRequest, base: {} }, + } as unknown as DriftAnalysisPromptVars; + expect(() => TemplateEngine.loadDriftAnalysisPrompt(vars)).toThrow( + /drift-analysis.*changeRequest\.base\.ref/ + ); + }); + + it('renders an explicit empty string', () => { + expect(() => + TemplateEngine.loadComponentSelectionPrompt({ components: '', files: '' }) + ).not.toThrow(); + }); +}); diff --git a/packages/core/src/analysis/template-engine.ts b/packages/core/src/analysis/template-engine.ts index 30eaec05..0a60f114 100644 --- a/packages/core/src/analysis/template-engine.ts +++ b/packages/core/src/analysis/template-engine.ts @@ -62,10 +62,19 @@ function formatValue(value: unknown): string { } } -function replaceVariables(template: string, variables: object): string { +function replaceVariables(templateName: string, template: string, variables: object): string { return template.replace(/\{\{([^}]+)\}\}/g, (_match: string, path: string) => { const value = resolveVariable(variables, path); - return value === undefined ? '' : formatValue(value); + if (value === undefined) { + const key = path.trim(); + throw new ErodeError( + `Template "${templateName}" references missing variable "${key}"`, + ErrorCode.INTERNAL_UNKNOWN, + `Could not build the "${templateName}" prompt: no value for "${key}". This looks like a programming bug.`, + { templateName, key } + ); + } + return formatValue(value); }); } @@ -75,19 +84,19 @@ function replaceVariables(template: string, variables: object): string { export const TemplateEngine = { loadDependencyExtractionPrompt(variables: DependencyExtractionPromptVars): string { const template = loadTemplate('dependency-extraction'); - return replaceVariables(template, variables); + return replaceVariables('dependency-extraction', template, variables); }, loadDriftAnalysisPrompt(variables: DriftAnalysisPromptVars): string { const template = loadTemplate('drift-analysis'); - return replaceVariables(template, variables); + return replaceVariables('drift-analysis', template, variables); }, loadComponentSelectionPrompt(variables: ComponentSelectionPromptVars): string { const template = loadTemplate('component-selection'); - return replaceVariables(template, variables); + return replaceVariables('component-selection', template, variables); }, loadModelPatchPrompt(variables: ModelPatchPromptVars): string { const template = loadTemplate('model-patch'); - return replaceVariables(template, variables); + return replaceVariables('model-patch', template, variables); }, loadSyntaxGuide(adapterDir: string, name: string): string { const guidePath = join(__dirname, '..', 'adapters', adapterDir, 'prompts', `${name}.md`); From ff29575b6908d6cd3f65267d02b1838a7ad09bec Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 16:56:14 +0100 Subject: [PATCH 08/10] refactor(core): simplify template rendering helper --- packages/core/src/analysis/template-engine.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/packages/core/src/analysis/template-engine.ts b/packages/core/src/analysis/template-engine.ts index 0a60f114..934d2c9b 100644 --- a/packages/core/src/analysis/template-engine.ts +++ b/packages/core/src/analysis/template-engine.ts @@ -62,8 +62,8 @@ function formatValue(value: unknown): string { } } -function replaceVariables(templateName: string, template: string, variables: object): string { - return template.replace(/\{\{([^}]+)\}\}/g, (_match: string, path: string) => { +function renderTemplate(templateName: string, variables: object): string { + return loadTemplate(templateName).replace(/\{\{([^}]+)\}\}/g, (_match: string, path: string) => { const value = resolveVariable(variables, path); if (value === undefined) { const key = path.trim(); @@ -83,20 +83,16 @@ function replaceVariables(templateName: string, template: string, variables: obj */ export const TemplateEngine = { loadDependencyExtractionPrompt(variables: DependencyExtractionPromptVars): string { - const template = loadTemplate('dependency-extraction'); - return replaceVariables('dependency-extraction', template, variables); + return renderTemplate('dependency-extraction', variables); }, loadDriftAnalysisPrompt(variables: DriftAnalysisPromptVars): string { - const template = loadTemplate('drift-analysis'); - return replaceVariables('drift-analysis', template, variables); + return renderTemplate('drift-analysis', variables); }, loadComponentSelectionPrompt(variables: ComponentSelectionPromptVars): string { - const template = loadTemplate('component-selection'); - return replaceVariables('component-selection', template, variables); + return renderTemplate('component-selection', variables); }, loadModelPatchPrompt(variables: ModelPatchPromptVars): string { - const template = loadTemplate('model-patch'); - return replaceVariables('model-patch', template, variables); + return renderTemplate('model-patch', variables); }, loadSyntaxGuide(adapterDir: string, name: string): string { const guidePath = join(__dirname, '..', 'adapters', adapterDir, 'prompts', `${name}.md`); From 7f898235dbbe76c0a574e1d0f2d6d2b106dee704 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 17:11:20 +0100 Subject: [PATCH 09/10] fix(core): address review findings in small correctness fixes - apply the line budget in the shared pipeline after skip patterns, for analyze and check; skip oversized files instead of stopping - dedupe relationships by kind only for LikeC4 (Structurizr keeps endpoint matching) - normalise excludePaths (whitespace, trailing dot) and document segment semantics - matchComponentId prefers the earliest match in the reply - dependency scan uses the medium output budget; Anthropic small back to 600 - template engine renders missing variables empty with a debug warning --- packages/core/src/adapters/base-patcher.ts | 11 ++- .../adapters/likec4/__tests__/adapter.test.ts | 8 ++ .../deduplicate-relationships.test.ts | 19 +++- packages/core/src/adapters/likec4/adapter.ts | 8 +- packages/core/src/adapters/likec4/patcher.ts | 1 + .../deduplicate-relationships.test.ts | 23 +++++ .../core/src/adapters/structurizr/patcher.ts | 1 + .../__tests__/template-engine.test.ts | 50 +++++++--- packages/core/src/analysis/template-engine.ts | 35 ++++--- .../pipelines/__tests__/line-budget.test.ts | 59 ++++++++++++ packages/core/src/pipelines/analyze.ts | 14 +++ packages/core/src/pipelines/check.ts | 12 ++- .../core/src/pipelines/pipeline-shared.ts | 93 +++++++++++++++++++ .../__tests__/platform-utils.test.ts | 33 +------ packages/core/src/platforms/platform-utils.ts | 56 +++-------- .../__tests__/generation-profile.test.ts | 7 +- .../__tests__/match-component-id.test.ts | 9 +- .../anthropic/__tests__/provider.test.ts | 2 +- .../core/src/providers/anthropic/provider.ts | 2 +- packages/core/src/providers/base-provider.ts | 12 ++- .../gemini/__tests__/provider.test.ts | 2 +- .../core/src/providers/generation-profile.ts | 4 +- .../openai/__tests__/provider.test.ts | 2 +- .../docs/docs/reference/configuration.md | 2 + 24 files changed, 344 insertions(+), 121 deletions(-) create mode 100644 packages/core/src/adapters/structurizr/__tests__/deduplicate-relationships.test.ts create mode 100644 packages/core/src/pipelines/__tests__/line-budget.test.ts diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index 75b101eb..5dbaffbc 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -60,6 +60,8 @@ export abstract class BasePatcher implements ModelPatcher { protected abstract readonly formatName: string; protected abstract readonly formatId: string; protected abstract readonly defaultIndent: string; + /** Whether differing relationship kinds make a same-endpoint proposal distinct. */ + protected abstract readonly kindSensitiveDedup: boolean; protected abstract isModelBlockLine(line: string): boolean; @@ -252,15 +254,20 @@ export abstract class BasePatcher implements ModelPatcher { existingRelationships: ModelRelationship[], skipped: PatchResult['skipped'] ): StructuredRelationship[] { + // A proposal is a duplicate of a same-endpoint relationship unless both carry a kind and + // the kinds differ. Structurizr opts out: its `kind` is free-text technology. + const kindsDiffer = (a?: string, b?: string): boolean => + this.kindSensitiveDedup && a !== undefined && b !== undefined && a !== b; return valid.filter((rel) => { const isDuplicate = existingRelationships.some( (existing) => (existing.source === rel.source && existing.target === rel.target && - (rel.kind === undefined || existing.kind === rel.kind)) || + !kindsDiffer(rel.kind, existing.kind)) || (existing.bidirectional === true && existing.source === rel.target && - existing.target === rel.source) + existing.target === rel.source && + !kindsDiffer(rel.kind, existing.kind)) ); if (isDuplicate) { skipped.push({ diff --git a/packages/core/src/adapters/likec4/__tests__/adapter.test.ts b/packages/core/src/adapters/likec4/__tests__/adapter.test.ts index 1dff7b60..3eafb973 100644 --- a/packages/core/src/adapters/likec4/__tests__/adapter.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/adapter.test.ts @@ -423,6 +423,14 @@ describe('LikeC4Adapter - Component Exclusion', () => { expect(findId(components, 'api_gateway')).toBeDefined(); }); + it('should ignore surrounding whitespace and a trailing dot in configured paths', async () => { + await setupExclusion([' azure_infrastructure. ']); + const components = adapter.extractComponents(); + expect(findId(components, 'azure_infrastructure')).toBeUndefined(); + expect(findId(components, 'azure_infrastructure.vnet')).toBeUndefined(); + expect(findId(components, 'frontend')).toBeDefined(); + }); + it('should handle hierarchical component IDs', async () => { await setupExclusion(['azure_infrastructure']); const components = adapter.extractComponents(); diff --git a/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts b/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts index addf4ddd..09187c03 100644 --- a/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts @@ -17,11 +17,26 @@ describe('deduplicateRelationships', () => { const patcher = new TestPatcher(); const rel = (kind?: string) => ({ source: 'api', target: 'db', kind, description: 'x' }); - it('keeps a relationship whose kind differs from the existing one', () => { - const { kept } = patcher.dedupe([rel('async')], [{ source: 'api', target: 'db' }]); + it('keeps a relationship when both have a kind and the kinds differ', () => { + const { kept } = patcher.dedupe( + [rel('async')], + [{ source: 'api', target: 'db', kind: 'sync' }] + ); expect(kept).toHaveLength(1); }); + it('drops a relationship when the existing one has no kind', () => { + const { kept } = patcher.dedupe([rel('async')], [{ source: 'api', target: 'db' }]); + expect(kept).toHaveLength(0); + }); + + it('applies the kind rule to bidirectional relationships too', () => { + const reverse = { source: 'db', target: 'api', kind: 'async', description: 'x' }; + const existing = { source: 'api', target: 'db', bidirectional: true }; + expect(patcher.dedupe([reverse], [{ ...existing, kind: 'sync' }]).kept).toHaveLength(1); + expect(patcher.dedupe([reverse], [existing]).kept).toHaveLength(0); + }); + it('drops a relationship with the same kind', () => { const { kept, skipped } = patcher.dedupe( [rel('async')], diff --git a/packages/core/src/adapters/likec4/adapter.ts b/packages/core/src/adapters/likec4/adapter.ts index 10baf0cc..6f97ba22 100644 --- a/packages/core/src/adapters/likec4/adapter.ts +++ b/packages/core/src/adapters/likec4/adapter.ts @@ -43,9 +43,11 @@ export class LikeC4Adapter implements ArchitectureModelAdapter { const { excludePaths, excludeTags } = CONFIG.adapter.likec4; if (excludePaths.length > 0) { - const matchesPath = excludePaths.some( - (excludePath) => componentId === excludePath || componentId.startsWith(`${excludePath}.`) - ); + const matchesPath = excludePaths + .map((path) => path.trim().replace(/\.+$/, '')) + .some( + (path) => path !== '' && (componentId === path || componentId.startsWith(`${path}.`)) + ); if (matchesPath) { return true; } diff --git a/packages/core/src/adapters/likec4/patcher.ts b/packages/core/src/adapters/likec4/patcher.ts index d80c7960..06ef144d 100644 --- a/packages/core/src/adapters/likec4/patcher.ts +++ b/packages/core/src/adapters/likec4/patcher.ts @@ -45,6 +45,7 @@ export class LikeC4Patcher extends BasePatcher { protected readonly formatName = 'LikeC4Patcher'; protected readonly formatId = 'likec4'; protected readonly defaultIndent = ' '; + protected readonly kindSensitiveDedup = true; protected isModelBlockLine(line: string): boolean { return line.includes('model {') || line.includes('model{'); diff --git a/packages/core/src/adapters/structurizr/__tests__/deduplicate-relationships.test.ts b/packages/core/src/adapters/structurizr/__tests__/deduplicate-relationships.test.ts new file mode 100644 index 00000000..a5cca667 --- /dev/null +++ b/packages/core/src/adapters/structurizr/__tests__/deduplicate-relationships.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect } from 'vitest'; +import { StructurizrPatcher } from '../patcher.js'; +import type { PatchResult } from '../../model-patcher.js'; + +class TestPatcher extends StructurizrPatcher { + public dedupe( + valid: { source: string; target: string; kind?: string; description: string }[], + existing: { source: string; target: string; kind?: string }[] + ) { + const skipped: PatchResult['skipped'] = []; + return { kept: this.deduplicateRelationships(valid, existing, skipped), skipped }; + } +} + +describe('StructurizrPatcher deduplicateRelationships', () => { + it('matches on endpoints only, ignoring free-text technology in kind', () => { + const { kept } = new TestPatcher().dedupe( + [{ source: 'api', target: 'db', kind: 'async', description: 'x' }], + [{ source: 'api', target: 'db', kind: 'HTTPS' }] + ); + expect(kept).toHaveLength(0); + }); +}); diff --git a/packages/core/src/adapters/structurizr/patcher.ts b/packages/core/src/adapters/structurizr/patcher.ts index f0eba001..73c13554 100644 --- a/packages/core/src/adapters/structurizr/patcher.ts +++ b/packages/core/src/adapters/structurizr/patcher.ts @@ -22,6 +22,7 @@ export class StructurizrPatcher extends BasePatcher { protected readonly formatName = 'StructurizrPatcher'; protected readonly formatId = 'structurizr'; protected readonly defaultIndent = ' '; + protected readonly kindSensitiveDedup = false; protected isModelBlockLine(line: string): boolean { return /\bmodel\s*\{/.test(line); diff --git a/packages/core/src/analysis/__tests__/template-engine.test.ts b/packages/core/src/analysis/__tests__/template-engine.test.ts index 8377ca81..77f694d5 100644 --- a/packages/core/src/analysis/__tests__/template-engine.test.ts +++ b/packages/core/src/analysis/__tests__/template-engine.test.ts @@ -1,5 +1,11 @@ -import { describe, it, expect } from 'vitest'; -import { TemplateEngine } from '../template-engine.js'; +import { describe, it, expect, vi } from 'vitest'; +import { readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import { fileURLToPath } from 'url'; +import { TemplateEngine, findMissingVariables } from '../template-engine.js'; +import { CONFIG } from '../../utils/config.js'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); import type { ComponentSelectionPromptVars, DependencyExtractionPromptVars, @@ -87,21 +93,35 @@ describe('TemplateEngine real templates', () => { ); }); - it('throws naming the template and key when a variable is missing', () => { - const { files: _files, ...incomplete } = componentVars; - expect(() => - TemplateEngine.loadComponentSelectionPrompt(incomplete as ComponentSelectionPromptVars) - ).toThrow(/component-selection.*files/); + it('leaves no key of any real template without a value', () => { + // A missing key renders empty at runtime, so this is what catches a renamed variable. + const read = (name: string) => + readFileSync(join(__dirname, '..', 'prompts', `${name}.md`), 'utf-8'); + expect(findMissingVariables(read('dependency-extraction'), dependencyVars)).toEqual([]); + expect(findMissingVariables(read('component-selection'), componentVars)).toEqual([]); + expect(findMissingVariables(read('drift-analysis'), driftVars)).toEqual([]); + expect(findMissingVariables(read('model-patch'), patchVars)).toEqual([]); }); - it('throws for a missing nested key', () => { - const vars = { - ...driftVars, - changeRequest: { ...driftVars.changeRequest, base: {} }, - } as unknown as DriftAnalysisPromptVars; - expect(() => TemplateEngine.loadDriftAnalysisPrompt(vars)).toThrow( - /drift-analysis.*changeRequest\.base\.ref/ - ); + it('reports missing keys, including nested ones', () => { + expect(findMissingVariables('{{a}} {{ b.c }} {{d}}', { a: '', b: {} })).toEqual(['b.c', 'd']); + }); + + it('renders a missing variable as empty and warns in verbose mode', () => { + const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const previous = CONFIG.debug.verbose; + CONFIG.debug.verbose = true; + try { + const { files: _files, ...incomplete } = componentVars; + const output = TemplateEngine.loadComponentSelectionPrompt( + incomplete as ComponentSelectionPromptVars + ); + expect(output).not.toMatch(/\{\{[^}]*\}\}/); + expect(spy).toHaveBeenCalledWith(expect.stringMatching(/component-selection.*files/)); + } finally { + CONFIG.debug.verbose = previous; + spy.mockRestore(); + } }); it('renders an explicit empty string', () => { diff --git a/packages/core/src/analysis/template-engine.ts b/packages/core/src/analysis/template-engine.ts index 934d2c9b..3db8eac8 100644 --- a/packages/core/src/analysis/template-engine.ts +++ b/packages/core/src/analysis/template-engine.ts @@ -8,6 +8,7 @@ import type { import { join, dirname } from 'path'; import { fileURLToPath } from 'url'; import { ErodeError, ErrorCode } from '../errors.js'; +import { CONFIG } from '../utils/config.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -62,20 +63,30 @@ function formatValue(value: unknown): string { } } +const PLACEHOLDER = /\{\{([^}]+)\}\}/g; + +/** Placeholder keys in `template` that `variables` does not provide. */ +export function findMissingVariables(template: string, variables: object): string[] { + const missing: string[] = []; + for (const match of template.matchAll(PLACEHOLDER)) { + const key = (match[1] ?? '').trim(); + if (resolveVariable(variables, key) === undefined) missing.push(key); + } + return missing; +} + +// A missing key renders empty rather than aborting a real analysis; tests catch renamed +// variables through findMissingVariables. function renderTemplate(templateName: string, variables: object): string { - return loadTemplate(templateName).replace(/\{\{([^}]+)\}\}/g, (_match: string, path: string) => { - const value = resolveVariable(variables, path); - if (value === undefined) { - const key = path.trim(); - throw new ErodeError( - `Template "${templateName}" references missing variable "${key}"`, - ErrorCode.INTERNAL_UNKNOWN, - `Could not build the "${templateName}" prompt: no value for "${key}". This looks like a programming bug.`, - { templateName, key } - ); + const template = loadTemplate(templateName); + if (CONFIG.debug.verbose) { + for (const key of findMissingVariables(template, variables)) { + console.error(`[TemplateEngine] Template "${templateName}" has no value for "${key}"`); } - return formatValue(value); - }); + } + return template.replace(PLACEHOLDER, (_match: string, path: string) => + formatValue(resolveVariable(variables, path)) + ); } /** diff --git a/packages/core/src/pipelines/__tests__/line-budget.test.ts b/packages/core/src/pipelines/__tests__/line-budget.test.ts new file mode 100644 index 00000000..8c661de3 --- /dev/null +++ b/packages/core/src/pipelines/__tests__/line-budget.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from 'vitest'; +import { applyLineBudget, applyLineBudgetToDiff } from '../pipeline-shared.js'; +import type { ChangeRequestFile } from '../../platforms/source-platform.js'; + +function makeFile(filename: string, changes: number, patch?: string): ChangeRequestFile { + return { filename, status: 'modified', additions: changes, deletions: 0, changes, patch }; +} + +describe('applyLineBudget', () => { + it('returns files untouched when under budget', () => { + const files = [makeFile('a.ts', 10), makeFile('b.ts', 20)]; + const result = applyLineBudget(files, 100); + expect(result.files).toBe(files); + expect(result.truncationReason).toBeUndefined(); + }); + + it('skips a file that does not fit but keeps smaller later files', () => { + const files = [makeFile('a.ts', 60), makeFile('huge.ts', 200), makeFile('c.ts', 30)]; + const result = applyLineBudget(files, 100); + expect(result.files.map((f) => f.filename)).toEqual(['a.ts', 'c.ts']); + expect(result.truncationReason).toContain('100-line limit'); + expect(result.truncationReason).toContain('290 lines found'); + expect(result.truncationReason).toContain('1 file was dropped'); + }); + + it('keeps the first file and cuts its patch when it alone exceeds the budget', () => { + const patch = Array.from({ length: 50 }, (_, i) => `+l${String(i)}`).join('\n'); + const result = applyLineBudget([makeFile('big.ts', 50, patch), makeFile('b.ts', 5)], 10); + expect(result.files).toHaveLength(1); + expect(result.files[0]?.patch?.split('\n')).toHaveLength(10); + expect(result.truncationReason).toContain('first file was cut to fit'); + }); + + it('flags a lone oversized first file without a patch', () => { + const result = applyLineBudget([makeFile('big.ts', 50)], 10); + expect(result.files).toHaveLength(1); + expect(result.truncationReason).toContain('50 lines found'); + }); +}); + +describe('applyLineBudgetToDiff', () => { + const seg = (name: string, adds: number): string => + `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -0,0 +1 @@\n` + + Array.from({ length: adds }, (_, i) => `+x${String(i)}`).join('\n'); + + it('leaves a small diff untouched', () => { + const diff = seg('a.ts', 3); + expect(applyLineBudgetToDiff(diff, 100)).toEqual({ diff }); + }); + + it('drops a segment that does not fit and keeps later small ones', () => { + const diff = [seg('a.ts', 5), seg('big.ts', 50), seg('c.ts', 3)].join('\n'); + const result = applyLineBudgetToDiff(diff, 10); + expect(result.diff).toContain('a/a.ts'); + expect(result.diff).toContain('a/c.ts'); + expect(result.diff).not.toContain('big.ts'); + expect(result.truncationReason).toContain('1 file was dropped'); + }); +}); diff --git a/packages/core/src/pipelines/analyze.ts b/packages/core/src/pipelines/analyze.ts index f959d803..7ed72911 100644 --- a/packages/core/src/pipelines/analyze.ts +++ b/packages/core/src/pipelines/analyze.ts @@ -15,6 +15,7 @@ import { selectComponentWithAI, resolveAndCloneModel, findComponentsForRepo, + applyLineBudget, } from './pipeline-shared.js'; import { CONFIG } from '../utils/config.js'; import { loadSkipPatterns, applySkipPatterns } from '../utils/skip-patterns.js'; @@ -124,6 +125,19 @@ export async function runAnalyze( } } + // ── Line budget (after skip patterns so excluded files never use it) ── + const budget = applyLineBudget(prData.files); + if (budget.truncationReason) { + prData.files = budget.files; + prData.diff = buildDiffFromFiles(budget.files); + prData.changed_files = budget.files.length; + prData.wasTruncated = true; + prData.truncationReason = [prData.truncationReason, budget.truncationReason] + .filter(Boolean) + .join(' '); + p.warn(budget.truncationReason); + } + // ── Find components for this repository ────────────────────────────── const repoUrl = ref.repositoryUrl; const prMetadata = { diff --git a/packages/core/src/pipelines/check.ts b/packages/core/src/pipelines/check.ts index 3766d9b4..66ef3c51 100644 --- a/packages/core/src/pipelines/check.ts +++ b/packages/core/src/pipelines/check.ts @@ -26,6 +26,7 @@ import { selectComponentWithAI, resolveAndCloneModel, findComponentsForRepo, + applyLineBudgetToDiff, } from './pipeline-shared.js'; export interface CheckOptions { @@ -146,11 +147,20 @@ export async function runCheck( } // ── Filter diff to match included files ──────────────────────────── - const effectiveDiff = + let effectiveDiff = !options.skipFileFiltering && files.length > 0 ? filterDiffByFiles(options.diff, files) : options.diff; + // ── Line budget (after skip patterns so excluded files never use it) ── + const budget = applyLineBudgetToDiff(effectiveDiff); + if (budget.truncationReason) { + effectiveDiff = budget.diff; + const keptNames = new Set(parseFilesFromDiff(effectiveDiff).map((f) => f.filename)); + files = files.filter((f) => keptNames.has(f.filename)); + p.warn(budget.truncationReason); + } + // ── Stage 1: Component selection ───────────────────────────────────── let selectedComponent: ArchitecturalComponent = defaultComponent; let candidateComponents: { id: string; name: string; type: string }[] | undefined; diff --git a/packages/core/src/pipelines/pipeline-shared.ts b/packages/core/src/pipelines/pipeline-shared.ts index 1b47b4ae..42219236 100644 --- a/packages/core/src/pipelines/pipeline-shared.ts +++ b/packages/core/src/pipelines/pipeline-shared.ts @@ -12,6 +12,7 @@ import type { ProgressReporter } from './progress.js'; import { validatePath } from '../utils/validation.js'; import { buildStructuredOutput } from '../output.js'; import { CONFIG } from '../utils/config.js'; +import type { ChangeRequestFile } from '../platforms/source-platform.js'; import { ErodeError, ErrorCode } from '../errors.js'; import { resolveModelSource, type ResolvedModelSource } from '../utils/model-source.js'; @@ -208,3 +209,95 @@ export function findComponentsForRepo( type ComponentLookupResult = | { found: true; components: ArchitecturalComponent[]; defaultComponent: ArchitecturalComponent } | EmptyCheckResult; + +export interface LineBudgetResult { + files: ChangeRequestFile[]; + truncationReason?: string; +} + +/** + * Keep files in order until the line budget is used up. Runs after skip patterns so excluded + * files (lockfiles) never consume budget. A file that does not fit is skipped, not a stop + * signal, so smaller later files still fit. The first file is always kept, with its patch + * cut to the budget when it alone exceeds it. + */ +export function applyLineBudget( + files: ChangeRequestFile[], + maxLines: number = CONFIG.constraints.maxLinesPerDiff +): LineBudgetResult { + const totalLines = files.reduce((sum, f) => sum + f.changes, 0); + if (totalLines <= maxLines) return { files }; + + const kept: ChangeRequestFile[] = []; + let used = 0; + let patchTrimmed = false; + for (const file of files) { + if (kept.length === 0) { + if (file.changes > maxLines && file.patch !== undefined) { + kept.push({ ...file, patch: file.patch.split('\n').slice(0, maxLines).join('\n') }); + patchTrimmed = true; + } else { + kept.push(file); + } + used += file.changes; + continue; + } + if (used + file.changes > maxLines) continue; + kept.push(file); + used += file.changes; + } + + const dropped = files.length - kept.length; + const header = `Diff surpassed the ${String(maxLines)}-line limit (${String(totalLines)} lines found).`; + const detail = + dropped > 0 || patchTrimmed + ? `${String(dropped)} ${dropped === 1 ? 'file was' : 'files were'} dropped${patchTrimmed ? ' and the first file was cut to fit' : ''}.` + : 'Analysis may be partial.'; + return { files: kept, truncationReason: `${header} ${detail}` }; +} + +/** Count added and removed lines in one per-file diff segment (headers excluded). */ +function countChangedLines(segment: string): number { + let n = 0; + for (const line of segment.split('\n')) { + if (line.startsWith('+') && !line.startsWith('+++')) n++; + else if (line.startsWith('-') && !line.startsWith('---')) n++; + } + return n; +} + +/** Line budget for a local unified diff; same rules as {@link applyLineBudget}. */ +export function applyLineBudgetToDiff( + diff: string, + maxLines: number = CONFIG.constraints.maxLinesPerDiff +): { diff: string; truncationReason?: string } { + const marker = 'diff --git '; + const segments: string[] = []; + let current = ''; + for (const line of diff.split('\n')) { + if (line.startsWith(marker) && current) { + segments.push(current); + current = ''; + } + current += `${line}\n`; + } + if (current) segments.push(current); + + const asFiles: ChangeRequestFile[] = segments.map((seg, i) => { + const changes = countChangedLines(seg); + return { + filename: String(i), + status: 'modified', + additions: changes, + deletions: 0, + changes, + patch: seg.replace(/\n$/, ''), + }; + }); + const result = applyLineBudget(asFiles, maxLines); + if (result.truncationReason === undefined) return { diff }; + return { + diff: result.files.map((f) => f.patch ?? '').join('\n'), + truncationReason: result.truncationReason, + }; +} diff --git a/packages/core/src/platforms/__tests__/platform-utils.test.ts b/packages/core/src/platforms/__tests__/platform-utils.test.ts index f78ca692..91f2a24e 100644 --- a/packages/core/src/platforms/__tests__/platform-utils.test.ts +++ b/packages/core/src/platforms/__tests__/platform-utils.test.ts @@ -37,38 +37,13 @@ describe('applyDiffTruncation', () => { expect(result.truncationReason).toContain('60 files found'); }); - it('drops trailing files once the line budget is exceeded', () => { - const files = [makeFile('a.ts', 3000), makeFile('b.ts', 1500), makeFile('c.ts', 1000)]; - const result = applyDiffTruncation(files, 5500); + it('keeps all files but marks truncated when line count exceeds limit', () => { + const files = [makeFile('big.ts', 6000)]; + const result = applyDiffTruncation(files, 6000); expect(result.wasTruncated).toBe(true); - expect(result.files.map((f) => f.filename)).toEqual(['a.ts', 'b.ts']); - expect(result.truncationReason).toContain('5000-line limit'); - expect(result.truncationReason).toContain('5500 lines found'); - expect(result.truncationReason).toContain('1 file was dropped'); - }); - - it('always keeps the first file and cuts its patch to the budget', () => { - const patch = Array.from({ length: 6000 }, (_, i) => `+line${String(i)}`).join('\n'); - const files = [{ ...makeFile('big.ts', 6000), patch }, makeFile('b.ts', 10)]; - const result = applyDiffTruncation(files, 6010); expect(result.files).toHaveLength(1); - expect(result.files[0]?.patch?.split('\n')).toHaveLength(5000); - expect(result.truncationReason).toContain('1 file was dropped'); - }); - - it('keeps an oversized first file without a patch and still flags truncation', () => { - const result = applyDiffTruncation([makeFile('big.ts', 6000)], 6000); - expect(result.wasTruncated).toBe(true); + expect(result.truncationReason).toContain('5000-line limit'); expect(result.truncationReason).toContain('6000 lines found'); - expect(result.files).toHaveLength(1); - }); - - it('applies the line budget after the file-count limit', () => { - const files = Array.from({ length: 60 }, (_, i) => makeFile(`f${String(i)}.ts`, 200)); - const result = applyDiffTruncation(files, 12000); - expect(result.files).toHaveLength(25); - expect(result.truncationReason).toContain('50-file limit'); - expect(result.truncationReason).toContain('25 files were dropped'); }); }); diff --git a/packages/core/src/platforms/platform-utils.ts b/packages/core/src/platforms/platform-utils.ts index 50cdfc4b..5d612417 100644 --- a/packages/core/src/platforms/platform-utils.ts +++ b/packages/core/src/platforms/platform-utils.ts @@ -9,57 +9,27 @@ interface TruncationResult { truncationReason?: string; } -function applyLineBudget( - files: ChangeRequestFile[], - maxLines: number -): { files: ChangeRequestFile[]; dropped: number; patchTrimmed: boolean } { - const kept: ChangeRequestFile[] = []; - let used = 0; - let patchTrimmed = false; - for (const file of files) { - if (kept.length > 0 && used + file.changes > maxLines) break; - if (kept.length === 0 && file.changes > maxLines && file.patch !== undefined) { - // The first file always stays, but its patch is cut to the budget. - kept.push({ ...file, patch: file.patch.split('\n').slice(0, maxLines).join('\n') }); - patchTrimmed = true; - } else { - kept.push(file); - } - used += file.changes; - } - return { files: kept, dropped: files.length - kept.length, patchTrimmed }; -} - export function applyDiffTruncation( files: ChangeRequestFile[], totalLines: number ): TruncationResult { - const { maxFilesPerDiff, maxLinesPerDiff } = CONFIG.constraints; const totalFiles = files.length; - const reasons: string[] = []; - let kept = files; - if (totalFiles > maxFilesPerDiff) { - kept = files.slice(0, maxFilesPerDiff); - reasons.push( - `Diff surpassed the ${String(maxFilesPerDiff)}-file limit (${String(totalFiles)} files found). Only the first ${String(maxFilesPerDiff)} files were analyzed.` - ); + if (totalFiles > CONFIG.constraints.maxFilesPerDiff) { + return { + files: files.slice(0, CONFIG.constraints.maxFilesPerDiff), + wasTruncated: true, + truncationReason: `Diff surpassed the ${String(CONFIG.constraints.maxFilesPerDiff)}-file limit (${String(totalFiles)} files found). Only the first ${String(CONFIG.constraints.maxFilesPerDiff)} files were analyzed.`, + }; } - if (totalLines > maxLinesPerDiff) { - const budgeted = applyLineBudget(kept, maxLinesPerDiff); - kept = budgeted.files; - const header = `Diff surpassed the ${String(maxLinesPerDiff)}-line limit (${String(totalLines)} lines found).`; - if (budgeted.dropped > 0 || budgeted.patchTrimmed) { - reasons.push( - `${header} ${String(budgeted.dropped)} ${budgeted.dropped === 1 ? 'file was' : 'files were'} dropped${budgeted.patchTrimmed ? ' and the first file was cut to fit' : ''}.` - ); - } else { - reasons.push(`${header} Analysis may be partial.`); - } + if (totalLines > CONFIG.constraints.maxLinesPerDiff) { + return { + files, + wasTruncated: true, + truncationReason: `Diff surpassed the ${String(CONFIG.constraints.maxLinesPerDiff)}-line limit (${String(totalLines)} lines found). Analysis may be partial.`, + }; } - - if (reasons.length === 0) return { files, wasTruncated: false }; - return { files: kept, wasTruncated: true, truncationReason: reasons.join(' ') }; + return { files, wasTruncated: false }; } export function sanitizeErrorMessage(message: string): string { diff --git a/packages/core/src/providers/__tests__/generation-profile.test.ts b/packages/core/src/providers/__tests__/generation-profile.test.ts index d9700df3..a48fe7b3 100644 --- a/packages/core/src/providers/__tests__/generation-profile.test.ts +++ b/packages/core/src/providers/__tests__/generation-profile.test.ts @@ -7,13 +7,16 @@ import { } from '../generation-profile.js'; describe('getGenerationProfileForPhase', () => { - it('uses small low-effort generation for simple phases', () => { + it('uses small low-effort generation for component resolution', () => { expect(getGenerationProfileForPhase(AnalysisPhase.COMPONENT_RESOLUTION)).toEqual({ outputSize: 'small', reasoningEffort: 'low', }); + }); + + it('gives the dependency scan a medium output budget for its longer JSON', () => { expect(getGenerationProfileForPhase(AnalysisPhase.DEPENDENCY_SCAN)).toEqual({ - outputSize: 'small', + outputSize: 'medium', reasoningEffort: 'low', }); }); diff --git a/packages/core/src/providers/__tests__/match-component-id.test.ts b/packages/core/src/providers/__tests__/match-component-id.test.ts index 78e9c0c7..d77080b5 100644 --- a/packages/core/src/providers/__tests__/match-component-id.test.ts +++ b/packages/core/src/providers/__tests__/match-component-id.test.ts @@ -13,9 +13,14 @@ describe('matchComponentId', () => { expect(matchComponentId('"api"', ids)).toBe('api'); }); - it('finds a whole-token id inside prose and picks the longest', () => { + it('finds a whole-token id inside prose', () => { expect(matchComponentId('The component is api-gateway.', ids)).toBe('api-gateway'); - expect(matchComponentId('I think api, not system.web', ids)).toBe('system.web'); + expect(matchComponentId('I think system.web, not api', ids)).toBe('system.web'); + }); + + it('prefers the earliest match over a longer id mentioned later', () => { + expect(matchComponentId('api. api-gateway is not affected', ids)).toBe('api'); + expect(matchComponentId('api-gateway, not api', ids)).toBe('api-gateway'); }); it('does not match inside a longer token', () => { diff --git a/packages/core/src/providers/anthropic/__tests__/provider.test.ts b/packages/core/src/providers/anthropic/__tests__/provider.test.ts index d318ebc4..84b0fec3 100644 --- a/packages/core/src/providers/anthropic/__tests__/provider.test.ts +++ b/packages/core/src/providers/anthropic/__tests__/provider.test.ts @@ -120,7 +120,7 @@ describe('AnthropicProvider', () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: 'claude-haiku-4-5', - max_tokens: 1500, + max_tokens: 600, }) ); }); diff --git a/packages/core/src/providers/anthropic/provider.ts b/packages/core/src/providers/anthropic/provider.ts index 40519877..81b636a2 100644 --- a/packages/core/src/providers/anthropic/provider.ts +++ b/packages/core/src/providers/anthropic/provider.ts @@ -11,7 +11,7 @@ import { import { ANTHROPIC_MODELS } from './models.js'; const MAX_TOKENS_BY_OUTPUT_SIZE = { - small: 1500, + small: 600, medium: 1500, large: 8192, } satisfies Record; diff --git a/packages/core/src/providers/base-provider.ts b/packages/core/src/providers/base-provider.ts index 5c230860..2b9d6d07 100644 --- a/packages/core/src/providers/base-provider.ts +++ b/packages/core/src/providers/base-provider.ts @@ -38,24 +38,26 @@ export function matchComponentId(responseText: string, ids: string[]): string | .trim(); if (ids.includes(reply)) return reply; - let best: string | null = null; + // Earliest whole-token occurrence wins (the reply leads with its answer); the longest id + // breaks ties at the same position. + let best: { id: string; at: number } | null = null; for (const id of ids) { - if (id.length === 0 || (best !== null && id.length <= best.length)) continue; + if (id.length === 0) continue; let from = 0; for (;;) { const at = reply.indexOf(id, from); - if (at === -1) break; + if (at === -1 || (best !== null && at > best.at)) break; const after = reply[at + id.length]; // A trailing "." that ends a sentence is punctuation, not part of the id. const afterOk = !isIdChar(after) || (after === '.' && !isIdChar(reply[at + id.length + 1])); if (!isIdChar(reply[at - 1]) && afterOk) { - best = id; + if (best === null || at < best.at || id.length > best.id.length) best = { id, at }; break; } from = at + 1; } } - return best; + return best?.id ?? null; } function formatDuration(startedAt: bigint): string { diff --git a/packages/core/src/providers/gemini/__tests__/provider.test.ts b/packages/core/src/providers/gemini/__tests__/provider.test.ts index 95cbda14..02e16d3f 100644 --- a/packages/core/src/providers/gemini/__tests__/provider.test.ts +++ b/packages/core/src/providers/gemini/__tests__/provider.test.ts @@ -191,7 +191,7 @@ describe('GeminiProvider', () => { expect(mockGenerateContent).toHaveBeenCalledWith( expect.objectContaining({ model: 'gemini-3.5-flash-lite', - config: { maxOutputTokens: 1500, thinkingConfig: { thinkingLevel: 'LOW' } }, + config: { maxOutputTokens: 3000, thinkingConfig: { thinkingLevel: 'LOW' } }, }) ); }); diff --git a/packages/core/src/providers/generation-profile.ts b/packages/core/src/providers/generation-profile.ts index 8c521034..6200aa0e 100644 --- a/packages/core/src/providers/generation-profile.ts +++ b/packages/core/src/providers/generation-profile.ts @@ -14,8 +14,10 @@ export interface GenerationProfile { export function getGenerationProfileForPhase(phase: AnalysisPhase): GenerationProfile { switch (phase) { case AnalysisPhase.COMPONENT_RESOLUTION: - case AnalysisPhase.DEPENDENCY_SCAN: return { outputSize: 'small', reasoningEffort: 'low' }; + case AnalysisPhase.DEPENDENCY_SCAN: + // The dependency JSON can be long, so it gets more room than a component pick. + return { outputSize: 'medium', reasoningEffort: 'low' }; case AnalysisPhase.MODEL_UPDATE: return { outputSize: 'medium', reasoningEffort: 'medium' }; case AnalysisPhase.CHANGE_ANALYSIS: diff --git a/packages/core/src/providers/openai/__tests__/provider.test.ts b/packages/core/src/providers/openai/__tests__/provider.test.ts index cb617e06..1d10aa01 100644 --- a/packages/core/src/providers/openai/__tests__/provider.test.ts +++ b/packages/core/src/providers/openai/__tests__/provider.test.ts @@ -227,7 +227,7 @@ describe('OpenAIProvider', () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: 'gpt-5.6-luna', - max_output_tokens: 1500, + max_output_tokens: 6000, reasoning: { effort: 'low' }, }) ); diff --git a/packages/web/src/content/docs/docs/reference/configuration.md b/packages/web/src/content/docs/docs/reference/configuration.md index ff5fda7e..f4febe2f 100644 --- a/packages/web/src/content/docs/docs/reference/configuration.md +++ b/packages/web/src/content/docs/docs/reference/configuration.md @@ -67,6 +67,8 @@ Environment variable names map to nested JSON keys. For example: | `ERODE_LIKEC4_PATCH_STRATEGY` | How to patch LikeC4 models (`text` or `model-edits`) | `text` | | `ERODE_LIKEC4_PROJECT` | LikeC4 project to load when the workspace has several | — | +A path in `ERODE_LIKEC4_EXCLUDE_PATHS` excludes that element and its descendants by whole segment (`cloud.api` covers `cloud.api` and `cloud.api.*`, not `cloud.apigateway`). + `model-edits` is experimental. Erode lets LikeC4 decide where suggested elements and relationships go, instead of inserting text into the model block. The patched file contains plain DSL, so your project does not need a newer LikeC4 version. If LikeC4 rejects the change, reports overlaps with other diffs, needs to change more than one file, or the result fails validation, Erode falls back to `text`. Set `ERODE_VERBOSE=true` to log the reason. From 5780a2c802f9bec7053deb331023641fc7177fd3 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 19:00:08 +0100 Subject: [PATCH 10/10] fix(core): address review findings on line budget and relationship kinds - Dedup resolves a proposal's kind the same way the LikeC4 writer does, via a shared helper; an undefined kind counts as no kind - Report files dropped by the line budget on the analysis result, structured output (changeRequest.wasTruncated/truncationReason) and PR comment, for analyze and check - Count +/- lines as content after a hunk header, so removed ---- and added +++x lines count toward the budget --- packages/core/src/__tests__/output.test.ts | 20 +++++++++++++++++ packages/core/src/adapters/base-patcher.ts | 8 ++++++- .../deduplicate-relationships.test.ts | 19 ++++++++++++++-- packages/core/src/adapters/likec4/patcher.ts | 8 ++++--- .../core/src/adapters/relationship-kind.ts | 18 +++++++++++++++ packages/core/src/analysis/analysis-types.ts | 2 ++ packages/core/src/output.ts | 9 ++++++++ .../src/pipelines/__tests__/check.test.ts | 22 +++++++++++++++++++ .../pipelines/__tests__/line-budget.test.ts | 11 ++++++++++ packages/core/src/pipelines/analyze.ts | 3 +++ packages/core/src/pipelines/check.ts | 3 +++ .../core/src/pipelines/pipeline-shared.ts | 12 +++++++--- 12 files changed, 126 insertions(+), 9 deletions(-) create mode 100644 packages/core/src/adapters/relationship-kind.ts diff --git a/packages/core/src/__tests__/output.test.ts b/packages/core/src/__tests__/output.test.ts index 51a83192..bb9ff373 100644 --- a/packages/core/src/__tests__/output.test.ts +++ b/packages/core/src/__tests__/output.test.ts @@ -96,6 +96,18 @@ describe('buildStructuredOutput', () => { expect(result.metadata.component?.id).toBe('comp.api'); }); + it('should report truncation in change request metadata', () => { + const truncated = buildStructuredOutput( + makeAnalysisResult({ truncation: { reason: '2 files were dropped.' } }), + 'LikeC4' + ); + expect(truncated.metadata.changeRequest?.wasTruncated).toBe(true); + expect(truncated.metadata.changeRequest?.truncationReason).toBe('2 files were dropped.'); + + const clean = buildStructuredOutput(makeAnalysisResult(), 'LikeC4'); + expect(clean.metadata.changeRequest?.wasTruncated).toBeUndefined(); + }); + it('should include extras when provided', () => { const result = buildStructuredOutput(makeAnalysisResult(), 'LikeC4', { selectedComponentId: 'comp.api', @@ -155,6 +167,14 @@ describe('formatAnalysisAsComment', () => { expect(output).not.toContain('**Status**: violations'); }); + it('should note partial analysis when files were dropped', () => { + const output = formatAnalysisAsComment( + makeAnalysisResult({ truncation: { reason: '2 files were dropped.' } }) + ); + expect(output).toContain('Partial analysis: 2 files were dropped.'); + expect(formatAnalysisAsComment(makeAnalysisResult())).not.toContain('Partial analysis'); + }); + it('should show checkmark emoji when no violations', () => { const output = formatAnalysisAsComment(makeAnalysisResult()); diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index 5dbaffbc..732cdfe7 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -12,6 +12,7 @@ import type { ModelRelationship, ComponentIndex } from './architecture-types.js' import type { ValidationDiagnostic } from './architecture-adapter.js'; import type { AIProvider } from '../providers/ai-provider.js'; import { CONFIG } from '../utils/config.js'; +import { knownRelationshipKinds, resolveRelationshipKind } from './relationship-kind.js'; import { selectTargetFileByLocation, type TargetFileContext } from './target-file-selection.js'; interface AcceptedPatch { @@ -256,9 +257,14 @@ export abstract class BasePatcher implements ModelPatcher { ): StructuredRelationship[] { // A proposal is a duplicate of a same-endpoint relationship unless both carry a kind and // the kinds differ. Structurizr opts out: its `kind` is free-text technology. + const knownKinds = knownRelationshipKinds(existingRelationships); const kindsDiffer = (a?: string, b?: string): boolean => this.kindSensitiveDedup && a !== undefined && b !== undefined && a !== b; - return valid.filter((rel) => { + return valid.filter((proposed) => { + // A kind the writer would drop counts as no kind + const rel = this.kindSensitiveDedup + ? { ...proposed, kind: resolveRelationshipKind(proposed.kind, knownKinds) } + : proposed; const isDuplicate = existingRelationships.some( (existing) => (existing.source === rel.source && diff --git a/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts b/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts index 09187c03..d55c6ea4 100644 --- a/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/deduplicate-relationships.test.ts @@ -20,11 +20,23 @@ describe('deduplicateRelationships', () => { it('keeps a relationship when both have a kind and the kinds differ', () => { const { kept } = patcher.dedupe( [rel('async')], - [{ source: 'api', target: 'db', kind: 'sync' }] + [ + { source: 'api', target: 'db', kind: 'sync' }, + { source: 'web', target: 'api', kind: 'async' }, + ] ); expect(kept).toHaveLength(1); }); + it('treats a kind the model does not define as no kind, so it is a duplicate', () => { + const { kept, skipped } = patcher.dedupe( + [rel('grpc')], + [{ source: 'api', target: 'db', kind: 'sync' }] + ); + expect(kept).toHaveLength(0); + expect(skipped).toHaveLength(1); + }); + it('drops a relationship when the existing one has no kind', () => { const { kept } = patcher.dedupe([rel('async')], [{ source: 'api', target: 'db' }]); expect(kept).toHaveLength(0); @@ -33,7 +45,10 @@ describe('deduplicateRelationships', () => { it('applies the kind rule to bidirectional relationships too', () => { const reverse = { source: 'db', target: 'api', kind: 'async', description: 'x' }; const existing = { source: 'api', target: 'db', bidirectional: true }; - expect(patcher.dedupe([reverse], [{ ...existing, kind: 'sync' }]).kept).toHaveLength(1); + const asyncElsewhere = { source: 'web', target: 'api', kind: 'async' }; + expect( + patcher.dedupe([reverse], [{ ...existing, kind: 'sync' }, asyncElsewhere]).kept + ).toHaveLength(1); expect(patcher.dedupe([reverse], [existing]).kept).toHaveLength(0); }); diff --git a/packages/core/src/adapters/likec4/patcher.ts b/packages/core/src/adapters/likec4/patcher.ts index 06ef144d..3e63ca65 100644 --- a/packages/core/src/adapters/likec4/patcher.ts +++ b/packages/core/src/adapters/likec4/patcher.ts @@ -1,6 +1,7 @@ import { readFileSync, readdirSync, type Dirent } from 'fs'; import { join, resolve } from 'path'; import { BasePatcher, acceptedValidation, type PatchedFile } from '../base-patcher.js'; +import { knownRelationshipKinds, resolveRelationshipKind } from '../relationship-kind.js'; import { validateLikeC4Dsl } from './dsl-validator.js'; import { formatLikeC4Dsl } from './dsl-formatter.js'; import { componentBlock, escapeLikeC4String, previewModelEdits } from './model-edits.js'; @@ -55,12 +56,13 @@ export class LikeC4Patcher extends BasePatcher { unique: StructuredRelationship[], existing: ModelRelationship[] ): string[] { - const validKinds = new Set(existing.map((r) => r.kind).filter((k): k is string => Boolean(k))); + const validKinds = knownRelationshipKinds(existing); this.debugLog('Valid relationship kinds in model', [...validKinds]); return unique.map((rel) => { const desc = escapeLikeC4String(rel.description); - if (rel.kind && validKinds.has(rel.kind)) { - return ` ${rel.source} -[${rel.kind}]-> ${rel.target} '${desc}'`; + const kind = resolveRelationshipKind(rel.kind, validKinds); + if (kind) { + return ` ${rel.source} -[${kind}]-> ${rel.target} '${desc}'`; } return ` ${rel.source} -> ${rel.target} '${desc}'`; }); diff --git a/packages/core/src/adapters/relationship-kind.ts b/packages/core/src/adapters/relationship-kind.ts new file mode 100644 index 00000000..e28b3278 --- /dev/null +++ b/packages/core/src/adapters/relationship-kind.ts @@ -0,0 +1,18 @@ +import type { ModelRelationship } from './architecture-types.js'; + +/** Relationship kinds declared by the model's existing relationships. */ +export function knownRelationshipKinds(existing: readonly ModelRelationship[]): Set { + return new Set(existing.map((r) => r.kind).filter((k): k is string => Boolean(k))); +} + +/** + * The kind a proposed relationship is written with. A kind the model does not use is written + * as a plain relationship, so it resolves to undefined. Dedup and the writer both go through + * this so they agree on what ends up in the file. + */ +export function resolveRelationshipKind( + kind: string | undefined, + knownKinds: ReadonlySet +): string | undefined { + return kind && knownKinds.has(kind) ? kind : undefined; +} diff --git a/packages/core/src/analysis/analysis-types.ts b/packages/core/src/analysis/analysis-types.ts index e10f664f..f34d473f 100644 --- a/packages/core/src/analysis/analysis-types.ts +++ b/packages/core/src/analysis/analysis-types.ts @@ -104,6 +104,8 @@ export interface DriftAnalysisResult { component: ArchitecturalComponent; /** Aggregated dependency changes across all commits */ dependencyChanges: DependencyExtractionResult; + /** Set when files or lines were dropped before analysis, so the result may be partial */ + truncation?: { reason: string }; } /** * Input data for change request analysis prompt diff --git a/packages/core/src/output.ts b/packages/core/src/output.ts index e33d4584..5dd61157 100644 --- a/packages/core/src/output.ts +++ b/packages/core/src/output.ts @@ -55,6 +55,10 @@ export function buildStructuredOutput( head: result.metadata.head.ref, commits: result.metadata.stats.commits, filesChanged: result.metadata.stats.files_changed, + ...(result.truncation && { + wasTruncated: true, + truncationReason: result.truncation.reason, + }), }, component: { id: result.component.id, @@ -139,6 +143,11 @@ export function formatAnalysisAsComment( : ':white_check_mark: No drift found'; lines.push(`**Status**: ${status}`); + if (result.truncation) { + lines.push(''); + lines.push(`> :warning: Partial analysis: ${result.truncation.reason}`); + } + if (result.modelUpdates?.newComponents && result.modelUpdates.newComponents.length > 0) { lines.push(''); lines.push('### :new: New Components Detected'); diff --git a/packages/core/src/pipelines/__tests__/check.test.ts b/packages/core/src/pipelines/__tests__/check.test.ts index 635c02d1..4622dc3d 100644 --- a/packages/core/src/pipelines/__tests__/check.test.ts +++ b/packages/core/src/pipelines/__tests__/check.test.ts @@ -190,6 +190,28 @@ describe('runCheck', () => { expect(result.analysisResult.violations).toHaveLength(1); }); + it('reports files dropped by the line budget on the result', async () => { + const fileDiff = (name: string, adds: number): string => + `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -0,0 +1 @@\n` + + Array.from({ length: adds }, (_, i) => `+x${String(i)}`).join('\n'); + const result = await runCheck({ + ...baseOptions(), + skipFileFiltering: true, + diff: [fileDiff('a.ts', 3), fileDiff('huge.ts', 60000)].join('\n'), + files: [ + { filename: 'a.ts', status: 'modified' }, + { filename: 'huge.ts', status: 'modified' }, + ], + }); + + expect(result.analysisResult.truncation?.reason).toContain('1 file was dropped'); + }); + + it('reports no truncation when under budget', async () => { + const result = await runCheck(baseOptions()); + expect(result.analysisResult.truncation).toBeUndefined(); + }); + it('returns empty result when no components match', async () => { mockFindAllComponentsByRepository.mockReturnValue([]); diff --git a/packages/core/src/pipelines/__tests__/line-budget.test.ts b/packages/core/src/pipelines/__tests__/line-budget.test.ts index 8c661de3..310f4c5d 100644 --- a/packages/core/src/pipelines/__tests__/line-budget.test.ts +++ b/packages/core/src/pipelines/__tests__/line-budget.test.ts @@ -56,4 +56,15 @@ describe('applyLineBudgetToDiff', () => { expect(result.diff).not.toContain('big.ts'); expect(result.truncationReason).toContain('1 file was dropped'); }); + + it('counts removed ---- and added +++x lines as content inside a hunk', () => { + const diff = + 'diff --git a/a.md b/a.md\n--- a/a.md\n+++ b/a.md\n@@ -1,2 +1,2 @@\n-----\n+++x\n context\n' + + seg('b.ts', 5); + // a.md has 2 changed lines, b.ts 5; a budget of 5 must drop b.ts + const result = applyLineBudgetToDiff(diff, 5); + expect(result.truncationReason).toContain('7 lines found'); + expect(result.diff).toContain('a/a.md'); + expect(result.diff).not.toContain('b.ts'); + }); }); diff --git a/packages/core/src/pipelines/analyze.ts b/packages/core/src/pipelines/analyze.ts index 7ed72911..e0985a0b 100644 --- a/packages/core/src/pipelines/analyze.ts +++ b/packages/core/src/pipelines/analyze.ts @@ -240,6 +240,9 @@ export async function runAnalyze( // ── Stage 3: Drift analysis ────────────────────────────────────────── ctx.analysisResult = await runDriftStage(provider, promptData, p); + if (prData.wasTruncated && prData.truncationReason) { + ctx.analysisResult.truncation = { reason: prData.truncationReason }; + } // ── Build structured output ────────────────────────────────────────── p.section('Output'); diff --git a/packages/core/src/pipelines/check.ts b/packages/core/src/pipelines/check.ts index 66ef3c51..7c17925a 100644 --- a/packages/core/src/pipelines/check.ts +++ b/packages/core/src/pipelines/check.ts @@ -147,6 +147,7 @@ export async function runCheck( } // ── Filter diff to match included files ──────────────────────────── + let truncationReason: string | undefined; let effectiveDiff = !options.skipFileFiltering && files.length > 0 ? filterDiffByFiles(options.diff, files) @@ -158,6 +159,7 @@ export async function runCheck( effectiveDiff = budget.diff; const keptNames = new Set(parseFilesFromDiff(effectiveDiff).map((f) => f.filename)); files = files.filter((f) => keptNames.has(f.filename)); + truncationReason = budget.truncationReason; p.warn(budget.truncationReason); } @@ -227,6 +229,7 @@ export async function runCheck( // ── Stage 3: Drift Analysis ────────────────────────────────────────── const analysisResult = await runDriftStage(provider, promptData, p); + if (truncationReason) analysisResult.truncation = { reason: truncationReason }; // ── Build structured output ────────────────────────────────────────── const structured = buildStructuredOutput(analysisResult, adapter.metadata.displayName, { diff --git a/packages/core/src/pipelines/pipeline-shared.ts b/packages/core/src/pipelines/pipeline-shared.ts index 42219236..b5c42402 100644 --- a/packages/core/src/pipelines/pipeline-shared.ts +++ b/packages/core/src/pipelines/pipeline-shared.ts @@ -256,12 +256,18 @@ export function applyLineBudget( return { files: kept, truncationReason: `${header} ${detail}` }; } -/** Count added and removed lines in one per-file diff segment (headers excluded). */ +/** + * Count added and removed lines in one per-file diff segment. Only the file header (before the + * first hunk) is excluded; inside a hunk every +/- line is content, including `----` (a removed + * Markdown rule) and `+++x`. + */ function countChangedLines(segment: string): number { let n = 0; + let inHunk = false; for (const line of segment.split('\n')) { - if (line.startsWith('+') && !line.startsWith('+++')) n++; - else if (line.startsWith('-') && !line.startsWith('---')) n++; + if (line.startsWith('diff --git ')) inHunk = false; + else if (line.startsWith('@@')) inHunk = true; + else if (inHunk && (line.startsWith('+') || line.startsWith('-'))) n++; } return n; }