Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

Feat/sql support (#97)

josephismikhail25e3ac9108fc
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..e354da4e
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+* text=auto eol=lf
+*.sh text eol=lf
+*.ps1 text eol=crlf
diff --git a/core-ingestion/src/__tests__/queries.cpp.test.ts b/core-ingestion/src/__tests__/queries.cpp.test.ts
new file mode 100644
index 00000000..0c2305b6
--- /dev/null
+++ b/core-ingestion/src/__tests__/queries.cpp.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseFile } from '../index.js';
+
+describe('C++ queries', () => {
+ it('normalizes include targets without truncating path segments or leaving angle brackets', () => {
+ const result = parseFile(
+ '/repo/include/KimeraRPGO/outlier/Pcm.h',
+ `
+#include <gtsam/nonlinear/Values.h>
+#include <Eigen/Dense>
+#include "KimeraRPGO/utils/GraphUtils.h"
+
+class Pcm : public OutlierRemoval {};
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.entities.map((entity) => entity.name)).toEqual(
+ expect.arrayContaining(['Pcm']),
+ );
+
+ const importTargets = result!.relationships
+ .filter((relationship) => relationship.predicate === 'IMPORTS')
+ .map((relationship) => relationship.dstName);
+
+ expect(importTargets).toEqual(
+ expect.arrayContaining([
+ 'gtsam/nonlinear/Values.h',
+ 'Eigen/Dense',
+ 'KimeraRPGO/utils/GraphUtils.h',
+ ]),
+ );
+ expect(importTargets.some((name) => name.endsWith('>'))).toBe(false);
+ });
+});
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index e8f73cdd..cc4b359d 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -213,7 +213,7 @@ function builtinsForLanguage(lang: SupportedLanguages): Set<string> {
export function isGrammarSupported(filePath: string): boolean {
const language = languageFromPath(filePath);
if (!language) return false;
- if (language === SupportedLanguages.YAML || language === SupportedLanguages.Dockerfile) return true;
+ if (language === SupportedLanguages.YAML || language === SupportedLanguages.Dockerfile || language === SupportedLanguages.SQL) return true;
if (filePath.endsWith('.tsx')) return true; // TSX uses TypeScript.tsx, always available
return GRAMMAR_MAP[language] !== undefined;
}
@@ -545,6 +545,156 @@ function parseDockerfileFile(filePath: string, source: string): FileParseResult
};
}
+// ---------------------------------------------------------------------------
+// SQL
+// ---------------------------------------------------------------------------
+
+/** Strip -- line comments and /* block comments *\/ from SQL source. */
+function stripSqlComments(source: string): string {
+ // Block comments first, then line comments
+ return source
+ .replace(/\/\*[\s\S]*?\*\//g, match => match.replace(/[^\n]/g, ' '))
+ .replace(/--[^\n]*/g, match => ' '.repeat(match.length));
+}
+
+/** Extract unquoted table/view names following FROM, JOIN variants, INTO, UPDATE, REFERENCES. */
+function extractSqlTableRefs(sql: string): string[] {
+ const refs = new Set<string>();
+ // FROM tbl, JOIN tbl, INTO tbl, UPDATE tbl, REFERENCES tbl
+ const refPattern =
+ /\b(?:FROM|JOIN|INNER\s+JOIN|LEFT\s+JOIN|RIGHT\s+JOIN|FULL\s+JOIN|CROSS\s+JOIN|INTO|UPDATE|REFERENCES)\s+([A-Za-z0-9_.`"[\]]+)/gi;
+ let m: RegExpExecArray | null;
+ while ((m = refPattern.exec(sql)) !== null) {
+ refs.add(m[1].replace(/[`"[\]]/g, ''));
+ }
+ return [...refs];
+}
+
+function parseSqlFile(filePath: string, source: string): FileParseResult {
+ const language = SupportedLanguages.SQL;
+ const fileName = nodePath.basename(filePath);
+ const sourceLineCount = countSourceLines(source);
+ const fileRole = classifyFileRole(filePath);
+ const entities: ParsedEntity[] = [
+ { name: fileName, kind: 'file', lineStart: 1, lineEnd: sourceLineCount, language },
+ ];
+ const chunks: ParsedChunk[] = [];
+ const relationships: ParsedRelationship[] = [];
+ const lineStarts = computeLineStarts(source);
+ const lines = source.split(/\r?\n/);
+ const stripped = stripSqlComments(source);
+ const strippedLines = stripped.split(/\r?\n/);
+
+ // Matches: CREATE [OR REPLACE] [TEMP[ORARY]] [UNIQUE] <TYPE> [IF NOT EXISTS] <name>
+ const createRe =
+ /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMP(?:ORARY)?\s+)?(?:UNIQUE\s+)?(TABLE|VIEW|FUNCTION|PROCEDURE|PROC|TRIGGER|INDEX)\s+(?:IF\s+NOT\s+EXISTS\s+)?([A-Za-z0-9_.`"[\]]+)/i;
+
+ // For INDEX ... ON tableName
+ const indexOnRe = /\bON\s+([A-Za-z0-9_.`"[\]]+)/i;
+
+ let statementLines: number[] = []; // line indices (0-based) belonging to current statement
+ let currentCreate: { kind: string; name: string; lineStart: number } | null = null;
+
+ const flushStatement = (endLineIdx: number) => {
+ if (!currentCreate) return;
+ const lineEnd = endLineIdx + 1;
+ const startByte = lineStarts[currentCreate.lineStart - 1] ?? 0;
+ const endByte =
+ lineEnd < lines.length ? (lineStarts[lineEnd] ?? source.length) - 1 : source.length;
+ const statementText = strippedLines
+ .slice(currentCreate.lineStart - 1, lineEnd)
+ .join('\n');
+ const rawContent = lines.slice(currentCreate.lineStart - 1, lineEnd).join('\n');
+
+ const objType = currentCreate.kind.toUpperCase();
+ const entityKind =
+ objType === 'TABLE' ? 'table'
+ : objType === 'VIEW' ? 'view'
+ : objType === 'INDEX' ? 'config_entry'
+ : 'function'; // FUNCTION, PROCEDURE, PROC, TRIGGER
+ const chunkKind =
+ objType === 'TABLE' ? 'create_table'
+ : objType === 'VIEW' ? 'create_view'
+ : objType === 'INDEX' ? 'create_index'
+ : objType === 'TRIGGER' ? 'create_trigger'
+ : 'create_function';
+
+ entities.push({
+ name: currentCreate.name,
+ kind: entityKind,
+ lineStart: currentCreate.lineStart,
+ lineEnd,
+ language,
+ });
+ chunks.push({
+ name: currentCreate.name,
+ chunkKind,
+ lineStart: currentCreate.lineStart,
+ lineEnd,
+ startByte,
+ endByte,
+ contentHash: crypto.createHash('sha256').update(rawContent).digest('hex'),
+ language,
+ });
+ relationships.push({ srcName: fileName, dstName: currentCreate.name, predicate: 'CONTAINS' });
+
+ if (objType === 'INDEX') {
+ // REFERENCES the table the index is ON
+ const onMatch = indexOnRe.exec(statementText);
+ if (onMatch) {
+ relationships.push({
+ srcName: currentCreate.name,
+ dstName: onMatch[1].replace(/[`"[\]]/g, ''),
+ predicate: 'REFERENCES',
+ });
+ }
+ } else if (objType !== 'TABLE') {
+ // Views, functions, procedures, triggers: extract table refs from body
+ for (const ref of extractSqlTableRefs(statementText)) {
+ if (ref !== currentCreate.name) {
+ relationships.push({ srcName: currentCreate.name, dstName: ref, predicate: 'REFERENCES' });
+ }
+ }
+ }
+
+ currentCreate = null;
+ };
+
+ for (let i = 0; i < strippedLines.length; i++) {
+ const line = strippedLines[i];
+
+ if (!currentCreate) {
+ const m = createRe.exec(line);
+ if (m) {
+ currentCreate = {
+ kind: m[1],
+ name: m[2].replace(/[`"[\]]/g, ''),
+ lineStart: i + 1,
+ };
+ }
+ }
+
+ if (currentCreate && /;/.test(line)) {
+ flushStatement(i);
+ }
+ }
+
+ if (chunks.length === 0) {
+ chunks.push({
+ name: null,
+ chunkKind: 'file_body',
+ lineStart: 1,
+ lineEnd: Math.max(sourceLineCount, 1),
+ startByte: 0,
+ endByte: source.length,
+ contentHash: crypto.createHash('sha256').update(source).digest('hex'),
+ language,
+ });
+ }
+
+ return { filePath, language, entities, chunks, relationships, fileRole };
+}
+
// ---------------------------------------------------------------------------
// Rust: cfg macro unwrapping
// ---------------------------------------------------------------------------
@@ -606,6 +756,7 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
if (!language) return null;
if (language === SupportedLanguages.YAML) return parseYamlFile(filePath, source);
if (language === SupportedLanguages.Dockerfile) return parseDockerfileFile(filePath, source);
+ if (language === SupportedLanguages.SQL) return parseSqlFile(filePath, source);
// TypeScript TSX uses a separate grammar
const isTsx = filePath.endsWith('.tsx');
diff --git a/core-ingestion/src/languages.ts b/core-ingestion/src/languages.ts
index 0d7a6822..35117828 100644
--- a/core-ingestion/src/languages.ts
+++ b/core-ingestion/src/languages.ts
@@ -15,6 +15,7 @@ export enum SupportedLanguages {
Scala = 'scala',
YAML = 'yaml',
Dockerfile = 'dockerfile',
+ SQL = 'sql',
}
const EXT_MAP: Record<string, SupportedLanguages> = {
@@ -45,6 +46,7 @@ const EXT_MAP: Record<string, SupportedLanguages> = {
'.yaml': SupportedLanguages.YAML,
'.yml': SupportedLanguages.YAML,
'.dockerfile': SupportedLanguages.Dockerfile,
+ '.sql': SupportedLanguages.SQL,
};
export function languageFromPath(filePath: string): SupportedLanguages | null {
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
index afd0fd55..9f423a4c 100644
--- a/core-ingestion/src/queries.ts
+++ b/core-ingestion/src/queries.ts
@@ -1181,5 +1181,6 @@ export const LANGUAGE_QUERIES: Record<SupportedLanguages, string> = {
[SupportedLanguages.Scala]: SCALA_QUERIES,
[SupportedLanguages.YAML]: '',
[SupportedLanguages.Dockerfile]: '',
+ [SupportedLanguages.SQL]: '',
};
diff --git a/core-ingestion/tsconfig-prod.json b/core-ingestion/tsconfig-prod.json
new file mode 100644
index 00000000..06ba3aed
--- /dev/null
+++ b/core-ingestion/tsconfig-prod.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "esModuleInterop": true,
+ "declaration": true,
+ "skipLibCheck": true,
+ "typeRoots": ["../ix-cli/node_modules/@types"]
+ },
+ "include": ["src"],
+ "exclude": ["src/__tests__"]
+}
diff --git a/docker-compose.standalone.yml b/docker-compose.standalone.yml
index bf417771..a6734a18 100644
--- a/docker-compose.standalone.yml
+++ b/docker-compose.standalone.yml
@@ -31,7 +31,10 @@ services:
ports:
- "127.0.0.1:8090:8090"
volumes:
- - ${IX_HOST_MOUNT_ROOT:-${HOME}}:${IX_HOST_MOUNT_ROOT:-${HOME}}:ro
+ - type: bind
+ source: ${IX_HOST_MOUNT_ROOT:-$HOME}
+ target: ${IX_CONTAINER_MOUNT_ROOT:-$HOME}
+ read_only: true
environment:
ARANGO_HOST: arangodb
ARANGO_PORT: "8529"
diff --git a/docker-compose.yml b/docker-compose.yml
index e40e5e51..f851361c 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -24,7 +24,10 @@ services:
ports:
- "127.0.0.1:8090:8090"
volumes:
- - ${IX_HOST_MOUNT_ROOT:-${DOCKER_HOME:-$HOME}}:${IX_HOST_MOUNT_ROOT:-${DOCKER_HOME:-$HOME}}:ro
+ - type: bind
+ source: ${IX_HOST_MOUNT_ROOT:-$HOME}
+ target: ${IX_CONTAINER_MOUNT_ROOT:-$HOME}
+ read_only: true
environment:
ARANGO_HOST: arangodb
ARANGO_PORT: "8529"
diff --git a/ix-cli/package-lock.json b/ix-cli/package-lock.json
index 4a54ccf5..ccd24475 100644
--- a/ix-cli/package-lock.json
+++ b/ix-cli/package-lock.json
@@ -6,7 +6,7 @@
"packages": {
"": {
"name": "@ix/cli",
- "version": "0.4.8",
+ "version": "0.5.0",
"dependencies": {
"chalk": "^5.3.0",
"commander": "^12.0.0",
@@ -854,6 +854,7 @@
"integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"undici-types": "~6.21.0"
}
diff --git a/ix-cli/src/cli/__tests__/resolver-type-preference.test.ts b/ix-cli/src/cli/__tests__/resolver-type-preference.test.ts
new file mode 100644
index 00000000..60c0ea1c
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/resolver-type-preference.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveEntityFull } from '../resolve.js';
+
+describe('resolver type preference', () => {
+ it('prefers a class declaration over same-named method candidates for PascalCase symbols', async () => {
+ const client = {
+ async search() {
+ return [
+ {
+ id: 'method-node',
+ kind: 'method',
+ name: 'RobustSolver',
+ provenance: { sourceUri: '/repo/src/RobustSolver.cpp' },
+ },
+ {
+ id: 'class-node',
+ kind: 'class',
+ name: 'RobustSolver',
+ provenance: { sourceUri: '/repo/include/RobustSolver.h' },
+ },
+ ];
+ },
+ };
+
+ const result = await resolveEntityFull(client as any, 'RobustSolver', [
+ 'file',
+ 'class',
+ 'object',
+ 'trait',
+ 'interface',
+ 'module',
+ 'method',
+ 'function',
+ ]);
+
+ expect(result.resolved).toBe(true);
+ if (result.resolved) {
+ expect(result.entity.id).toBe('class-node');
+ expect(result.entity.kind).toBe('class');
+ }
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/trace-path.test.ts b/ix-cli/src/cli/__tests__/trace-path.test.ts
new file mode 100644
index 00000000..15925663
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/trace-path.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+
+import { findPath } from '../commands/trace.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/** Build a mock IxClient.expand that returns neighbours keyed by (id, direction). */
+function makeClient(edges: Record<string, Record<string, Array<{ id: string; name: string; kind: string }>>>) {
+ return {
+ async expand(id: string, opts?: { direction?: string }) {
+ const direction = opts?.direction ?? 'out';
+ return { nodes: edges[id]?.[direction] ?? [], edges: [] };
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Existing: inbound-edge traversal
+// ---------------------------------------------------------------------------
+
+describe('trace path search', () => {
+ it('finds a route through inbound edges when the connection is reversed from the starting node', async () => {
+ const client = {
+ async expand(id: string, opts?: { direction?: string }) {
+ const direction = opts?.direction ?? 'both';
+ if (id === 'pcm-file' && direction === 'out') {
+ return { nodes: [{ id: 'graph-utils-file', name: 'GraphUtils.h', kind: 'file' }], edges: [] };
+ }
+ if (id === 'graph-utils-file' && direction === 'in') {
+ return { nodes: [{ id: 'pcm-file', name: 'Pcm.h', kind: 'file' }], edges: [] };
+ }
+ return { nodes: [], edges: [] };
+ },
+ };
+
+ const path = await findPath(client as any, 'graph-utils-file', 'pcm-file', ['IMPORTS'], 4);
+
+ expect(path).toEqual([
+ { id: 'graph-utils-file', name: '', kind: '' },
+ { id: 'pcm-file', name: 'Pcm.h', kind: 'file' },
+ ]);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 1-hop: map.ts → ingest.ts
+//
+// map.ts calls ingestFiles imported from ingest.ts — a direct IMPORTS edge.
+// Manually verified: ix-cli/src/cli/commands/map.ts line 7
+// import { ingestFiles } from "./ingest.js";
+// ---------------------------------------------------------------------------
+
+describe('one-hop import path', () => {
+ it('map.ts → ingest.ts: direct IMPORTS edge', async () => {
+ const client = makeClient({
+ 'map-ts': {
+ out: [{ id: 'ingest-ts', name: 'ingest.ts', kind: 'file' }],
+ in: [],
+ },
+ 'ingest-ts': { out: [], in: [] },
+ });
+
+ const path = await findPath(client as any, 'map-ts', 'ingest-ts', ['IMPORTS'], 4);
+
+ expect(path).not.toBeNull();
+ expect(path).toHaveLength(2);
+ expect(path![0]).toEqual({ id: 'map-ts', name: '', kind: '' });
+ expect(path![1]).toMatchObject({ id: 'ingest-ts', name: 'ingest.ts', kind: 'file' });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 2-hop: oss.ts → trace.ts → depends.ts
+//
+// Manually verified import chain:
+// ix-cli/src/cli/register/oss.ts:
+// import { registerTraceCommand } from "../commands/trace.js";
+// ix-cli/src/cli/commands/trace.ts:
+// import { buildDependencyTree } from "./depends.js";
+// ---------------------------------------------------------------------------
+
+describe('two-hop import path', () => {
+ it('oss.ts → trace.ts → depends.ts: two-hop IMPORTS chain', async () => {
+ const client = makeClient({
+ 'oss-ts': {
+ out: [{ id: 'trace-ts', name: 'trace.ts', kind: 'file' }],
+ in: [],
+ },
+ 'trace-ts': {
+ out: [{ id: 'depends-ts', name: 'depends.ts', kind: 'file' }],
+ in: [{ id: 'oss-ts', name: 'oss.ts', kind: 'file' }],
+ },
+ 'depends-ts': { out: [], in: [] },
+ });
+
+ const path = await findPath(client as any, 'oss-ts', 'depends-ts', ['IMPORTS'], 5);
+
+ expect(path).not.toBeNull();
+ expect(path).toHaveLength(3);
+ expect(path!.map(n => n.id)).toEqual(['oss-ts', 'trace-ts', 'depends-ts']);
+ expect(path![1]).toMatchObject({ id: 'trace-ts', name: 'trace.ts', kind: 'file' });
+ expect(path![2]).toMatchObject({ id: 'depends-ts', name: 'depends.ts', kind: 'file' });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// No path: disconnected files return null
+//
+// parse-pool.ts has no import relationship with api.ts — they are independent
+// modules. A search between them should exhaust the graph and return null.
+// ---------------------------------------------------------------------------
+
+describe('no path between disconnected files', () => {
+ it('parse-pool.ts ↔ api.ts: returns null when no route exists', async () => {
+ const client = makeClient({
+ 'parse-pool-ts': {
+ out: [{ id: 'node-worker-threads', name: 'worker_threads', kind: 'module' }],
+ in: [{ id: 'ingest-ts', name: 'ingest.ts', kind: 'file' }],
+ },
+ 'node-worker-threads': { out: [], in: [] },
+ 'ingest-ts': { out: [], in: [] },
+ 'api-ts': { out: [], in: [] },
+ });
+
+ const path = await findPath(client as any, 'parse-pool-ts', 'api-ts', ['IMPORTS'], 6);
+
+ expect(path).toBeNull();
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index e044b0de..9320a6f7 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -118,7 +118,7 @@ export function registerCallersCommand(program: Command): void {
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
direction: "out",
- predicates: ["CALLS"],
+ predicates: ["CALLS", "REFERENCES"],
});
formatEdgeResults(result.nodes.slice(0, calleeLimit), "callees", target.name, opts.format, target, "graph");
});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index bdc48d9f..e35ef430 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -34,6 +34,7 @@ const SUPPORTED_EXTENSIONS = new Set([
'.scala', '.sc',
'.yaml', '.yml',
'.dockerfile',
+ '.sql',
]);
export function isSupportedSourceFile(filePath: string): boolean {
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 130c8c8f..b1e6f0d6 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -109,14 +109,26 @@ export function registerLocateCommand(program: Command): void {
};
}
+ // Sub-file entities (table, view, function, etc.) have no IN_REGION edges of their
+ // own — those belong to the containing file. Walk up via CONTAINS to inherit the
+ // parent file's system path so hasMapData returns true after `ix map`.
+ let effectiveSystemPath = systemPath;
+ if (!hasMapData(systemPath) && !isContainer && containsResult.nodes.length > 0) {
+ const parentFile = containsResult.nodes[0] as any;
+ if (parentFile?.id) {
+ const parentPath = await getSystemPath(client, parentFile.id);
+ if (hasMapData(parentPath)) effectiveSystemPath = parentPath;
+ }
+ }
+
// Diagnostic for missing map data
- const hasMap = hasMapData(systemPath);
+ const hasMap = hasMapData(effectiveSystemPath);
if (!hasMap) {
diagnostics.push("No system map. Run `ix map` to see hierarchy.");
}
// Build system path: append resolved symbol for non-file targets
- let systemPathMapped = systemPath.map((n) => ({ name: n.name, kind: n.kind }));
+ let systemPathMapped = effectiveSystemPath.map((n) => ({ name: n.name, kind: n.kind }));
if (!isFile) {
const lastInPath = systemPathMapped[systemPathMapped.length - 1];
if (!lastInPath || lastInPath.name !== target.name) {
diff --git a/ix-cli/src/cli/hierarchy.ts b/ix-cli/src/cli/hierarchy.ts
index b9cde020..e95abe70 100644
--- a/ix-cli/src/cli/hierarchy.ts
+++ b/ix-cli/src/cli/hierarchy.ts
@@ -7,7 +7,7 @@ const REGION_KINDS = new Set(["system", "subsystem", "module", "region"]);
/** Traverse IN_REGION edges upward to build the system-hierarchy path for a node. */
export async function getSystemPath(client: IxClient, nodeId: string): Promise<SystemPath> {
try {
- const result = await client.expand(nodeId, { direction: "out", predicates: ["IN_REGION"], hops: 5 });
+ const result = await client.expand(nodeId, { direction: "in", predicates: ["IN_REGION"], hops: 5 });
const nodes = result.nodes as Array<{ id: string; name?: string; attrs?: { name?: string }; kind?: string }>;
if (nodes.length === 0) return [];
// Sort by region kind: system > subsystem > module > region > file
@@ -55,7 +55,7 @@ export async function bucketByHierarchy(
const memberName = node.name || node.attrs?.name || "(unnamed)";
const memberKind = node.kind || "unknown";
- const regionResult = await client.expand(nodeId, { direction: "out", predicates: ["IN_REGION"], hops: 1 });
+ const regionResult = await client.expand(nodeId, { direction: "in", predicates: ["IN_REGION"], hops: 1 });
const regionNodes = regionResult.nodes as Array<{ id: string; name?: string; attrs?: { name?: string }; kind?: string }>;
// Pick the most specific region (lowest in hierarchy)
diff --git a/memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala b/memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala
index 6c3a161a..3a2b8aa8 100644
--- a/memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala
+++ b/memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala
@@ -103,8 +103,13 @@ class BulkWriteApi(client: ArangoClient) {
// Skip tombstone/retire on first ingest — DB is empty, no existing docs to update.
tombstoneAndRetireMs <-
if (skipTombstone || baseRev == 0) IO.pure((0L, 0L))
- else timedUnit(tombstoneExistingNodes(logicalIds, newRev))
- .both(timedUnit(retireOldClaims(fileBatches, newRev)))
+ else {
+ val sourceUris = fileBatches.map(_.filePath)
+ timedUnit(tombstoneExistingNodes(logicalIds, newRev))
+ .both(timedUnit(tombstoneExistingEdges(sourceUris, newRev)))
+ .both(timedUnit(retireOldClaims(fileBatches, newRev)))
+ .map { case ((nodesMs, edgesMs), claimsMs) => (nodesMs + edgesMs, claimsMs) }
+ }
(tombstoneMs: Long, retireClaimsMs: Long) = tombstoneAndRetireMs
// Run all four collection inserts concurrently — they write to independent collections
// with no referential-integrity enforcement between them. Wall time drops from the
@@ -151,6 +156,31 @@ class BulkWriteApi(client: ArangoClient) {
}
}
+ // Tombstone all active edges whose provenance.source_uri matches a re-ingested file.
+ // Without this, edges removed from the parse output (e.g. a decorator CALLS edge that
+ // was fixed) persist in the graph indefinitely, since UpsertEdge only updates edges
+ // that still exist in the new parse — it never deletes edges that were dropped.
+ // The subsequent bulkInsertEdges (overwriteMode=replace) will un-tombstone any edges
+ // that still exist in the new parse, so only genuinely removed edges remain tombstoned.
+ private def tombstoneExistingEdges(sourceUris: Vector[String], newRev: Long): IO[Unit] = {
+ if (sourceUris.isEmpty) IO.unit
+ else {
+ val uriList = new java.util.ArrayList[String](sourceUris.size)
+ sourceUris.distinct.foreach(uriList.add)
+ client.execute(
+ """FOR e IN edges
+ | FILTER e.provenance.source_uri IN @uris
+ | AND e.deleted_rev == null
+ | UPDATE e WITH { deleted_rev: @rev, updated_at: @now } IN edges""".stripMargin,
+ Map(
+ "uris" -> uriList.asInstanceOf[AnyRef],
+ "rev" -> Long.box(newRev).asInstanceOf[AnyRef],
+ "now" -> Instant.now().toString.asInstanceOf[AnyRef]
+ )
+ )
+ }
+ }
+
private def retireOldClaimsByEntityIds(entityIds: Seq[String], newRev: Long): IO[Unit] =
if (entityIds.isEmpty) IO.unit
else {
@@ -207,12 +237,14 @@ class BulkWriteApi(client: ArangoClient) {
val allIds = fileBatches.flatMap(_.patch.ops.collect {
case PatchOp.UpsertNode(id, _, _, _) => id.value.toString
}).distinct
+ val sourceUris = fileBatches.map(_.filePath)
val preTombRev = baseRev + 1L
timedUnit(tombstoneExistingNodes(allIds.toVector, preTombRev))
+ .both(timedUnit(tombstoneExistingEdges(sourceUris, preTombRev)))
.both(timedUnit(retireOldClaimsByEntityIds(allIds, preTombRev)))
- .flatMap { case (tombMs, retireMs) =>
+ .flatMap { case ((tombMs, edgeTombMs), retireMs) =>
if (debugBulkWrites)
- logger.info(s"[bulk-write] pre-tombstone files=${fileBatches.size} tombstoneMs=$tombMs retireMs=$retireMs")
+ logger.info(s"[bulk-write] pre-tombstone files=${fileBatches.size} tombstoneMs=$tombMs edgeTombMs=$edgeTombMs retireMs=$retireMs")
else IO.unit
}
}
diff --git a/memory-layer/src/main/scala/ix/memory/model/Node.scala b/memory-layer/src/main/scala/ix/memory/model/Node.scala
index 49f449e2..48fdf031 100644
--- a/memory-layer/src/main/scala/ix/memory/model/Node.scala
+++ b/memory-layer/src/main/scala/ix/memory/model/Node.scala
@@ -30,6 +30,8 @@ object NodeKind {
case object Region extends NodeKind
case object Chunk extends NodeKind
case object Macro extends NodeKind
+ case object Table extends NodeKind
+ case object View extends NodeKind
private val nameMap: Map[String, NodeKind] = Map(
"module" -> Module,
@@ -54,7 +56,9 @@ object NodeKind {
"goal" -> Goal,
"region" -> Region,
"chunk" -> Chunk,
- "macro" -> Macro
+ "macro" -> Macro,
+ "table" -> Table,
+ "view" -> View
)
implicit val encoder: Encoder[NodeKind] = Encoder[String].contramap {
@@ -81,6 +85,8 @@ object NodeKind {
case Region => "region"
case Chunk => "chunk"
case Macro => "macro"
+ case Table => "table"
+ case View => "view"
}
implicit val decoder: Decoder[NodeKind] = Decoder[String].emap { s =>
diff --git a/scripts/backend.sh b/scripts/backend.sh
index 3fd429af..60006d87 100755
--- a/scripts/backend.sh
+++ b/scripts/backend.sh
@@ -21,15 +21,24 @@ set -euo pipefail
IX_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$IX_DIR"
-# On Windows/MINGW, Docker (a Windows binary) receives paths via MINGW's
-# auto-conversion, which turns /c/Users/foo into C:\Users\foo — the drive
-# letter colon then breaks Docker's source:target:options mount syntax.
-# Prefixing with an extra / (//c/Users/foo) suppresses MINGW conversion so
-# the path reaches Docker Desktop as-is, which it maps correctly.
+# On Windows/MINGW, Docker Compose (a Windows binary) can mix POSIX and Windows
+# home paths if we rely on nested interpolation defaults in the compose file.
+# Export both sides of the bind mount explicitly instead:
+# IX_HOST_MOUNT_ROOT → host bind source (cygpath -m: C:/Users/...)
+# IX_CONTAINER_MOUNT_ROOT → container target ($HOME: /c/Users/... or /Users/...)
+# The dc() helper passes -f with a Windows-format path so docker compose can
+# locate its file regardless of how it resolves the CWD from a MINGW shell.
if [[ "$(uname -s)" =~ MINGW|MSYS|CYGWIN ]]; then
- export DOCKER_HOME="/${HOME}"
+ export IX_HOST_MOUNT_ROOT="$(cygpath -m "$HOME")"
+ export IX_CONTAINER_MOUNT_ROOT="${HOME}"
+ dc() {
+ MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' \
+ docker compose -f "$(cygpath -m "$IX_DIR/docker-compose.yml")" "$@"
+ }
else
- export DOCKER_HOME="${HOME}"
+ export IX_HOST_MOUNT_ROOT="${HOME}"
+ export IX_CONTAINER_MOUNT_ROOT="${HOME}"
+ dc() { docker compose "$@"; }
fi
JAR_PATH="memory-layer/target/scala-2.13/ix-memory-layer.jar"
@@ -140,7 +149,7 @@ is_healthy() {
containers_running() {
# Check if both containers are running via docker compose
local running
- running=$(docker compose ps --status running --format json 2>/dev/null | wc -l)
+ running=$(dc ps --status running --format json 2>/dev/null | wc -l)
[ "$running" -ge 2 ]
}
@@ -162,20 +171,20 @@ case "${1:-up}" in
# If containers are running but not healthy, restart them
if containers_running; then
echo "Containers are running but not healthy — restarting..."
- docker compose restart
+ dc restart
else
echo "Starting backend services..."
- docker compose up -d --build
+ dc up -d --build
fi
wait_for_health
;;
down)
- docker compose down
+ dc down
echo "[ok] Backend stopped."
;;
status)
- docker compose ps
+ dc ps
echo ""
if is_healthy; then
echo "[ok] Backend is healthy"
@@ -184,17 +193,17 @@ case "${1:-up}" in
fi
;;
logs)
- docker compose logs -f
+ dc logs -f
;;
clean)
- docker compose down -v
+ dc down -v
echo "[ok] Backend stopped and data volumes removed."
;;
rebuild)
ensure_docker
build_jar true
echo "Rebuilding and starting backend..."
- docker compose up -d --build
+ dc up -d --build
wait_for_health
;;
check)
diff --git a/scripts/dev/shutdown.sh b/scripts/dev/shutdown.sh
index fe64b067..c56aa476 100755
--- a/scripts/dev/shutdown.sh
+++ b/scripts/dev/shutdown.sh
@@ -18,6 +18,19 @@ set -euo pipefail
IX_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$IX_DIR"
+if [[ "$(uname -s)" =~ MINGW|MSYS|CYGWIN ]]; then
+ export IX_HOST_MOUNT_ROOT="$(cygpath -m "$HOME")"
+ export IX_CONTAINER_MOUNT_ROOT="${HOME}"
+ dc() {
+ MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' \
+ docker compose -f "$(cygpath -m "$IX_DIR/docker-compose.yml")" "$@"
+ }
+else
+ export IX_HOST_MOUNT_ROOT="${HOME}"
+ export IX_CONTAINER_MOUNT_ROOT="${HOME}"
+ dc() { docker compose -f "$IX_DIR/docker-compose.yml" "$@"; }
+fi
+
CLEAN=false
DISCONNECT_PROJECTS=()
@@ -108,10 +121,10 @@ elif ! docker info &> /dev/null 2>&1; then
echo " [ok] Docker not running, nothing to stop"
else
if [ "$CLEAN" = true ]; then
- docker compose -f "$IX_DIR/docker-compose.yml" down -v 2>&1 | sed 's/^/ /'
+ dc down -v 2>&1 | sed 's/^/ /'
echo " [ok] Containers stopped and data volumes removed"
else
- docker compose -f "$IX_DIR/docker-compose.yml" down 2>&1 | sed 's/^/ /'
+ dc down 2>&1 | sed 's/^/ /'
echo " [ok] Containers stopped (data preserved)"
fi
fi
diff --git a/scripts/install/install.sh b/scripts/install/install.sh
index 412c548c..387c0d12 100755
--- a/scripts/install/install.sh
+++ b/scripts/install/install.sh
@@ -31,6 +31,18 @@ ARANGO_URL="http://localhost:8529/_api/version"
NODE_MIN_MAJOR=18
+if [[ "$(uname -s)" =~ MINGW|MSYS|CYGWIN ]]; then
+ export IX_HOST_MOUNT_ROOT="$(cygpath -m "$HOME")"
+ export IX_CONTAINER_MOUNT_ROOT="${HOME}"
+ dc() {
+ MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' docker compose "$@"
+ }
+else
+ export IX_HOST_MOUNT_ROOT="${HOME}"
+ export IX_CONTAINER_MOUNT_ROOT="${HOME}"
+ dc() { docker compose "$@"; }
+fi
+
# Pick a bin dir that's already in PATH and writable
pick_bin_dir() {
# Prefer /usr/local/bin (already in PATH everywhere)
@@ -341,7 +353,7 @@ else
info "Downloaded docker-compose.yml"
printf " Starting backend services (this may take a minute on first run)..."
- docker compose -f "$COMPOSE_DIR/docker-compose.yml" up -d --pull always < /dev/null >/dev/null 2>&1 &
+ dc -f "$COMPOSE_DIR/docker-compose.yml" up -d --pull always < /dev/null >/dev/null 2>&1 &
DOCKER_PID=$!
while kill -0 "$DOCKER_PID" 2>/dev/null; do
printf "."