Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/core/src/__tests__/output.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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());

Expand Down
21 changes: 18 additions & 3 deletions packages/core/src/adapters/base-patcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -60,6 +61,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;

Expand Down Expand Up @@ -252,13 +255,25 @@ export abstract class BasePatcher implements ModelPatcher {
existingRelationships: ModelRelationship[],
skipped: PatchResult['skipped']
): StructuredRelationship[] {
return valid.filter((rel) => {
// 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((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 && existing.target === rel.target) ||
(existing.source === rel.source &&
existing.target === rel.target &&
!kindsDiffer(rel.kind, existing.kind)) ||
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
(existing.bidirectional === true &&
existing.source === rel.target &&
existing.target === rel.source)
existing.target === rel.source &&
!kindsDiffer(rel.kind, existing.kind))
);
if (isDuplicate) {
skipped.push({
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/adapters/likec4/__tests__/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,20 @@ 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 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();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
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 when both have a kind and the kinds differ', () => {
const { kept } = patcher.dedupe(
[rel('async')],
[
{ 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);
});

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 };
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);
});

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);
});
});
6 changes: 5 additions & 1 deletion packages/core/src/adapters/likec4/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ 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
.map((path) => path.trim().replace(/\.+$/, ''))
.some(
(path) => path !== '' && (componentId === path || componentId.startsWith(`${path}.`))
);
if (matchesPath) {
return true;
}
Expand Down
9 changes: 6 additions & 3 deletions packages/core/src/adapters/likec4/patcher.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -45,6 +46,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{');
Expand All @@ -54,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}'`;
});
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/adapters/relationship-kind.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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>
): string | undefined {
return kind && knownKinds.has(kind) ? kind : undefined;
}
Original file line number Diff line number Diff line change
@@ -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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof readdirSync>);
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<typeof readdirSync>);
mockReadFileSync.mockReturnValue(SAMPLE_DSL);
Expand Down
23 changes: 18 additions & 5 deletions packages/core/src/adapters/structurizr/patcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,23 @@ 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';
protected readonly defaultIndent = ' ';
protected readonly kindSensitiveDedup = false;

protected isModelBlockLine(line: string): boolean {
return /\bmodel\s*\{/.test(line);
Expand All @@ -20,17 +33,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}`;
});
}
Expand Down
Loading
Loading