From 76af07df5235137224f504f2d08b4d0fde40bdfa Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:12:39 +0100 Subject: [PATCH 1/5] fix(core): place dotted components and skip strings when text-patching models - Dotted new-component IDs now become `extend { = ... }` in the text path, sharing componentDefinition with the model-edits diff block. Before, `a.b.c = service` failed validation and dropped the whole patch. - Model blocks are found by a `model` keyword at line start followed by `{`, possibly on the next line, so `extend x.datamodel {` no longer counts. - New dsl-scanner masks '...', "...", '''...''', // and /* */ before brace matching, used by deterministicInsert, quickValidatePatch and findTargetFile. Replaces closingBraceOnSameLine. - quickValidatePatch checks multi-line entries line by line, and deterministicInsert re-indents them as a unit. --- .../adapters/__tests__/dsl-scanner.test.ts | 44 +++++++ packages/core/src/adapters/base-patcher.ts | 121 ++++++----------- packages/core/src/adapters/dsl-scanner.ts | 89 +++++++++++++ .../__tests__/patcher-dotted-e2e.test.ts | 107 +++++++++++++++ .../__tests__/patcher-robustness.test.ts | 124 ++++++++++++++++++ .../core/src/adapters/likec4/model-edits.ts | 24 ++-- packages/core/src/adapters/likec4/patcher.ts | 11 +- .../core/src/adapters/structurizr/patcher.ts | 4 - 8 files changed, 419 insertions(+), 105 deletions(-) create mode 100644 packages/core/src/adapters/__tests__/dsl-scanner.test.ts create mode 100644 packages/core/src/adapters/dsl-scanner.ts create mode 100644 packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts create mode 100644 packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts diff --git a/packages/core/src/adapters/__tests__/dsl-scanner.test.ts b/packages/core/src/adapters/__tests__/dsl-scanner.test.ts new file mode 100644 index 00000000..329db4be --- /dev/null +++ b/packages/core/src/adapters/__tests__/dsl-scanner.test.ts @@ -0,0 +1,44 @@ +import { describe, it, expect } from 'vitest'; +import { countBraces, findModelBlocks, maskStringsAndComments } from '../dsl-scanner.js'; + +describe('maskStringsAndComments', () => { + it('blanks strings and comments but keeps offsets and newlines', () => { + const text = "a 'x } y' // }\nb /* {\n} */ c"; + const masked = maskStringsAndComments(text); + expect(masked).toHaveLength(text.length); + expect(masked).toBe(`a${' '.repeat(13)}\nb${' '.repeat(5)}\n c`); + }); + + it('honours backslash escapes in quoted strings', () => { + expect(maskStringsAndComments("'it\\'s }' }")).toBe(' }'); + }); + + it('treats triple-quoted strings as one string across lines', () => { + expect(maskStringsAndComments("'''a } '\n}''' }")).toBe(`${' '.repeat(8)}\n }`); + expect(maskStringsAndComments('"""}""" {')).toBe(' {'); + }); +}); + +describe('findModelBlocks', () => { + it('ignores extend blocks whose name ends in model', () => { + const text = "model {\n extend shop.datamodel {\n x = service 'X'\n }\n}"; + expect(findModelBlocks(text)).toEqual([{ open: 6, close: text.length - 1 }]); + }); + + it('accepts tabs, extra spaces and a brace on the next line', () => { + expect(findModelBlocks('model\t{ }')).toHaveLength(1); + expect(findModelBlocks('model { }')).toHaveLength(1); + expect(findModelBlocks('model\n{\n}')).toEqual([{ open: 6, close: 8 }]); + }); + + it('skips model keywords inside strings and comments, and element names', () => { + expect(findModelBlocks("// model {\nx = '''\nmodel {\n'''")).toEqual([]); + expect(findModelBlocks("model = service 'M' {\n}")).toEqual([]); + }); +}); + +describe('countBraces', () => { + it('counts only structural braces', () => { + expect(countBraces("a { description '}' /* } */ // {\n}")).toEqual({ open: 1, close: 1 }); + }); +}); diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index 732cdfe7..dffa3b1b 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -14,6 +14,7 @@ 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'; +import { countBraces, findModelBlocks, maskStringsAndComments } from './dsl-scanner.js'; interface AcceptedPatch { content: string; @@ -32,31 +33,6 @@ export function acceptedValidation(dslResult: DslValidationResult): Omit 0 && --depth === 0) { - return i; - } - } - return -1; -} - export abstract class BasePatcher implements ModelPatcher { protected abstract readonly formatName: string; protected abstract readonly formatId: string; @@ -64,8 +40,6 @@ export abstract class BasePatcher implements ModelPatcher { /** Whether differing relationship kinds make a same-endpoint proposal distinct. */ protected abstract readonly kindSensitiveDedup: boolean; - protected abstract isModelBlockLine(line: string): boolean; - protected abstract generateDslLines( unique: StructuredRelationship[], existing: ModelRelationship[] @@ -381,65 +355,32 @@ export abstract class BasePatcher implements ModelPatcher { } protected deterministicInsert(content: string, lines: string[]): string { - const contentLines = content.split('\n'); - let insertIndex = -1; - - let inModel = false; - let braceDepth = 0; - for (let i = 0; i < contentLines.length; i++) { - const line = contentLines[i] ?? ''; - if (this.isModelBlockLine(line)) { - const closeAt = closingBraceOnSameLine(line); - if (closeAt !== -1) { - // One-line block such as `model { a = service 'A' }`: split it so lines can go inside - contentLines.splice(i, 1, line.slice(0, closeAt).trimEnd(), line.slice(closeAt)); - insertIndex = i + 1; - break; - } - inModel = true; - braceDepth = 1; - continue; - } - if (inModel) { - for (const ch of line) { - if (ch === '{') braceDepth++; - if (ch === '}') { - braceDepth--; - if (braceDepth === 0) { - insertIndex = i; - inModel = false; - break; - } - } - } - } - } - - // If no model block found, insert before the last } in the file - if (insertIndex === -1) { - for (let i = contentLines.length - 1; i >= 0; i--) { - if ((contentLines[i] ?? '').includes('}')) { - insertIndex = i; - break; - } - } + // Insert before the end of the last model block, else before the last `}` in the file + const closeAt = + findModelBlocks(content).at(-1)?.close ?? maskStringsAndComments(content).lastIndexOf('}'); + if (closeAt === -1) { + return content + '\n' + lines.join('\n') + '\n'; } - if (insertIndex === -1) { - // No closing brace found, just append - return content + '\n' + lines.join('\n') + '\n'; + const contentLines = content.split('\n'); + const lineStart = content.lastIndexOf('\n', closeAt - 1) + 1; + let insertIndex = content.slice(0, lineStart).split('\n').length - 1; + const closingLine = contentLines[insertIndex] ?? ''; + const column = closeAt - lineStart; + if (closingLine.slice(0, column).trim() !== '') { + // Code before the brace, as in `model { a = service 'A' }`: split so lines can go inside + contentLines.splice( + insertIndex, + 1, + closingLine.slice(0, column).trimEnd(), + closingLine.slice(column) + ); + insertIndex++; } const lineAbove = contentLines[insertIndex - 1] ?? ''; - const match = /^(\s*)/.exec(lineAbove); - const indent = match?.[1] ?? this.defaultIndent; - - const indentedLines = lines.map((line) => { - const trimmed = line.trimStart(); - return indent + trimmed; - }); - - contentLines.splice(insertIndex, 0, '', ...indentedLines); + const indent = /^(\s*)/.exec(lineAbove)?.[1] ?? this.defaultIndent; + contentLines.splice(insertIndex, 0, '', ...lines.flatMap((entry) => reindent(entry, indent))); return contentLines.join('\n'); } @@ -457,6 +398,15 @@ export abstract class BasePatcher implements ModelPatcher { } } +/** Re-indents a possibly multi-line entry to `indent`, keeping its inner nesting. */ +function reindent(entry: string, indent: string): string[] { + const lines = entry.split('\n'); + const common = Math.min( + ...lines.filter((l) => l.trim().length > 0).map((l) => /^\s*/.exec(l)?.[0].length ?? 0) + ); + return lines.map((l) => (l.trim().length > 0 ? indent + l.slice(common) : '')); +} + /** Quick structural validation shared by both patchers. */ export function quickValidatePatch( original: string, @@ -473,7 +423,11 @@ export function quickValidatePatch( } } - for (const line of insertedLines) { + // Multi-line entries are checked per line, since the LLM may re-indent nested blocks + const insertedSubLines = insertedLines.flatMap((entry) => + entry.split('\n').filter((l) => l.trim().length > 0) + ); + for (const line of insertedSubLines) { if (!patched.includes(line.trim())) { if (CONFIG.debug.verbose) { console.error('[quickValidatePatch] Failed: inserted line missing', JSON.stringify(line)); @@ -482,8 +436,7 @@ export function quickValidatePatch( } } - const openBraces = (patched.match(/\{/g) ?? []).length; - const closeBraces = (patched.match(/\}/g) ?? []).length; + const { open: openBraces, close: closeBraces } = countBraces(patched); if (openBraces !== closeBraces) { if (CONFIG.debug.verbose) { console.error( diff --git a/packages/core/src/adapters/dsl-scanner.ts b/packages/core/src/adapters/dsl-scanner.ts new file mode 100644 index 00000000..a3b32d26 --- /dev/null +++ b/packages/core/src/adapters/dsl-scanner.ts @@ -0,0 +1,89 @@ +/** + * Copy of `text` with the contents of strings and comments replaced by spaces. + * Newlines and offsets are kept, so positions found in the result apply to `text`. + * Handles '...' and "..." (backslash escapes, may span lines), '''...''' and """...""", + * `//` line comments and `/* *\/` block comments. + */ +export function maskStringsAndComments(text: string): string { + const out = text.split(''); + const blank = (from: number, to: number): void => { + for (let k = from; k < to && k < out.length; k++) { + if (out[k] !== '\n') out[k] = ' '; + } + }; + + let i = 0; + while (i < text.length) { + const ch = text[i]; + let end: number; + if (ch === "'" || ch === '"') { + const triple = ch.repeat(3); + if (text.startsWith(triple, i)) { + const close = text.indexOf(triple, i + 3); + end = close === -1 ? text.length : close + 3; + } else { + end = i + 1; + while (end < text.length && text[end] !== ch) { + end += text[end] === '\\' ? 2 : 1; + } + end = Math.min(end + 1, text.length); + } + } else if (ch === '/' && text[i + 1] === '/') { + const newline = text.indexOf('\n', i); + end = newline === -1 ? text.length : newline; + } else if (ch === '/' && text[i + 1] === '*') { + const close = text.indexOf('*/', i + 2); + end = close === -1 ? text.length : close + 2; + } else { + i++; + continue; + } + blank(i, end); + i = end; + } + return out.join(''); +} + +/** Offset of the `}` matching the `{` at `open` in masked text, or -1 if unbalanced. */ +function matchingBrace(masked: string, open: number): number { + let depth = 0; + for (let i = open; i < masked.length; i++) { + if (masked[i] === '{') depth++; + else if (masked[i] === '}' && --depth === 0) return i; + } + return -1; +} + +export interface BlockSpan { + /** Offset of the opening `{` */ + open: number; + /** Offset of the matching `}` */ + close: number; +} + +/** + * Balanced `model { ... }` blocks, in file order. The keyword must start a line and the + * `{` may follow on a later line, so `extend shop.datamodel {` is not a model block. + */ +export function findModelBlocks(text: string): BlockSpan[] { + const masked = maskStringsAndComments(text); + const blocks: BlockSpan[] = []; + for (const match of masked.matchAll(/^[ \t]*model\s*\{/gm)) { + const open = match.index + match[0].length - 1; + const close = matchingBrace(masked, open); + if (close !== -1) blocks.push({ open, close }); + } + return blocks; +} + +/** Counts `{` and `}` outside strings and comments. */ +export function countBraces(text: string): { open: number; close: number } { + const masked = maskStringsAndComments(text); + let open = 0; + let close = 0; + for (const ch of masked) { + if (ch === '{') open++; + else if (ch === '}') close++; + } + return { open, close }; +} diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts new file mode 100644 index 00000000..f67fc57f --- /dev/null +++ b/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts @@ -0,0 +1,107 @@ +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { LikeC4Adapter } from '../adapter.js'; +import { LikeC4Patcher } from '../patcher.js'; +import { withTempWorkspaceCopy } from '../../dsl-validation.js'; +import { CONFIG } from '../../../utils/config.js'; +import type { ModelPatchOptions, PatchResult } from '../../model-patcher.js'; +import type { ArchitectureModel } from '../../architecture-types.js'; +import type { AIProvider } from '../../../providers/ai-provider.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const workspace = path.join(__dirname, 'fixtures', 'multi-file-workspace'); + +// No patchModel, so text patching goes straight to the deterministic insert +const provider: AIProvider = { + extractDependencies: vi.fn(), + analyzeDrift: vi.fn(), +}; + +async function reload(result: PatchResult | null): Promise { + if (!result) throw new Error('expected a patch'); + return withTempWorkspaceCopy( + workspace, + result.absolutePath, + result.content, + 'erode-test', + async (_tmpTarget, tmpDir) => { + const adapter = new LikeC4Adapter(); + await adapter.loadFromPath(tmpDir); + return adapter; + } + ); +} + +describe('LikeC4Patcher text strategy with dotted new components (real validator)', () => { + const saved = { ...CONFIG.adapter.likec4 }; + let adapter: LikeC4Adapter; + let model: ArchitectureModel; + + beforeAll(async () => { + Object.assign(CONFIG.adapter.likec4, { + excludePaths: [], + excludeTags: [], + formatAfterPatch: false, + patchStrategy: 'text', + }); + adapter = new LikeC4Adapter(); + model = await adapter.loadFromPath(workspace); + }); + + afterAll(() => { + Object.assign(CONFIG.adapter.likec4, saved); + }); + + function options(overrides: Partial): ModelPatchOptions { + return { + modelPath: workspace, + relationships: [], + existingRelationships: adapter.getAllRelationships(), + componentIndex: model.componentIndex, + provider, + elementSourceFiles: adapter.getElementSourceFiles(), + ...overrides, + }; + } + + it('nests a new child under its parent and keeps the relationship', async () => { + const result = await new LikeC4Patcher().patch( + options({ + relationships: [{ source: 'core.payments', target: 'core.billing', description: 'pays' }], + newComponents: [{ id: 'core.payments', kind: 'service', name: 'Payments' }], + }) + ); + + expect(result?.absolutePath).toBe(path.join(workspace, 'systems', 'core.c4')); + expect(result?.validationSkipped).toBeUndefined(); + expect(result?.content).toContain('extend core {'); + expect(result?.content).not.toContain('core.payments = service'); + expect(result?.relationshipLines).toEqual([" core.payments -> core.billing 'pays'"]); + + const patched = await reload(result); + expect(patched.findComponentById('core.payments')?.name).toBe('Payments'); + expect(patched.getAllRelationships()).toContainEqual( + expect.objectContaining({ source: 'core.payments', target: 'core.billing' }) + ); + }, 60_000); + + it('handles a two-level parent', async () => { + const result = await new LikeC4Patcher().patch( + options({ + relationships: [ + { source: 'edge.gateway.cache', target: 'core.orders', description: 'warms' }, + ], + newComponents: [{ id: 'edge.gateway.cache', kind: 'service', name: 'Cache' }], + }) + ); + + expect(result?.validationSkipped).toBeUndefined(); + + const patched = await reload(result); + expect(patched.findComponentById('edge.gateway.cache')?.name).toBe('Cache'); + expect(patched.getAllRelationships()).toContainEqual( + expect.objectContaining({ source: 'edge.gateway.cache', target: 'core.orders' }) + ); + }, 60_000); +}); diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts new file mode 100644 index 00000000..fce275ce --- /dev/null +++ b/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts @@ -0,0 +1,124 @@ +import { describe, it, expect } from 'vitest'; +import { LikeC4Patcher } from '../patcher.js'; +import { quickValidatePatch } from '../../base-patcher.js'; +import type { NewComponent } from '../../../analysis/analysis-types.js'; + +class TestPatcher extends LikeC4Patcher { + public insert(content: string, lines: string[]): string { + return this.deterministicInsert(content, lines); + } + + public componentLines(components: NewComponent[]): string[] { + return this.generateComponentDslLines(components); + } +} + +const patcher = new TestPatcher(); + +describe('LikeC4Patcher dotted new components', () => { + it('wraps a dotted ID in an extend block of its parent', () => { + const [block] = patcher.componentLines([ + { id: 'cloud.backend.billing', kind: 'service', name: 'Billing', technology: 'Go' }, + ]); + expect(block).toBe( + [ + ' extend cloud.backend {', + " billing = service 'Billing' {", + " technology 'Go'", + ' }', + ' }', + ].join('\n') + ); + }); + + it('keeps top-level IDs as plain definitions', () => { + expect(patcher.componentLines([{ id: 'billing', kind: 'service', name: 'Billing' }])).toEqual([ + " billing = service 'Billing' {\n }", + ]); + }); + + it('re-indents multi-line blocks as a unit when inserting', () => { + const [block = ''] = patcher.componentLines([ + { id: 'shop.cache', kind: 'service', name: 'Cache' }, + ]); + const result = patcher.insert("model {\n shop = system 'Shop'\n}", [block]); + expect(result).toBe( + [ + 'model {', + " shop = system 'Shop'", + '', + ' extend shop {', + " cache = service 'Cache' {", + ' }', + ' }', + '}', + ].join('\n') + ); + }); + + it('quick-validates a re-indented multi-line block', () => { + const original = "model {\n shop = system 'Shop'\n}"; + const inserted = [" extend shop {\n cache = service 'Cache' {\n }\n }"]; + const patched = + "model {\n shop = system 'Shop'\n\n extend shop {\n cache = service 'Cache' {\n }\n }\n}"; + expect(quickValidatePatch(original, patched, inserted)).toBe(true); + }); +}); + +describe('LikeC4Patcher deterministic insert placement', () => { + it('does not treat extend x.datamodel as the model block', () => { + const content = [ + 'model {', + " shop = system 'Shop'", + ' extend shop.datamodel {', + " orders = component 'Orders'", + ' }', + '}', + ].join('\n'); + expect(patcher.insert(content, [' a -> b'])).toBe( + [...content.split('\n').slice(0, 5), '', ' a -> b', '}'].join('\n') + ); + }); + + it('finds a model keyword with the brace on the next line', () => { + const content = "specification {\n element service\n}\nmodel\n{\n a = service 'A'\n}"; + expect(patcher.insert(content, [' a -> a'])).toBe( + "specification {\n element service\n}\nmodel\n{\n a = service 'A'\n\n a -> a\n}" + ); + }); + + it('ignores a closing brace inside a description string', () => { + const content = [ + 'model {', + " a = service 'A' {", + " description 'closing } here'", + ' }', + '}', + ].join('\n'); + expect(patcher.insert(content, [' a -> a'])).toBe( + [...content.split('\n').slice(0, 4), '', ' a -> a', '}'].join('\n') + ); + }); + + it('ignores braces in block comments and triple-quoted strings', () => { + const content = [ + 'model {', + " a = service 'A' {", + ' /* } */', + " description '''", + ' }', + " '''", + ' }', + '}', + ].join('\n'); + expect(patcher.insert(content, [' a -> a'])).toBe( + [...content.split('\n').slice(0, 7), '', ' a -> a', '}'].join('\n') + ); + }); + + it('accepts a patch whose original has a brace in a string', () => { + const original = "model {\n a = service 'A } B'\n}"; + const patched = "model {\n a = service 'A } B'\n a -> a\n}"; + expect(quickValidatePatch(original, patched, [' a -> a'])).toBe(true); + }); +}); diff --git a/packages/core/src/adapters/likec4/model-edits.ts b/packages/core/src/adapters/likec4/model-edits.ts index 14fdf3f1..4a7c2f05 100644 --- a/packages/core/src/adapters/likec4/model-edits.ts +++ b/packages/core/src/adapters/likec4/model-edits.ts @@ -31,7 +31,7 @@ export function escapeLikeC4String(value: string): string { return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'"); } -export function componentBlock(comp: NewComponent, localId: string, indent: string): string[] { +function componentBlock(comp: NewComponent, localId: string, indent: string): string[] { const name = escapeLikeC4String(comp.name); const lines = [`${indent}${localId} = ${comp.kind} '${name}' {`]; if (comp.tags && comp.tags.length > 0) { @@ -48,9 +48,20 @@ export function componentBlock(comp: NewComponent, localId: string, indent: stri } /** - * Builds a LikeC4 `diff` block. Dotted component IDs become `extend { ... }`, + * Element definition for a new component. A dotted ID becomes `extend { = ... }`, * because a dotted name is not a valid element definition. */ +export function componentDefinition(comp: NewComponent, indent: string): string[] { + const dot = comp.id.lastIndexOf('.'); + if (dot === -1) return componentBlock(comp, comp.id, indent); + return [ + `${indent}extend ${comp.id.slice(0, dot)} {`, + ...componentBlock(comp, comp.id.slice(dot + 1), `${indent} `), + `${indent}}`, + ]; +} + +/** Builds a LikeC4 `diff` block with the new components and relationship lines. */ export function buildDiffBlock( diffId: string, components: NewComponent[], @@ -58,14 +69,7 @@ export function buildDiffBlock( ): string { const body: string[] = []; for (const comp of components) { - const dot = comp.id.lastIndexOf('.'); - if (dot === -1) { - body.push(...componentBlock(comp, comp.id, ' ')); - continue; - } - body.push(` extend ${comp.id.slice(0, dot)} {`); - body.push(...componentBlock(comp, comp.id.slice(dot + 1), ' ')); - body.push(' }'); + body.push(...componentDefinition(comp, ' ')); } for (const line of relationshipLines) { body.push(` ${line.trim()}`); diff --git a/packages/core/src/adapters/likec4/patcher.ts b/packages/core/src/adapters/likec4/patcher.ts index 3e63ca65..b6efd6a9 100644 --- a/packages/core/src/adapters/likec4/patcher.ts +++ b/packages/core/src/adapters/likec4/patcher.ts @@ -4,7 +4,8 @@ import { BasePatcher, acceptedValidation, type PatchedFile } from '../base-patch 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'; +import { componentDefinition, escapeLikeC4String, previewModelEdits } from './model-edits.js'; +import { findModelBlocks } from '../dsl-scanner.js'; import type { StructuredRelationship, NewComponent } from '../../analysis/analysis-types.js'; import type { ModelRelationship } from '../architecture-types.js'; import type { DslValidationResult } from '../model-patcher.js'; @@ -48,10 +49,6 @@ export class LikeC4Patcher extends BasePatcher { protected readonly defaultIndent = ' '; protected readonly kindSensitiveDedup = true; - protected isModelBlockLine(line: string): boolean { - return line.includes('model {') || line.includes('model{'); - } - protected generateDslLines( unique: StructuredRelationship[], existing: ModelRelationship[] @@ -69,7 +66,7 @@ export class LikeC4Patcher extends BasePatcher { } protected generateComponentDslLines(components: NewComponent[]): string[] { - return components.map((comp) => componentBlock(comp, comp.id, ' ').join('\n')); + return components.map((comp) => componentDefinition(comp, ' ').join('\n')); } protected findTargetFile(modelPath: string): string | null { @@ -84,7 +81,7 @@ export class LikeC4Patcher extends BasePatcher { } catch { continue; // dangling symlink or unreadable file } - if (!content.includes('model {')) continue; + if (findModelBlocks(content).length === 0) continue; if (content.includes('->')) return file; withModel ??= file; } diff --git a/packages/core/src/adapters/structurizr/patcher.ts b/packages/core/src/adapters/structurizr/patcher.ts index 73c13554..96145abc 100644 --- a/packages/core/src/adapters/structurizr/patcher.ts +++ b/packages/core/src/adapters/structurizr/patcher.ts @@ -24,10 +24,6 @@ export class StructurizrPatcher extends BasePatcher { protected readonly defaultIndent = ' '; protected readonly kindSensitiveDedup = false; - protected isModelBlockLine(line: string): boolean { - return /\bmodel\s*\{/.test(line); - } - protected generateDslLines( unique: StructuredRelationship[], _existing: ModelRelationship[] From ef1aad90f086e4bb6d2894950fb7a6f06d95fa82 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:12:44 +0100 Subject: [PATCH 2/5] feat(core): make model-edits the default LikeC4 patch strategy `adapter.likec4.patchStrategy` now defaults to `model-edits`; `text` stays selectable and is still the fallback whenever model edits return no patch. Tests about text patching pin `text` explicitly. Regenerates both config schemas, updates the configuration reference and amends ADR-012. --- packages/core/schemas/eroderc.schema.json | 2 +- .../__tests__/multi-file-workspace.test.ts | 1 + .../__tests__/patcher-bidirectional.test.ts | 2 + .../__tests__/patcher-dotted-e2e.test.ts | 43 ++++++++++++++++++- .../likec4/__tests__/patcher-escaping.test.ts | 1 + .../likec4/__tests__/patcher-format.test.ts | 2 + .../__tests__/patcher-model-edits.test.ts | 2 +- .../adapters/likec4/__tests__/patcher.test.ts | 2 + packages/core/src/utils/config.ts | 2 +- .../web/public/schemas/v0/eroderc.schema.json | 2 +- .../012-likec4-model-edits-via-diff-blocks.md | 4 ++ .../docs/docs/reference/configuration.md | 28 ++++++------ 12 files changed, 72 insertions(+), 19 deletions(-) diff --git a/packages/core/schemas/eroderc.schema.json b/packages/core/schemas/eroderc.schema.json index 29b699a9..218563b8 100644 --- a/packages/core/schemas/eroderc.schema.json +++ b/packages/core/schemas/eroderc.schema.json @@ -86,7 +86,7 @@ "type": "boolean" }, "patchStrategy": { - "default": "text", + "default": "model-edits", "type": "string", "enum": [ "text", diff --git a/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts b/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts index e0cf3e99..2cef6079 100644 --- a/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts @@ -25,6 +25,7 @@ describe('LikeC4 multi-file workspace', () => { CONFIG.adapter.likec4.excludePaths = []; CONFIG.adapter.likec4.excludeTags = []; CONFIG.adapter.likec4.formatAfterPatch = false; + CONFIG.adapter.likec4.patchStrategy = 'text'; adapter = new LikeC4Adapter(); model = await adapter.loadFromPath(workspace); diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-bidirectional.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-bidirectional.test.ts index 7daf87ba..7f271142 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher-bidirectional.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher-bidirectional.test.ts @@ -7,6 +7,7 @@ import type { ArchitecturalComponent, } from '../../architecture-types.js'; import type { AIProvider } from '../../../providers/ai-provider.js'; +import { CONFIG } from '../../../utils/config.js'; // Mock fs and child_process vi.mock('fs', async (importOriginal) => ({ @@ -75,6 +76,7 @@ describe('LikeC4Patcher bidirectional relationships', () => { beforeEach(() => { vi.clearAllMocks(); + CONFIG.adapter.likec4.patchStrategy = 'text'; patcher = new LikeC4Patcher(); mockValidateLikeC4Dsl.mockResolvedValue({ valid: true }); }); diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts index f67fc57f..33025c02 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher-dotted-e2e.test.ts @@ -1,10 +1,11 @@ -import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest'; import path from 'path'; import { fileURLToPath } from 'url'; import { LikeC4Adapter } from '../adapter.js'; import { LikeC4Patcher } from '../patcher.js'; +import * as modelEdits from '../model-edits.js'; import { withTempWorkspaceCopy } from '../../dsl-validation.js'; -import { CONFIG } from '../../../utils/config.js'; +import { CONFIG, ConfigSchema } from '../../../utils/config.js'; import type { ModelPatchOptions, PatchResult } from '../../model-patcher.js'; import type { ArchitectureModel } from '../../architecture-types.js'; import type { AIProvider } from '../../../providers/ai-provider.js'; @@ -105,3 +106,41 @@ describe('LikeC4Patcher text strategy with dotted new components (real validator ); }, 60_000); }); + +describe('LikeC4 patch strategy default', () => { + const saved = { ...CONFIG.adapter.likec4 }; + + afterEach(() => { + Object.assign(CONFIG.adapter.likec4, saved); + vi.restoreAllMocks(); + }); + + it('defaults to model-edits', () => { + expect(ConfigSchema.shape.adapter.shape.likec4.shape.patchStrategy.parse(undefined)).toBe( + 'model-edits' + ); + }); + + it('tries model edits first and falls back to text when they return nothing', async () => { + CONFIG.adapter.likec4.patchStrategy = + ConfigSchema.shape.adapter.shape.likec4.shape.patchStrategy.parse(undefined); + CONFIG.adapter.likec4.formatAfterPatch = false; + const spy = vi + .spyOn(modelEdits, 'previewModelEdits') + .mockResolvedValue({ ok: false, reason: 'unavailable' }); + const adapter = new LikeC4Adapter(); + const model = await adapter.loadFromPath(workspace); + + const result = await new LikeC4Patcher().patch({ + modelPath: workspace, + relationships: [{ source: 'edge.gateway', target: 'core.billing', description: 'bills' }], + existingRelationships: adapter.getAllRelationships(), + componentIndex: model.componentIndex, + provider, + elementSourceFiles: adapter.getElementSourceFiles(), + }); + + expect(spy).toHaveBeenCalledOnce(); + expect(result?.content).toContain("edge.gateway -> core.billing 'bills'"); + }, 60_000); +}); diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-escaping.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-escaping.test.ts index 54cba1f7..99ac8a19 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher-escaping.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher-escaping.test.ts @@ -27,6 +27,7 @@ describe('LikeC4Patcher escaping against the LikeC4 parser', () => { beforeAll(async () => { const configModule = await import('../../../utils/config.js'); configModule.CONFIG.adapter.likec4.formatAfterPatch = false; + configModule.CONFIG.adapter.likec4.patchStrategy = 'text'; }); it('produces DSL that LikeC4 parses when strings contain quotes and backslashes', async () => { diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-format.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-format.test.ts index ca3438bf..73a4901c 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher-format.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher-format.test.ts @@ -3,6 +3,7 @@ import { LikeC4Patcher } from '../patcher.js'; import type { StructuredRelationship } from '../../../analysis/analysis-types.js'; import type { ComponentIndex, ArchitecturalComponent } from '../../architecture-types.js'; import type { AIProvider } from '../../../providers/ai-provider.js'; +import { CONFIG } from '../../../utils/config.js'; vi.mock('fs', async (importOriginal) => ({ ...(await importOriginal()), @@ -71,6 +72,7 @@ describe('LikeC4Patcher post-format', () => { beforeEach(() => { vi.clearAllMocks(); + CONFIG.adapter.likec4.patchStrategy = 'text'; patcher = new LikeC4Patcher(); mockValidateLikeC4Dsl.mockResolvedValue({ valid: true }); }); diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-model-edits.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-model-edits.test.ts index 9c2e666e..635db53d 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher-model-edits.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher-model-edits.test.ts @@ -107,7 +107,7 @@ describe('LikeC4Patcher with patchStrategy model-edits', () => { expect(result?.content).toContain("frontend -> database 'reads'"); }, 60_000); - it('does not call model edits with the default text strategy', async () => { + it('does not call model edits with the text strategy', async () => { CONFIG.adapter.likec4.patchStrategy = 'text'; const spy = vi.spyOn(modelEdits, 'previewModelEdits'); const result = await new LikeC4Patcher().patch({ diff --git a/packages/core/src/adapters/likec4/__tests__/patcher.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher.test.ts index a3bdb047..7543df48 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher.test.ts @@ -7,6 +7,7 @@ import type { ArchitecturalComponent, } from '../../architecture-types.js'; import type { AIProvider } from '../../../providers/ai-provider.js'; +import { CONFIG } from '../../../utils/config.js'; // Mock fs and child_process vi.mock('fs', async (importOriginal) => ({ @@ -75,6 +76,7 @@ describe('LikeC4Patcher', () => { beforeEach(() => { vi.clearAllMocks(); + CONFIG.adapter.likec4.patchStrategy = 'text'; patcher = new LikeC4Patcher(); mockValidateLikeC4Dsl.mockResolvedValue({ valid: true }); }); diff --git a/packages/core/src/utils/config.ts b/packages/core/src/utils/config.ts index edc1e6bd..30f241f1 100644 --- a/packages/core/src/utils/config.ts +++ b/packages/core/src/utils/config.ts @@ -29,7 +29,7 @@ export const ConfigSchema = z.object({ excludePaths: z.array(z.string()).default([]), excludeTags: z.array(z.string()).default([]), formatAfterPatch: z.boolean().default(true), - patchStrategy: z.enum(['text', 'model-edits']).default('text'), + patchStrategy: z.enum(['text', 'model-edits']).default('model-edits'), project: z.string().optional(), }), structurizr: z.object({ diff --git a/packages/web/public/schemas/v0/eroderc.schema.json b/packages/web/public/schemas/v0/eroderc.schema.json index 29b699a9..218563b8 100644 --- a/packages/web/public/schemas/v0/eroderc.schema.json +++ b/packages/web/public/schemas/v0/eroderc.schema.json @@ -86,7 +86,7 @@ "type": "boolean" }, "patchStrategy": { - "default": "text", + "default": "model-edits", "type": "string", "enum": [ "text", diff --git a/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md b/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md index 48ced8a7..5067c1cd 100644 --- a/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md +++ b/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md @@ -62,6 +62,10 @@ Alternatives considered: - **Spike scope.** Preview runs without a `projectId`, so multi-project workspaces likely fall back. `excludePaths` is not applied to the temp copy. `insertedLines` for new components still holds the text-strategy lines, which can differ from the nested DSL in the patch. - **API stability.** `modelEdits` and `modelDiffs` are new in 1.61. The preview result is validated with a Zod schema so a shape change falls back instead of producing a broken patch. +## Amendments + +- **2026-11-17:** `model-edits` is now the default `patchStrategy`; `text` stays selectable and remains the fallback whenever model edits return no patch. The text path relies on line heuristics that failed on real models: it wrote dotted IDs such as `a.b.c = service` (invalid DSL, so the relationships in the same patch were dropped too), took `extend x.datamodel {` for the `model` block, and counted braces inside strings and comments. Model edits let LikeC4 place the change instead. The text path was fixed as well: dotted IDs become `extend { = ... }`, sharing the helper that builds the diff block, so the `insertedLines` risk above no longer applies to nesting; and a shared scanner skips strings (`'...'`, `"..."`, `'''...'''`) and comments when finding the `model` block and its closing brace. + ## Related commits - `build(deps): bump likec4 from 1.59.3 to 1.61.0` diff --git a/packages/web/src/content/docs/docs/reference/configuration.md b/packages/web/src/content/docs/docs/reference/configuration.md index f4febe2f..1b701ba0 100644 --- a/packages/web/src/content/docs/docs/reference/configuration.md +++ b/packages/web/src/content/docs/docs/reference/configuration.md @@ -54,25 +54,27 @@ Environment variable names map to nested JSON keys. For example: ## Architecture model -| Variable | Description | Default | -| --------------------------------- | ------------------------------------------------------- | -------- | -| `ERODE_MODEL_FORMAT` | Architecture model format (`likec4` or `structurizr`) | `likec4` | -| `ERODE_MODEL_PATH` | Path to the architecture model directory | — | -| `ERODE_MODEL_REPO` | Repository URL or owner/repo containing the model | — | -| `ERODE_MODEL_REF` | Branch or tag to clone from the model repository | `main` | -| `ERODE_STRUCTURIZR_CLI_PATH` | Path to the Structurizr CLI WAR file (for `.dsl` files) | — | -| `ERODE_LIKEC4_EXCLUDE_PATHS` | Comma-separated paths to exclude from model loading | — | -| `ERODE_LIKEC4_EXCLUDE_TAGS` | Comma-separated tags to exclude from model loading | — | -| `ERODE_LIKEC4_FORMAT_AFTER_PATCH` | Format LikeC4 models after applying generated patches | `true` | -| `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 | — | +| Variable | Description | Default | +| --------------------------------- | ------------------------------------------------------- | ------------- | +| `ERODE_MODEL_FORMAT` | Architecture model format (`likec4` or `structurizr`) | `likec4` | +| `ERODE_MODEL_PATH` | Path to the architecture model directory | — | +| `ERODE_MODEL_REPO` | Repository URL or owner/repo containing the model | — | +| `ERODE_MODEL_REF` | Branch or tag to clone from the model repository | `main` | +| `ERODE_STRUCTURIZR_CLI_PATH` | Path to the Structurizr CLI WAR file (for `.dsl` files) | — | +| `ERODE_LIKEC4_EXCLUDE_PATHS` | Comma-separated paths to exclude from model loading | — | +| `ERODE_LIKEC4_EXCLUDE_TAGS` | Comma-separated tags to exclude from model loading | — | +| `ERODE_LIKEC4_FORMAT_AFTER_PATCH` | Format LikeC4 models after applying generated patches | `true` | +| `ERODE_LIKEC4_PATCH_STRATEGY` | How to patch LikeC4 models (`text` or `model-edits`) | `model-edits` | +| `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. +With `model-edits`, Erode lets LikeC4 decide where suggested elements and relationships go. A new element such as `shop.cache` lands inside its parent's definition. 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. +`text` inserts the lines at the end of the `model` block, using `extend { ... }` for nested elements. Set it to skip model edits. + See [ADR-012](/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks/). ## Diff limits From a82f3b55ecad8b0b4b862d30411e338c2de64d9b Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 15:16:48 +0100 Subject: [PATCH 3/5] fix(core): scan Structurizr models with double quotes and # comments Structurizr strings use double quotes only and lines starting with # are comments, so an apostrophe such as "# Bob's workspace" no longer masks the model block. quickValidatePatch takes the format's scan options as an optional fourth argument. ADR-012 amendment now notes that text-path insertedLines can still differ from LikeC4's placement under model-edits. --- .../adapters/__tests__/dsl-scanner.test.ts | 14 ++++++++ packages/core/src/adapters/base-patcher.ts | 18 +++++++--- packages/core/src/adapters/dsl-scanner.ts | 35 ++++++++++++------ .../__tests__/deterministic-insert.test.ts | 36 +++++++++++++++++++ .../core/src/adapters/structurizr/patcher.ts | 2 ++ .../012-likec4-model-edits-via-diff-blocks.md | 2 +- 6 files changed, 90 insertions(+), 17 deletions(-) create mode 100644 packages/core/src/adapters/structurizr/__tests__/deterministic-insert.test.ts diff --git a/packages/core/src/adapters/__tests__/dsl-scanner.test.ts b/packages/core/src/adapters/__tests__/dsl-scanner.test.ts index 329db4be..3d9fed50 100644 --- a/packages/core/src/adapters/__tests__/dsl-scanner.test.ts +++ b/packages/core/src/adapters/__tests__/dsl-scanner.test.ts @@ -19,6 +19,20 @@ describe('maskStringsAndComments', () => { }); }); +describe('maskStringsAndComments with Structurizr options', () => { + const options = { quotes: ['"'], hashComments: true }; + + it('treats # at line start as a comment and apostrophes as plain text', () => { + expect(maskStringsAndComments(" # it's {\nx = \"}\" '{'", options)).toBe( + `${' '.repeat(10)}\nx = '{'` + ); + }); + + it('keeps # inside a line, such as a colour', () => { + expect(maskStringsAndComments('background #ff0000 }', options)).toBe('background #ff0000 }'); + }); +}); + describe('findModelBlocks', () => { it('ignores extend blocks whose name ends in model', () => { const text = "model {\n extend shop.datamodel {\n x = service 'X'\n }\n}"; diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index dffa3b1b..3b4ac67c 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -14,7 +14,12 @@ 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'; -import { countBraces, findModelBlocks, maskStringsAndComments } from './dsl-scanner.js'; +import { + countBraces, + findModelBlocks, + maskStringsAndComments, + type ScanOptions, +} from './dsl-scanner.js'; interface AcceptedPatch { content: string; @@ -39,6 +44,7 @@ export abstract class BasePatcher implements ModelPatcher { protected abstract readonly defaultIndent: string; /** Whether differing relationship kinds make a same-endpoint proposal distinct. */ protected abstract readonly kindSensitiveDedup: boolean; + protected readonly scanOptions: ScanOptions = {}; protected abstract generateDslLines( unique: StructuredRelationship[], @@ -312,7 +318,7 @@ export abstract class BasePatcher implements ModelPatcher { try { this.debugLog('Attempting LLM-based patching'); const result = await provider.patchModel(originalContent, insertedLines, this.formatId); - if (quickValidatePatch(originalContent, result, insertedLines)) { + if (quickValidatePatch(originalContent, result, insertedLines, this.scanOptions)) { const dslResult = await this.validateDsl(modelPath, targetFile, result, baseline); if (dslResult.valid || dslResult.skipped) { this.debugLog('LLM patch accepted', { @@ -357,7 +363,8 @@ export abstract class BasePatcher implements ModelPatcher { protected deterministicInsert(content: string, lines: string[]): string { // Insert before the end of the last model block, else before the last `}` in the file const closeAt = - findModelBlocks(content).at(-1)?.close ?? maskStringsAndComments(content).lastIndexOf('}'); + findModelBlocks(content, this.scanOptions).at(-1)?.close ?? + maskStringsAndComments(content, this.scanOptions).lastIndexOf('}'); if (closeAt === -1) { return content + '\n' + lines.join('\n') + '\n'; } @@ -411,7 +418,8 @@ function reindent(entry: string, indent: string): string[] { export function quickValidatePatch( original: string, patched: string, - insertedLines: string[] + insertedLines: string[], + scanOptions?: ScanOptions ): boolean { const originalLines = original.split('\n').filter((l) => l.trim().length > 0); for (const line of originalLines) { @@ -436,7 +444,7 @@ export function quickValidatePatch( } } - const { open: openBraces, close: closeBraces } = countBraces(patched); + const { open: openBraces, close: closeBraces } = countBraces(patched, scanOptions); if (openBraces !== closeBraces) { if (CONFIG.debug.verbose) { console.error( diff --git a/packages/core/src/adapters/dsl-scanner.ts b/packages/core/src/adapters/dsl-scanner.ts index a3b32d26..9a5f9c7d 100644 --- a/packages/core/src/adapters/dsl-scanner.ts +++ b/packages/core/src/adapters/dsl-scanner.ts @@ -1,22 +1,36 @@ +export interface ScanOptions { + /** Characters that open a string; default `'` and `"` */ + quotes?: readonly string[]; + /** Treat a line whose first non-blank character is `#` as a comment (Structurizr) */ + hashComments?: boolean; +} + /** * Copy of `text` with the contents of strings and comments replaced by spaces. * Newlines and offsets are kept, so positions found in the result apply to `text`. - * Handles '...' and "..." (backslash escapes, may span lines), '''...''' and """...""", + * Handles quoted strings (backslash escapes, may span lines), triple-quoted strings, * `//` line comments and `/* *\/` block comments. */ -export function maskStringsAndComments(text: string): string { +export function maskStringsAndComments(text: string, options: ScanOptions = {}): string { + const quotes = options.quotes ?? ["'", '"']; const out = text.split(''); const blank = (from: number, to: number): void => { for (let k = from; k < to && k < out.length; k++) { if (out[k] !== '\n') out[k] = ' '; } }; + const atHashComment = (at: number): boolean => + !!options.hashComments && text.slice(text.lastIndexOf('\n', at - 1) + 1, at).trim() === ''; + const lineEnd = (from: number): number => { + const newline = text.indexOf('\n', from); + return newline === -1 ? text.length : newline; + }; let i = 0; while (i < text.length) { - const ch = text[i]; + const ch = text.charAt(i); let end: number; - if (ch === "'" || ch === '"') { + if (quotes.includes(ch)) { const triple = ch.repeat(3); if (text.startsWith(triple, i)) { const close = text.indexOf(triple, i + 3); @@ -28,9 +42,8 @@ export function maskStringsAndComments(text: string): string { } end = Math.min(end + 1, text.length); } - } else if (ch === '/' && text[i + 1] === '/') { - const newline = text.indexOf('\n', i); - end = newline === -1 ? text.length : newline; + } else if ((ch === '/' && text[i + 1] === '/') || (ch === '#' && atHashComment(i))) { + end = lineEnd(i); } else if (ch === '/' && text[i + 1] === '*') { const close = text.indexOf('*/', i + 2); end = close === -1 ? text.length : close + 2; @@ -65,8 +78,8 @@ export interface BlockSpan { * Balanced `model { ... }` blocks, in file order. The keyword must start a line and the * `{` may follow on a later line, so `extend shop.datamodel {` is not a model block. */ -export function findModelBlocks(text: string): BlockSpan[] { - const masked = maskStringsAndComments(text); +export function findModelBlocks(text: string, options?: ScanOptions): BlockSpan[] { + const masked = maskStringsAndComments(text, options); const blocks: BlockSpan[] = []; for (const match of masked.matchAll(/^[ \t]*model\s*\{/gm)) { const open = match.index + match[0].length - 1; @@ -77,8 +90,8 @@ export function findModelBlocks(text: string): BlockSpan[] { } /** Counts `{` and `}` outside strings and comments. */ -export function countBraces(text: string): { open: number; close: number } { - const masked = maskStringsAndComments(text); +export function countBraces(text: string, options?: ScanOptions): { open: number; close: number } { + const masked = maskStringsAndComments(text, options); let open = 0; let close = 0; for (const ch of masked) { diff --git a/packages/core/src/adapters/structurizr/__tests__/deterministic-insert.test.ts b/packages/core/src/adapters/structurizr/__tests__/deterministic-insert.test.ts new file mode 100644 index 00000000..c8eafacf --- /dev/null +++ b/packages/core/src/adapters/structurizr/__tests__/deterministic-insert.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from 'vitest'; +import { StructurizrPatcher } from '../patcher.js'; +import { quickValidatePatch } from '../../base-patcher.js'; + +class TestPatcher extends StructurizrPatcher { + public insert(content: string, lines: string[]): string { + return this.deterministicInsert(content, lines); + } +} + +const content = [ + "# Bob's workspace", + 'workspace {', + ' model {', + ' a = softwareSystem "A"', + ' }', + " // Ops team's views", + ' views {', + ' }', + '}', +].join('\n'); +const lines = content.split('\n'); + +describe('StructurizrPatcher deterministic insert', () => { + it('ignores apostrophes in # and // comments', () => { + expect(new TestPatcher().insert(content, [' a -> a "uses"'])).toBe( + [...lines.slice(0, 4), '', ' a -> a "uses"', ...lines.slice(4)].join('\n') + ); + }); + + it('quick-validates with Structurizr scan options', () => { + const patched = content.replace(' }\n //', ' a -> a "uses"\n }\n //'); + const options = { quotes: ['"'], hashComments: true }; + expect(quickValidatePatch(content, patched, ['a -> a "uses"'], options)).toBe(true); + }); +}); diff --git a/packages/core/src/adapters/structurizr/patcher.ts b/packages/core/src/adapters/structurizr/patcher.ts index 96145abc..7b7f27ee 100644 --- a/packages/core/src/adapters/structurizr/patcher.ts +++ b/packages/core/src/adapters/structurizr/patcher.ts @@ -23,6 +23,8 @@ export class StructurizrPatcher extends BasePatcher { protected readonly formatId = 'structurizr'; protected readonly defaultIndent = ' '; protected readonly kindSensitiveDedup = false; + // Structurizr strings use double quotes only, so an apostrophe in a `#` comment opens nothing + protected override readonly scanOptions = { quotes: ['"'], hashComments: true }; protected generateDslLines( unique: StructuredRelationship[], diff --git a/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md b/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md index 5067c1cd..0d907afb 100644 --- a/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md +++ b/packages/web/src/content/docs/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks.md @@ -64,7 +64,7 @@ Alternatives considered: ## Amendments -- **2026-11-17:** `model-edits` is now the default `patchStrategy`; `text` stays selectable and remains the fallback whenever model edits return no patch. The text path relies on line heuristics that failed on real models: it wrote dotted IDs such as `a.b.c = service` (invalid DSL, so the relationships in the same patch were dropped too), took `extend x.datamodel {` for the `model` block, and counted braces inside strings and comments. Model edits let LikeC4 place the change instead. The text path was fixed as well: dotted IDs become `extend { = ... }`, sharing the helper that builds the diff block, so the `insertedLines` risk above no longer applies to nesting; and a shared scanner skips strings (`'...'`, `"..."`, `'''...'''`) and comments when finding the `model` block and its closing brace. +- **2026-11-17:** `model-edits` is now the default `patchStrategy`; `text` stays selectable and remains the fallback whenever model edits return no patch. The text path relies on line heuristics that failed on real models: it wrote dotted IDs such as `a.b.c = service` (invalid DSL, so the relationships in the same patch were dropped too), took `extend x.datamodel {` for the `model` block, and counted braces inside strings and comments. Model edits let LikeC4 place the change instead. The text path was fixed as well: dotted IDs become `extend { = ... }`, sharing the helper that builds the diff block, and a shared scanner skips strings (`'...'`, `"..."`, `'''...'''`) and comments when finding the `model` block and its closing brace. Structurizr uses the same scanner with double quotes only and `#` comment lines. The `insertedLines` risk above still holds in a narrower form: the text-path lines are now valid `extend` DSL, but under `model-edits` they can differ from where LikeC4 placed the element. ## Related commits From f05768f595acf59d7372d4af8e19bc7a64283b81 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 17:13:50 +0100 Subject: [PATCH 4/5] fix(core): address review findings in DSL scanning and patch validation - Keep // after : as part of an unquoted URI, not a line comment - Find model blocks after a BOM and after { or ; on the same line - Quick-validate by brace delta and require inserted entries as contiguous blocks - Place the model-edits diff file in the selected LikeC4 project's folder - Ignore -> in comments and strings when picking the target file - Indent entries one level inside an empty or split model block --- .../adapters/__tests__/dsl-scanner.test.ts | 37 +++++++++ packages/core/src/adapters/base-patcher.ts | 75 ++++++++++------- packages/core/src/adapters/dsl-scanner.ts | 16 ++-- .../__tests__/deterministic-insert.test.ts | 6 +- .../likec4/__tests__/model-edits.test.ts | 1 + .../__tests__/multi-file-workspace.test.ts | 2 +- .../likec4/__tests__/multi-project.test.ts | 19 +++++ .../__tests__/patcher-robustness.test.ts | 43 ++++++++++ .../core/src/adapters/likec4/model-edits.ts | 80 ++++++++++++++++--- packages/core/src/adapters/likec4/patcher.ts | 11 ++- 10 files changed, 238 insertions(+), 52 deletions(-) diff --git a/packages/core/src/adapters/__tests__/dsl-scanner.test.ts b/packages/core/src/adapters/__tests__/dsl-scanner.test.ts index 3d9fed50..1430a47d 100644 --- a/packages/core/src/adapters/__tests__/dsl-scanner.test.ts +++ b/packages/core/src/adapters/__tests__/dsl-scanner.test.ts @@ -51,6 +51,43 @@ describe('findModelBlocks', () => { }); }); +describe('unquoted URIs', () => { + it('keeps the brace after a LikeC4 link URI', () => { + const text = "model {\n api = service 'API' { link https://x.io }\n}"; + expect(countBraces(text)).toEqual({ open: 2, close: 2 }); + expect(findModelBlocks(text)).toEqual([{ open: 6, close: text.length - 1 }]); + }); + + it('keeps the brace after a Structurizr url', () => { + const options = { quotes: ['"'], hashComments: true }; + const text = 'model {\n a = softwareSystem "A" { url https://x.io }\n}'; + expect(countBraces(text, options)).toEqual({ open: 2, close: 2 }); + expect(findModelBlocks(text, options)).toEqual([{ open: 6, close: text.length - 1 }]); + }); + + it('still treats // after a space as a comment', () => { + expect(countBraces('a { // }\n}')).toEqual({ open: 1, close: 1 }); + }); +}); + +describe('findModelBlocks statement starts', () => { + it('ignores a byte order mark on the first line', () => { + expect(findModelBlocks('\uFEFFmodel {\n}')).toEqual([{ open: 7, close: 9 }]); + }); + + it('finds model after { or ; on the same line', () => { + const options = { quotes: ['"'], hashComments: true }; + const text = 'workspace "x" { model {\n a = person "A"\n} }'; + expect(findModelBlocks(text, options)).toEqual([{ open: 22, close: text.length - 3 }]); + expect(findModelBlocks('views { }; model { }')).toEqual([{ open: 17, close: 19 }]); + }); + + it('still rejects extend blocks and elements named model on the same line', () => { + expect(findModelBlocks('model { extend x.datamodel { } }')).toEqual([{ open: 6, close: 31 }]); + expect(findModelBlocks("x { model = service 'X' { } }")).toEqual([]); + }); +}); + describe('countBraces', () => { it('counts only structural braces', () => { expect(countBraces("a { description '}' /* } */ // {\n}")).toEqual({ open: 1, close: 1 }); diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index 3b4ac67c..4754029d 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -362,9 +362,9 @@ export abstract class BasePatcher implements ModelPatcher { protected deterministicInsert(content: string, lines: string[]): string { // Insert before the end of the last model block, else before the last `}` in the file + const block = findModelBlocks(content, this.scanOptions).at(-1); const closeAt = - findModelBlocks(content, this.scanOptions).at(-1)?.close ?? - maskStringsAndComments(content, this.scanOptions).lastIndexOf('}'); + block?.close ?? maskStringsAndComments(content, this.scanOptions).lastIndexOf('}'); if (closeAt === -1) { return content + '\n' + lines.join('\n') + '\n'; } @@ -386,7 +386,11 @@ export abstract class BasePatcher implements ModelPatcher { } const lineAbove = contentLines[insertIndex - 1] ?? ''; - const indent = /^(\s*)/.exec(lineAbove)?.[1] ?? this.defaultIndent; + const aboveIsOpener = block + ? content.slice(0, block.open).split('\n').length === insertIndex + : lineAbove.trimEnd().endsWith('{'); + const aboveIndent = /^[ \t]*/.exec(lineAbove)?.[0] ?? ''; + const indent = aboveIsOpener ? aboveIndent + this.defaultIndent : aboveIndent; contentLines.splice(insertIndex, 0, '', ...lines.flatMap((entry) => reindent(entry, indent))); return contentLines.join('\n'); @@ -414,6 +418,31 @@ function reindent(entry: string, indent: string): string[] { return lines.map((l) => (l.trim().length > 0 ? indent + l.slice(common) : '')); } +/** Whether `entry`'s non-blank lines appear, trimmed and in order, as a contiguous run in `lines`. */ +function containsRun(lines: readonly string[], entry: string): boolean { + const run = entry + .split('\n') + .map((l) => l.trim()) + .filter((l) => l.length > 0); + if (run.length === 0) return true; + for (let i = 0; i + run.length <= lines.length; i++) { + if (run.every((l, k) => lines[i + k] === l)) return true; + } + return false; +} + +function braceDelta(text: string, scanOptions?: ScanOptions): number { + const { open, close } = countBraces(text, scanOptions); + return open - close; +} + +function rejectPatch(reason: string, data: unknown): false { + if (CONFIG.debug.verbose) { + console.error(`[quickValidatePatch] Failed: ${reason}`, JSON.stringify(data)); + } + return false; +} + /** Quick structural validation shared by both patchers. */ export function quickValidatePatch( original: string, @@ -423,37 +452,23 @@ export function quickValidatePatch( ): boolean { const originalLines = original.split('\n').filter((l) => l.trim().length > 0); for (const line of originalLines) { - if (!patched.includes(line)) { - if (CONFIG.debug.verbose) { - console.error('[quickValidatePatch] Failed: original line missing', JSON.stringify(line)); - } - return false; - } + if (!patched.includes(line)) return rejectPatch('original line missing', line); } - // Multi-line entries are checked per line, since the LLM may re-indent nested blocks - const insertedSubLines = insertedLines.flatMap((entry) => - entry.split('\n').filter((l) => l.trim().length > 0) - ); - for (const line of insertedSubLines) { - if (!patched.includes(line.trim())) { - if (CONFIG.debug.verbose) { - console.error('[quickValidatePatch] Failed: inserted line missing', JSON.stringify(line)); - } - return false; - } + // Each entry must appear as a block; the LLM may re-indent it, so lines are compared trimmed + const patchedLines = patched + .split('\n') + .map((l) => l.trim()) + .filter((l) => l.length > 0); + for (const entry of insertedLines) { + if (!containsRun(patchedLines, entry)) return rejectPatch('inserted entry missing', entry); } - const { open: openBraces, close: closeBraces } = countBraces(patched, scanOptions); - if (openBraces !== closeBraces) { - if (CONFIG.debug.verbose) { - console.error( - '[quickValidatePatch] Failed: brace imbalance', - JSON.stringify({ open: openBraces, close: closeBraces }) - ); - } - return false; - } + // Compare deltas, not balance, so a file the scanner misreads does not reject every patch + const expected = + braceDelta(original, scanOptions) + braceDelta(insertedLines.join('\n'), scanOptions); + const actual = braceDelta(patched, scanOptions); + if (actual !== expected) return rejectPatch('brace delta mismatch', { expected, actual }); return true; } diff --git a/packages/core/src/adapters/dsl-scanner.ts b/packages/core/src/adapters/dsl-scanner.ts index 9a5f9c7d..2a7eab59 100644 --- a/packages/core/src/adapters/dsl-scanner.ts +++ b/packages/core/src/adapters/dsl-scanner.ts @@ -9,11 +9,12 @@ export interface ScanOptions { * Copy of `text` with the contents of strings and comments replaced by spaces. * Newlines and offsets are kept, so positions found in the result apply to `text`. * Handles quoted strings (backslash escapes, may span lines), triple-quoted strings, - * `//` line comments and `/* *\/` block comments. + * `//` line comments and `/* *\/` block comments. A byte order mark is blanked too. */ export function maskStringsAndComments(text: string, options: ScanOptions = {}): string { const quotes = options.quotes ?? ["'", '"']; const out = text.split(''); + if (out[0] === '\uFEFF') out[0] = ' '; const blank = (from: number, to: number): void => { for (let k = from; k < to && k < out.length; k++) { if (out[k] !== '\n') out[k] = ' '; @@ -42,7 +43,11 @@ export function maskStringsAndComments(text: string, options: ScanOptions = {}): } end = Math.min(end + 1, text.length); } - } else if ((ch === '/' && text[i + 1] === '/') || (ch === '#' && atHashComment(i))) { + } else if ( + // `//` right after `:` belongs to an unquoted URI such as `link https://x.io` + (ch === '/' && text[i + 1] === '/' && text[i - 1] !== ':') || + (ch === '#' && atHashComment(i)) + ) { end = lineEnd(i); } else if (ch === '/' && text[i + 1] === '*') { const close = text.indexOf('*/', i + 2); @@ -75,13 +80,14 @@ export interface BlockSpan { } /** - * Balanced `model { ... }` blocks, in file order. The keyword must start a line and the - * `{` may follow on a later line, so `extend shop.datamodel {` is not a model block. + * Balanced `model { ... }` blocks, in file order. The keyword must start a statement (a line, + * or follow `{` or `;`) and the `{` may follow on a later line, so `extend shop.datamodel {` + * is not a model block but `workspace "x" { model {` is. */ export function findModelBlocks(text: string, options?: ScanOptions): BlockSpan[] { const masked = maskStringsAndComments(text, options); const blocks: BlockSpan[] = []; - for (const match of masked.matchAll(/^[ \t]*model\s*\{/gm)) { + for (const match of masked.matchAll(/(?<=^|[{;])[ \t]*model\s*\{/gm)) { const open = match.index + match[0].length - 1; const close = matchingBrace(masked, open); if (close !== -1) blocks.push({ open, close }); diff --git a/packages/core/src/adapters/likec4/__tests__/deterministic-insert.test.ts b/packages/core/src/adapters/likec4/__tests__/deterministic-insert.test.ts index e44c3241..308500a8 100644 --- a/packages/core/src/adapters/likec4/__tests__/deterministic-insert.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/deterministic-insert.test.ts @@ -12,10 +12,14 @@ describe('LikeC4Patcher deterministic insert', () => { it('splits a one-line model block', () => { expect(patcher.insert("model { a = service 'A' }", [' a -> b'])).toBe( - "model { a = service 'A'\n\na -> b\n}" + "model { a = service 'A'\n\n a -> b\n}" ); }); + it('indents entries one level inside an empty model block', () => { + expect(patcher.insert(' model {\n }', ['a -> b'])).toBe(' model {\n\n a -> b\n }'); + }); + it('ignores braces inside quoted titles', () => { const content = "model { a = service 'Team } services'\n b = service 'B'\n}"; expect(patcher.insert(content, [' a -> b'])).toBe( diff --git a/packages/core/src/adapters/likec4/__tests__/model-edits.test.ts b/packages/core/src/adapters/likec4/__tests__/model-edits.test.ts index 39661190..f9382cb0 100644 --- a/packages/core/src/adapters/likec4/__tests__/model-edits.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/model-edits.test.ts @@ -24,6 +24,7 @@ vi.mock('likec4', () => ({ fromWorkspace: vi.fn((dir: string) => Promise.resolve({ dispose, + languageServices: { projects: () => [] }, modelDiffs: { list: () => Promise.resolve([{ id: currentDiffId }]) }, modelEdits: state.hasModelEdits ? { diff --git a/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts b/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts index 2cef6079..f829d44e 100644 --- a/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/multi-file-workspace.test.ts @@ -67,7 +67,7 @@ describe('LikeC4 multi-file workspace', () => { expect(result?.absolutePath).toBe(path.join(workspace, 'spec.c4')); expect(result?.validationSkipped).toBeUndefined(); expect(result?.content).toMatch( - /model \{ shared = system 'Shared Platform'\n\nshared -> core\.billing 'hosts'\n\}/ + /model \{ shared = system 'Shared Platform'\n\n {2}shared -> core\.billing 'hosts'\n\}/ ); }); diff --git a/packages/core/src/adapters/likec4/__tests__/multi-project.test.ts b/packages/core/src/adapters/likec4/__tests__/multi-project.test.ts index beac3255..6257275a 100644 --- a/packages/core/src/adapters/likec4/__tests__/multi-project.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/multi-project.test.ts @@ -7,6 +7,7 @@ import { LikeC4Adapter } from '../adapter.js'; import { validateLikeC4Dsl } from '../dsl-validator.js'; import { formatLikeC4Dsl } from '../dsl-formatter.js'; import { LikeC4Patcher } from '../patcher.js'; +import { previewModelEdits } from '../model-edits.js'; import type { AIProvider } from '../../../providers/ai-provider.js'; import { CONFIG } from '../../../utils/config.js'; import { ConfigurationError } from '../../../errors.js'; @@ -147,6 +148,24 @@ describe('LikeC4Adapter with a multi-project workspace', () => { } }); + it('should place model edits in the selected project', async () => { + const outcome = await previewModelEdits( + workspace, + [{ id: 'payments', kind: 'service', name: 'Payments' }], + ["cart -> storefront 'sends updates'"], + 'shop' + ); + expect(outcome).toMatchObject({ ok: true, patch: { targetFile: shopModel } }); + const content = outcome.ok ? outcome.patch.content : ''; + expect(content).toContain("cart -> storefront 'sends updates'"); + expect(content).toContain("payments = service 'Payments'"); + }); + + it('should not guess a project for model edits when several exist', async () => { + const outcome = await previewModelEdits(workspace, [], ["cart -> storefront 'x'"]); + expect(outcome.ok).toBe(false); + }); + it('should load only the configured project in loadAndListComponents', async () => { CONFIG.adapter.likec4.project = 'billing'; const components = await new LikeC4Adapter().loadAndListComponents(workspace); diff --git a/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts b/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts index fce275ce..f82257eb 100644 --- a/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts +++ b/packages/core/src/adapters/likec4/__tests__/patcher-robustness.test.ts @@ -1,4 +1,7 @@ import { describe, it, expect } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; import { LikeC4Patcher } from '../patcher.js'; import { quickValidatePatch } from '../../base-patcher.js'; import type { NewComponent } from '../../../analysis/analysis-types.js'; @@ -8,6 +11,10 @@ class TestPatcher extends LikeC4Patcher { return this.deterministicInsert(content, lines); } + public target(modelPath: string): string | null { + return this.findTargetFile(modelPath); + } + public componentLines(components: NewComponent[]): string[] { return this.generateComponentDslLines(components); } @@ -63,6 +70,29 @@ describe('LikeC4Patcher dotted new components', () => { "model {\n shop = system 'Shop'\n\n extend shop {\n cache = service 'Cache' {\n }\n }\n}"; expect(quickValidatePatch(original, patched, inserted)).toBe(true); }); + + it('rejects a block whose lines are present but not nested as one block', () => { + const original = "model {\n shop = system 'Shop'\n}"; + const inserted = [" extend shop {\n cache = service 'Cache' {\n }\n }"]; + const patched = + "model {\n shop = system 'Shop'\n extend shop {\n }\n cache = service 'Cache' {\n }\n}"; + expect(quickValidatePatch(original, patched, inserted)).toBe(false); + }); +}); + +describe('quickValidatePatch brace delta', () => { + // `/*` in the unquoted URI reads as an unterminated block comment, so the scan is unbalanced + const original = "model {\n a = service 'A' {\n link https://x.io/api/*\n }\n}"; + + it('accepts a correct patch to a file the scanner misreads', () => { + const patched = original.replace("'A' {", "'A' {\n -> a 'self'"); + expect(quickValidatePatch(original, patched, [" -> a 'self'"])).toBe(true); + }); + + it('rejects a patch that adds a stray brace', () => { + const patched = original.replace("'A' {", "'A' {\n -> a 'self'\n }"); + expect(quickValidatePatch(original, patched, [" -> a 'self'"])).toBe(false); + }); }); describe('LikeC4Patcher deterministic insert placement', () => { @@ -122,3 +152,16 @@ describe('LikeC4Patcher deterministic insert placement', () => { expect(quickValidatePatch(original, patched, [' a -> a'])).toBe(true); }); }); + +describe('LikeC4Patcher target file heuristic', () => { + it('ignores -> inside comments and strings when looking for relationships', () => { + const dir = mkdtempSync(join(tmpdir(), 'erode-target-')); + try { + writeFileSync(join(dir, 'a.c4'), "model {\n // a -> b\n a = service 'A -> B'\n}"); + writeFileSync(join(dir, 'b.c4'), "model {\n b = service 'B'\n b -> b\n}"); + expect(patcher.target(dir)).toBe(join(dir, 'b.c4')); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/core/src/adapters/likec4/model-edits.ts b/packages/core/src/adapters/likec4/model-edits.ts index 4a7c2f05..f395edde 100644 --- a/packages/core/src/adapters/likec4/model-edits.ts +++ b/packages/core/src/adapters/likec4/model-edits.ts @@ -1,5 +1,6 @@ import { realpathSync } from 'node:fs'; -import { isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { rename } from 'node:fs/promises'; +import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { randomBytes } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { z } from 'zod'; @@ -86,29 +87,63 @@ function canonical(path: string): string { } type LikeC4Instance = Awaited>; +type ProjectData = ReturnType[number]; + +type Placement = + { ok: true; project?: ProjectData; moveTo?: string } | { ok: false; reason: string }; + +/** + * The project the diff file must belong to. LikeC4 assigns a file to the project whose folder + * holds it, so a diff at the workspace root misses a project kept in a subfolder. + */ +function placeProposal( + likec4: LikeC4Instance, + projectName: string | undefined, + tmpProposal: string +): Placement { + const proposal = canonical(tmpProposal); + const all = likec4.languageServices.projects(); + // The proposal alone can create a root `default` project; that one does not count + const real = all.filter((p) => p.documents.some((d) => canonical(d.fsPath) !== proposal)); + const project = projectName ? all.find((p) => p.id === projectName) : real[0]; + if (projectName && !project) { + return { ok: false, reason: `LikeC4 project "${projectName}" not found` }; + } + if (!projectName && real.length > 1) { + return { ok: false, reason: 'several LikeC4 projects and adapter.likec4.project is not set' }; + } + if (!project) return { ok: true }; + const folder = canonical(project.folder.fsPath); + const inProject = project.documents.some((d) => canonical(d.fsPath) === proposal); + return inProject ? { ok: true, project } : { ok: true, project, moveTo: folder }; +} async function previewInWorkspace( likec4: LikeC4Instance, diffId: string, tmpProposal: string, tmpDir: string, - resolvedModel: string + resolvedModel: string, + projectId: ProjectData['id'] | undefined ): Promise { const edits = (likec4 as { modelEdits?: { preview?: unknown } }).modelEdits; if (!edits || typeof edits.preview !== 'function') { return { ok: false, reason: 'likec4 SDK has no modelEdits API' }; } - const diffs = DiffListSchema.safeParse(await likec4.modelDiffs.list()); + const diffs = DiffListSchema.safeParse(await likec4.modelDiffs.list(projectId)); if (!diffs.success || !diffs.data.some((d) => d.id === diffId)) { return { ok: false, reason: `diff ${diffId} not found in workspace` }; } - const raw: unknown = await likec4.modelEdits.preview({ - type: 'apply-diff', - diffId: diffId as never, - action: 'apply', - }); + const raw: unknown = await likec4.modelEdits.preview( + { + type: 'apply-diff', + diffId: diffId as never, + action: 'apply', + }, + projectId + ); const preview = PreviewSchema.safeParse(raw); if (!preview.success) { return { ok: false, reason: 'unexpected modelEdits.preview result' }; @@ -145,7 +180,8 @@ async function previewInWorkspace( export async function previewModelEdits( modelPath: string, components: NewComponent[], - relationshipLines: string[] + relationshipLines: string[], + projectName?: string ): Promise { const resolvedModel = resolve(modelPath); const diffId = `erode_${randomBytes(4).toString('hex')}`; @@ -159,11 +195,31 @@ export async function previewModelEdits( 'erode-likec4-edits', async (tmpProposal, tmpDir) => { const { LikeC4 } = await import('likec4'); - const likec4 = await LikeC4.fromWorkspace(tmpDir, { printErrors: false }); + const load = () => LikeC4.fromWorkspace(tmpDir, { printErrors: false }); + let likec4: LikeC4Instance | undefined = await load(); try { - return await previewInWorkspace(likec4, diffId, tmpProposal, tmpDir, resolvedModel); + const placement = placeProposal(likec4, projectName, tmpProposal); + if (!placement.ok) return placement; + let proposal = tmpProposal; + if (placement.moveTo) { + proposal = join(placement.moveTo, basename(tmpProposal)); + await rename(tmpProposal, proposal); + const stale = likec4; + likec4 = undefined; + await stale.dispose(); + likec4 = await load(); + } + const projectId = placement.project?.id; + return await previewInWorkspace( + likec4, + diffId, + proposal, + tmpDir, + resolvedModel, + projectId + ); } finally { - await likec4.dispose(); + await likec4?.dispose(); } } ); diff --git a/packages/core/src/adapters/likec4/patcher.ts b/packages/core/src/adapters/likec4/patcher.ts index b6efd6a9..e7ced68d 100644 --- a/packages/core/src/adapters/likec4/patcher.ts +++ b/packages/core/src/adapters/likec4/patcher.ts @@ -5,7 +5,7 @@ import { knownRelationshipKinds, resolveRelationshipKind } from '../relationship import { validateLikeC4Dsl } from './dsl-validator.js'; import { formatLikeC4Dsl } from './dsl-formatter.js'; import { componentDefinition, escapeLikeC4String, previewModelEdits } from './model-edits.js'; -import { findModelBlocks } from '../dsl-scanner.js'; +import { findModelBlocks, maskStringsAndComments } from '../dsl-scanner.js'; import type { StructuredRelationship, NewComponent } from '../../analysis/analysis-types.js'; import type { ModelRelationship } from '../architecture-types.js'; import type { DslValidationResult } from '../model-patcher.js'; @@ -82,7 +82,7 @@ export class LikeC4Patcher extends BasePatcher { continue; // dangling symlink or unreadable file } if (findModelBlocks(content).length === 0) continue; - if (content.includes('->')) return file; + if (maskStringsAndComments(content).includes('->')) return file; withModel ??= file; } @@ -108,7 +108,12 @@ export class LikeC4Patcher extends BasePatcher { if (CONFIG.adapter.likec4.patchStrategy !== 'model-edits') { return null; } - const outcome = await previewModelEdits(modelPath, components, relationshipLines); + const outcome = await previewModelEdits( + modelPath, + components, + relationshipLines, + CONFIG.adapter.likec4.project + ); if (!outcome.ok) { this.debugLog('Model edits unavailable; falling back to text patching', outcome.reason); return null; From 74e414dda164440c5545deec5fea58f6f1b498d8 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 18:58:40 +0100 Subject: [PATCH 5/5] fix(core): do not treat URL paths as comments in the DSL scanner Comments now open only at a token boundary (line start, whitespace, or one of { } ;), so unquoted URIs containing // or /* no longer hide later braces. --- .../__tests__/dsl-scanner-urls.test.ts | 67 +++++++++++++++++++ packages/core/src/adapters/dsl-scanner.ts | 10 ++- 2 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 packages/core/src/adapters/__tests__/dsl-scanner-urls.test.ts diff --git a/packages/core/src/adapters/__tests__/dsl-scanner-urls.test.ts b/packages/core/src/adapters/__tests__/dsl-scanner-urls.test.ts new file mode 100644 index 00000000..550a248a --- /dev/null +++ b/packages/core/src/adapters/__tests__/dsl-scanner-urls.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect } from 'vitest'; +import { BasePatcher } from '../base-patcher.js'; +import { countBraces, maskStringsAndComments } from '../dsl-scanner.js'; + +class TestPatcher extends BasePatcher { + protected readonly formatName = 'Test'; + protected readonly formatId = 'test'; + protected readonly defaultIndent = ' '; + protected readonly kindSensitiveDedup = false; + protected generateDslLines(): string[] { + return []; + } + protected generateComponentDslLines(): string[] { + return []; + } + protected findTargetFile(): string | null { + return null; + } + protected validateDsl(): Promise { + return Promise.reject(new Error('not used')); + } + insert(content: string, lines: string[]): string { + return this.deterministicInsert(content, lines); + } +} + +describe('URL paths are not comments', () => { + it.each([ + ['link', 'https://x.io/api/*'], + ['url', 'https://x.io/a/*b'], + ['link', 'https://x.io/a//b'], + ])('inserts inside model after `%s %s`', (keyword, uri) => { + const content = [ + 'model {', + ` api = service 'API' {`, + ` ${keyword} ${uri}`, + ' }', + ` db = database 'DB'`, + '}', + '', + ].join('\n'); + const result = new TestPatcher().insert(content, [' api -> db']).split('\n'); + expect(result).toEqual([ + 'model {', + ` api = service 'API' {`, + ` ${keyword} ${uri}`, + ' }', + ` db = database 'DB'`, + '', + ' api -> db', + '}', + '', + ]); + expect(countBraces(content)).toEqual({ open: 2, close: 2 }); + }); + + it('still masks real block and line comments', () => { + const text = 'a /* { */ b // }\n{ // }\n} /* x\n}'; + expect(maskStringsAndComments(text)).toBe('a b \n{ \n} \n '); + }); + + it('masks comments right after braces and semicolons', () => { + expect(maskStringsAndComments('a{// x')).toBe('a{ '); + expect(maskStringsAndComments('a}// x')).toBe('a} '); + expect(maskStringsAndComments('a;/* x */')).toBe('a; '); + }); +}); diff --git a/packages/core/src/adapters/dsl-scanner.ts b/packages/core/src/adapters/dsl-scanner.ts index 2a7eab59..a7497c7d 100644 --- a/packages/core/src/adapters/dsl-scanner.ts +++ b/packages/core/src/adapters/dsl-scanner.ts @@ -22,6 +22,11 @@ export function maskStringsAndComments(text: string, options: ScanOptions = {}): }; const atHashComment = (at: number): boolean => !!options.hashComments && text.slice(text.lastIndexOf('\n', at - 1) + 1, at).trim() === ''; + // A comment opens only at a token boundary (line start, whitespace, `{`, `}` or `;`), never + // inside an unquoted token. Unquoted URIs such as `link https://x.io/api/*` contain `//` and + // `/*`, and mistaking them for comments would hide every later closing brace. Real comments in + // models are always written after whitespace or a brace, so this is the safest boundary. + const commentMayStart = (at: number): boolean => at === 0 || /[\s{};]/.test(text.charAt(at - 1)); const lineEnd = (from: number): number => { const newline = text.indexOf('\n', from); return newline === -1 ? text.length : newline; @@ -44,12 +49,11 @@ export function maskStringsAndComments(text: string, options: ScanOptions = {}): end = Math.min(end + 1, text.length); } } else if ( - // `//` right after `:` belongs to an unquoted URI such as `link https://x.io` - (ch === '/' && text[i + 1] === '/' && text[i - 1] !== ':') || + (ch === '/' && text[i + 1] === '/' && commentMayStart(i)) || (ch === '#' && atHashComment(i)) ) { end = lineEnd(i); - } else if (ch === '/' && text[i + 1] === '*') { + } else if (ch === '/' && text[i + 1] === '*' && commentMayStart(i)) { const close = text.indexOf('*/', i + 2); end = close === -1 ? text.length : close + 2; } else {