Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(review): bound the spatial grids and keep cached routes read-only

goatliamia20eea1955825
diff --git a/archify.zip b/archify.zip
index 31c819d7..4dbe9bef 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/renderers/architecture/labels.mjs b/archify/renderers/architecture/labels.mjs
index e308afd4..1cced53d 100644
--- a/archify/renderers/architecture/labels.mjs
+++ b/archify/renderers/architecture/labels.mjs
@@ -1,4 +1,5 @@
import { normalizeRoutePoints, rectsOverlap, segmentRectClearanceWithin } from '../shared/geometry.mjs';
+import { createSpatialGrid } from '../shared/spatial-grid.mjs';
// A bounded fallback for an unpinned label whose usual position collides.
// It never routes an edge, moves a node, expands the canvas, or rewrites input.
@@ -18,38 +19,19 @@ export function placeAutomaticLabels({
// The mask test asked every segment about every candidate position. Segments
// go into a uniform grid once, and a candidate only asks the cells it covers.
const SEGMENT_CELL = 120;
- const segmentGrid = new Map();
+ const segmentGrid = createSpatialGrid(SEGMENT_CELL);
for (const segment of segments) {
const [sx, sy] = segment.start;
const [ex, ey] = segment.end;
- const x0 = Math.floor(Math.min(sx, ex) / SEGMENT_CELL);
- const x1 = Math.floor(Math.max(sx, ex) / SEGMENT_CELL);
- const y0 = Math.floor(Math.min(sy, ey) / SEGMENT_CELL);
- const y1 = Math.floor(Math.max(sy, ey) / SEGMENT_CELL);
- for (let cx = x0; cx <= x1; cx += 1) {
- for (let cy = y0; cy <= y1; cy += 1) {
- const key = cx + ':' + cy;
- let bucket = segmentGrid.get(key);
- if (!bucket) { bucket = []; segmentGrid.set(key, bucket); }
- bucket.push(segment);
- }
- }
+ segmentGrid.insert({
+ minX: Math.min(sx, ex), maxX: Math.max(sx, ex),
+ minY: Math.min(sy, ey), maxY: Math.max(sy, ey),
+ }, segment);
}
- const segmentsNear = (rect, margin) => {
- const found = new Set();
- const x0 = Math.floor((rect.x - margin) / SEGMENT_CELL);
- const x1 = Math.floor((rect.x + rect.width + margin) / SEGMENT_CELL);
- const y0 = Math.floor((rect.y - margin) / SEGMENT_CELL);
- const y1 = Math.floor((rect.y + rect.height + margin) / SEGMENT_CELL);
- for (let cx = x0; cx <= x1; cx += 1) {
- for (let cy = y0; cy <= y1; cy += 1) {
- const bucket = segmentGrid.get(cx + ':' + cy);
- if (!bucket) continue;
- for (const segment of bucket) found.add(segment);
- }
- }
- return found;
- };
+ const segmentsNear = (rect, margin) => segmentGrid.query({
+ minX: rect.x - margin, maxX: rect.x + rect.width + margin,
+ minY: rect.y - margin, maxY: rect.y + rect.height + margin,
+ });
const masksRoute = rect => {
for (const segment of segmentsNear(rect, 4)) {
if (segment.relationIndex === rect.relationIndex) continue;
diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjs
index 77317688..b993eb51 100644
--- a/archify/renderers/shared/cli.mjs
+++ b/archify/renderers/shared/cli.mjs
@@ -98,8 +98,9 @@ const BRAND_COLLECTIONS = {
function declaresBrandMark(diagramType, diagram) {
const collection = BRAND_COLLECTIONS[diagramType];
const elements = collection && Array.isArray(diagram?.[collection]) ? diagram[collection] : [];
- return elements.some((element) => element && element.brand !== undefined && element.brand !== null
- && String(element.brand).trim() !== '');
+ // Same skip condition as the preparer, so a mark it would report as unknown
+ // still reaches it.
+ return elements.some((element) => Boolean(element?.brand));
}
export async function loadDiagramWithBrandMarks(options) {
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index 8e5547fd..6231b9e1 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -1271,7 +1271,10 @@ function segmentPosition(index, segmentCount) {
// Normalizing a route is pure, and the same route array is normalized again by
// every predicate that inspects it. Keyed by the array itself, so a rebuilt
-// route simply gets a new entry.
+// route simply gets a new entry. Cached results are frozen: every reader gets
+// the same read-only array, and an in-place edit cannot leave a stale entry
+// behind. The point array it contains is produced once per render and read
+// only.
const NORMALIZED_ROUTE_POINTS = new WeakMap();
// Assembling a route from an anchor, corridor points and an anchor is the same
@@ -1291,6 +1294,7 @@ export function joinRoutePoints(start, via, end) {
accept(start);
for (const point of Array.isArray(via) ? via : []) accept(point);
accept(end);
+ Object.freeze(normalized);
NORMALIZED_ROUTE_POINTS.set(normalized, normalized);
return normalized;
}
@@ -1310,7 +1314,10 @@ export function normalizeRoutePoints(points) {
while (normalized.length >= 2 && collinearForward(normalized.at(-2), normalized.at(-1), point)) normalized.pop();
normalized.push(point);
}
- if (Array.isArray(points)) NORMALIZED_ROUTE_POINTS.set(points, normalized);
+ if (Array.isArray(points)) {
+ Object.freeze(normalized);
+ NORMALIZED_ROUTE_POINTS.set(points, normalized);
+ }
return normalized;
}
diff --git a/archify/renderers/shared/repository-evidence.mjs b/archify/renderers/shared/repository-evidence.mjs
index 3ab35271..c434de74 100644
--- a/archify/renderers/shared/repository-evidence.mjs
+++ b/archify/renderers/shared/repository-evidence.mjs
@@ -223,7 +223,29 @@ export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {
if (!Array.isArray(node.sources) || node.sources.length === 0) continue;
for (const [sourceIndex, authored] of node.sources.entries()) {
const at = `/${collection}/${nodeIndex}/sources/${sourceIndex}`;
- citedObjects.push(`${revision}:${verifiedSourcePath(authored.path, `${at}/path`)}`);
+ const sourcePath = verifiedSourcePath(authored.path, `${at}/path`);
+ // The same cheap line checks the verification loop makes, in the same
+ // order, so batching never reorders the first diagnostic.
+ if (authored.end_line && !authored.line) {
+ const nodeSubject = collection === 'components'
+ ? { diagramType, collection, nodeId: node.id, componentId: node.id }
+ : { diagramType, collection, nodeId: node.id };
+ evidenceFailure('repository-evidence/line-required', `${at}/end_line requires line.`, {
+ subject: { path: `${at}/end_line`, ...nodeSubject },
+ supportedFixes: ['add line or remove end_line'],
+ });
+ }
+ if (authored.end_line && authored.end_line < authored.line) {
+ const nodeSubject = collection === 'components'
+ ? { diagramType, collection, nodeId: node.id, componentId: node.id }
+ : { diagramType, collection, nodeId: node.id };
+ evidenceFailure('repository-evidence/line-range-invalid', `${at}/end_line must be greater than or equal to line.`, {
+ subject: { path: at, ...nodeSubject },
+ evidence: { line: authored.line, endLine: authored.end_line },
+ supportedFixes: ['use an end_line greater than or equal to line'],
+ });
+ }
+ citedObjects.push(`${revision}:${sourcePath}`);
}
}
const prefetchedBlobs = prefetchBlobs(realRoot, [...new Set(citedObjects)]);
diff --git a/archify/renderers/shared/spatial-grid.mjs b/archify/renderers/shared/spatial-grid.mjs
new file mode 100644
index 00000000..d2eb4396
--- /dev/null
+++ b/archify/renderers/shared/spatial-grid.mjs
@@ -0,0 +1,66 @@
+/** Uniform spatial grid for "which items can this box reach" queries (#8). */
+
+// A cell box wider than this is not worth walking: the query returns every
+// inserted item instead, which stays a superset of what the box reaches.
+const DEFAULT_MAX_CELLS = 4096;
+
+export function createSpatialGrid(cellSize, { maxCells = DEFAULT_MAX_CELLS } = {}) {
+ const buckets = new Map();
+ const items = [];
+ // Items whose own box cannot be walked are candidates for every query.
+ const overflow = [];
+ const keyOf = (x, y) => x + ':' + y;
+ const rangeOf = (box) => ({
+ x0: Math.floor(box.minX / cellSize), x1: Math.floor(box.maxX / cellSize),
+ y0: Math.floor(box.minY / cellSize), y1: Math.floor(box.maxY / cellSize),
+ });
+ // Finite coordinates can still land outside the safe-integer range, where
+ // incrementing an index no longer advances it; and a legal coordinate can
+ // name more cells than the grid is worth. Both cases stay out of the buckets
+ // and are answered by the item list, so they never hang or allocate.
+ const walkable = (range) => Number.isSafeInteger(range.x0) && Number.isSafeInteger(range.x1)
+ && Number.isSafeInteger(range.y0) && Number.isSafeInteger(range.y1)
+ && (range.x1 - range.x0 + 1) * (range.y1 - range.y0 + 1) <= maxCells;
+
+ return {
+ insert(box, item) {
+ items.push(item);
+ const range = rangeOf(box);
+ if (!walkable(range)) {
+ overflow.push(item);
+ return;
+ }
+ for (let x = range.x0; x <= range.x1; x += 1) {
+ for (let y = range.y0; y <= range.y1; y += 1) {
+ const key = keyOf(x, y);
+ let bucket = buckets.get(key);
+ if (!bucket) { bucket = []; buckets.set(key, bucket); }
+ bucket.push(item);
+ }
+ }
+ },
+ query(box) {
+ const range = rangeOf(box);
+ if (!walkable(range)) return items.slice();
+ const seen = new Set();
+ const found = [];
+ for (let x = range.x0; x <= range.x1; x += 1) {
+ for (let y = range.y0; y <= range.y1; y += 1) {
+ const bucket = buckets.get(keyOf(x, y));
+ if (!bucket) continue;
+ for (const item of bucket) {
+ if (seen.has(item)) continue;
+ seen.add(item);
+ found.push(item);
+ }
+ }
+ }
+ for (const item of overflow) {
+ if (seen.has(item)) continue;
+ seen.add(item);
+ found.push(item);
+ }
+ return found;
+ },
+ };
+}
diff --git a/archify/renderers/workflow/workflow-compiler.mjs b/archify/renderers/workflow/workflow-compiler.mjs
index f00bb61e..275dc6a0 100644
--- a/archify/renderers/workflow/workflow-compiler.mjs
+++ b/archify/renderers/workflow/workflow-compiler.mjs
@@ -1,3 +1,4 @@
+import { createSpatialGrid } from '../shared/spatial-grid.mjs';
import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';
import {
animateAttr,
@@ -1415,45 +1416,8 @@ const { measureNode, nodeTextFit, nodes } = measureWorkflowNodes(workflow, layou
// Obstacles of the routing search are queried through a uniform grid instead of
// scanned: a candidate can only fail an obstacle its own box can reach.
const OBSTACLE_CELL = 160;
-function createObstacleGrid() {
- const buckets = new Map();
- const rangeOf = (box) => ({
- x0: Math.floor(box.minX / OBSTACLE_CELL), x1: Math.floor(box.maxX / OBSTACLE_CELL),
- y0: Math.floor(box.minY / OBSTACLE_CELL), y1: Math.floor(box.maxY / OBSTACLE_CELL),
- });
- return {
- insert(box, item) {
- const range = rangeOf(box);
- for (let x = range.x0; x <= range.x1; x += 1) {
- for (let y = range.y0; y <= range.y1; y += 1) {
- const key = x + ':' + y;
- let bucket = buckets.get(key);
- if (!bucket) { bucket = []; buckets.set(key, bucket); }
- bucket.push(item);
- }
- }
- },
- query(box) {
- const range = rangeOf(box);
- const seen = new Set();
- const found = [];
- for (let x = range.x0; x <= range.x1; x += 1) {
- for (let y = range.y0; y <= range.y1; y += 1) {
- const bucket = buckets.get(x + ':' + y);
- if (!bucket) continue;
- for (const item of bucket) {
- if (seen.has(item)) continue;
- seen.add(item);
- found.push(item);
- }
- }
- }
- return found;
- },
- };
-}
-const obstacleGrid = createObstacleGrid();
+const obstacleGrid = createSpatialGrid(OBSTACLE_CELL);
let rightmostNodeEdge = 0;
for (const node of nodes.values()) {
obstacleGrid.insert(rectToBounds(node), { kind: 'node', node, bounds: rectToBounds(node) });
diff --git a/archify/test/spatial-grid.test.mjs b/archify/test/spatial-grid.test.mjs
new file mode 100644
index 00000000..d3630dbd
--- /dev/null
+++ b/archify/test/spatial-grid.test.mjs
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createSpatialGrid } from '../renderers/shared/spatial-grid.mjs';
+
+test('a query returns the items its box reaches, once each', () => {
+ const grid = createSpatialGrid(100);
+ const near = { id: 'near' };
+ const far = { id: 'far' };
+ grid.insert({ minX: 90, minY: 0, maxX: 210, maxY: 60 }, near);
+ grid.insert({ minX: 900, minY: 900, maxX: 960, maxY: 960 }, far);
+ assert.deepEqual(grid.query({ minX: 0, minY: 0, maxX: 140, maxY: 80 }), [near]);
+ assert.deepEqual(grid.query({ minX: 850, minY: 850, maxX: 1000, maxY: 1000 }), [far]);
+});
+
+test('an item spanning several cells is reported once', () => {
+ const grid = createSpatialGrid(100);
+ const long = { id: 'long' };
+ grid.insert({ minX: 0, minY: 0, maxX: 500, maxY: 40 }, long);
+ assert.deepEqual(grid.query({ minX: 0, minY: 0, maxX: 500, maxY: 60 }), [long]);
+});
+
+test('an item with an unbounded box stays out of the buckets and never stalls', () => {
+ const grid = createSpatialGrid(100);
+ const huge = { id: 'huge' };
+ const normal = { id: 'normal' };
+ grid.insert({ minX: 0, minY: 0, maxX: Number.MAX_VALUE, maxY: Number.MAX_VALUE }, huge);
+ grid.insert({ minX: 10, minY: 10, maxX: 20, maxY: 20 }, normal);
+ assert.deepEqual(grid.query({ minX: 0, minY: 0, maxX: 30, maxY: 30 }), [normal, huge]);
+});
+
+test('a query that cannot be walked returns every item instead of stalling', () => {
+ const grid = createSpatialGrid(100);
+ const first = { id: 'first' };
+ const second = { id: 'second' };
+ grid.insert({ minX: 0, minY: 0, maxX: 20, maxY: 20 }, first);
+ grid.insert({ minX: 500, minY: 500, maxX: 520, maxY: 520 }, second);
+ const all = grid.query({ minX: -Number.MAX_VALUE, minY: -Number.MAX_VALUE, maxX: Number.MAX_VALUE, maxY: Number.MAX_VALUE });
+ assert.deepEqual(all, [first, second]);
+});
+
+test('a legal but enormous box is answered without walking cells', () => {
+ const grid = createSpatialGrid(1);
+ const only = { id: 'only' };
+ grid.insert({ minX: 0, minY: 0, maxX: 0, maxY: 0 }, only);
+ assert.deepEqual(grid.query({ minX: 0, minY: 0, maxX: 1e9, maxY: 1e9 }), [only]);
+});