From 9d04c4443a7b0892548868fe04e59f9a35e43dcf Mon Sep 17 00:00:00 2001 From: "jason.ma" Date: Mon, 13 Apr 2026 20:38:29 +0800 Subject: [PATCH 1/2] feat: support global config fallback and configurable batch size - loadConfig: fall back to ~/.claude/arch (or SOCRATICODE_GLOBAL_CONFIG_DIR env var) when project root has no .socraticodecontextartifacts.json - BATCH_SIZE: configurable via EMBEDDING_BATCH_SIZE env var, default 32 (validates positive integer, throws on invalid input) --- src/services/context-artifacts.ts | 16 ++++++++++++++-- src/services/embeddings.ts | 14 +++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/services/context-artifacts.ts b/src/services/context-artifacts.ts index f833a12..d44950a 100644 --- a/src/services/context-artifacts.ts +++ b/src/services/context-artifacts.ts @@ -17,6 +17,7 @@ import { createHash } from "node:crypto"; import fsp from "node:fs/promises"; +import os from "node:os"; import path from "node:path"; import { glob } from "glob"; import { contextCollectionName, projectIdFromPath } from "../config.js"; @@ -52,14 +53,25 @@ export interface SocratiCodeConfig { */ export async function loadConfig(projectPath: string): Promise { const configPath = path.join(path.resolve(projectPath), CONFIG_FILENAME); + // Fall back to a global config location when no project-level config exists. + // Configurable via env var SOCRATICODE_GLOBAL_CONFIG_DIR; defaults to ~/.claude/arch. + const globalConfigDir = + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR || path.join(os.homedir(), ".claude", "arch"); + const globalConfigPath = path.join(globalConfigDir, CONFIG_FILENAME); + let actualPath = configPath; try { await fsp.access(configPath); } catch { - return null; // file doesn't exist — that's fine + try { + await fsp.access(globalConfigPath); + actualPath = globalConfigPath; + } catch { + return null; // neither project nor global file exists — that's fine + } } - const raw = await fsp.readFile(configPath, "utf-8"); + const raw = await fsp.readFile(actualPath, "utf-8"); let parsed: unknown; try { parsed = JSON.parse(raw); diff --git a/src/services/embeddings.ts b/src/services/embeddings.ts index 7689b42..f8eb342 100644 --- a/src/services/embeddings.ts +++ b/src/services/embeddings.ts @@ -5,7 +5,19 @@ import { getEmbeddingConfig } from "./embedding-config.js"; import { getEmbeddingProvider } from "./embedding-provider.js"; import { logger } from "./logger.js"; -const BATCH_SIZE = 32; // Number of texts to embed per provider request +// Number of texts to embed per provider request. +// Configurable via env var EMBEDDING_BATCH_SIZE (positive integer); defaults to 32. +const BATCH_SIZE: number = (() => { + const raw = process.env.EMBEDDING_BATCH_SIZE; + if (!raw) return 32; + const parsed = Number.parseInt(raw, 10); + if (!Number.isFinite(parsed) || parsed <= 0) { + throw new Error( + `Invalid EMBEDDING_BATCH_SIZE: "${raw}". Must be a positive integer.`, + ); + } + return parsed; +})(); const MAX_RETRIES = 3; const BASE_DELAY_MS = 500; From 49b5b35bff2809c17f1096cb62db7670503594aa Mon Sep 17 00:00:00 2001 From: "jason.ma" Date: Tue, 14 Apr 2026 19:12:44 +0800 Subject: [PATCH 2/2] fix: resolve relative paths for global config fallback and strict batch size validation 1. Global config fallback: relative artifact paths are now resolved against the global config directory (not the project root) when loading from fallback. Absolute paths are left unchanged. Project-level config behavior is unaffected. 2. EMBEDDING_BATCH_SIZE: replaced Number.parseInt with Number() + Number.isInteger() so that inputs like "64abc", "1.5", and "" are correctly rejected instead of silently accepted. Co-Authored-By: Claude Opus 4.6 (1M context) --- src/services/context-artifacts.ts | 13 +++ src/services/embeddings.ts | 8 +- tests/unit/context-artifacts.test.ts | 127 +++++++++++++++++++++++- tests/unit/embedding-batch-size.test.ts | 61 ++++++++++++ 4 files changed, 203 insertions(+), 6 deletions(-) create mode 100644 tests/unit/embedding-batch-size.test.ts diff --git a/src/services/context-artifacts.ts b/src/services/context-artifacts.ts index d44950a..f68a804 100644 --- a/src/services/context-artifacts.ts +++ b/src/services/context-artifacts.ts @@ -59,6 +59,7 @@ export async function loadConfig(projectPath: string): Promise ({ + ...artifact, + path: path.isAbsolute(artifact.path) ? artifact.path : path.resolve(baseDir, artifact.path), + })); + } + return config as SocratiCodeConfig; } diff --git a/src/services/embeddings.ts b/src/services/embeddings.ts index f8eb342..01d89ca 100644 --- a/src/services/embeddings.ts +++ b/src/services/embeddings.ts @@ -9,14 +9,14 @@ import { logger } from "./logger.js"; // Configurable via env var EMBEDDING_BATCH_SIZE (positive integer); defaults to 32. const BATCH_SIZE: number = (() => { const raw = process.env.EMBEDDING_BATCH_SIZE; - if (!raw) return 32; - const parsed = Number.parseInt(raw, 10); - if (!Number.isFinite(parsed) || parsed <= 0) { + if (raw === undefined) return 32; + const num = Number(raw); + if (!Number.isInteger(num) || num <= 0) { throw new Error( `Invalid EMBEDDING_BATCH_SIZE: "${raw}". Must be a positive integer.`, ); } - return parsed; + return num; })(); const MAX_RETRIES = 3; const BASE_DELAY_MS = 500; diff --git a/tests/unit/context-artifacts.test.ts b/tests/unit/context-artifacts.test.ts index 8b9d662..c1af8e7 100644 --- a/tests/unit/context-artifacts.test.ts +++ b/tests/unit/context-artifacts.test.ts @@ -42,8 +42,19 @@ async function createTempProject( describe("loadConfig", () => { it("returns null when no .socraticodecontextartifacts.json exists", async () => { const projectDir = await createTempProject({ "README.md": "# Hello" }); - const config = await loadConfig(projectDir); - expect(config).toBeNull(); + // Point global fallback to a non-existent directory so we only test project-level + const originalEnv = process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = path.join(tempDir, "nonexistent-global"); + try { + const config = await loadConfig(projectDir); + expect(config).toBeNull(); + } finally { + if (originalEnv === undefined) { + delete process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + } else { + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = originalEnv; + } + } }); it("parses a valid .socraticodecontextartifacts.json", async () => { @@ -146,6 +157,118 @@ describe("loadConfig", () => { await expect(loadConfig(projectDir)).rejects.toThrow("description must be a non-empty string"); }); + it("falls back to global config when project-level config is absent", async () => { + const projectDir = await createTempProject({ "README.md": "# Hello" }); + // Create a global config directory with a config file + const globalDir = path.join(tempDir, `global-${Date.now()}`); + await fsp.mkdir(globalDir, { recursive: true }); + await fsp.writeFile( + path.join(globalDir, ".socraticodecontextartifacts.json"), + JSON.stringify({ + artifacts: [ + { name: "shared-schema", path: "./shared/schema.sql", description: "Shared DB schema" }, + ], + }), + ); + + // Override the env var to point to our temp global dir + const originalEnv = process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = globalDir; + try { + const config = await loadConfig(projectDir); + expect(config).not.toBeNull(); + expect(config?.artifacts).toHaveLength(1); + expect(config?.artifacts?.[0].name).toBe("shared-schema"); + } finally { + if (originalEnv === undefined) { + delete process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + } else { + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = originalEnv; + } + } + }); + + it("resolves relative artifact paths against global config dir when using fallback", async () => { + const projectDir = await createTempProject({ "README.md": "# Hello" }); + const globalDir = path.join(tempDir, `global-resolve-${Date.now()}`); + await fsp.mkdir(globalDir, { recursive: true }); + await fsp.writeFile( + path.join(globalDir, ".socraticodecontextartifacts.json"), + JSON.stringify({ + artifacts: [ + { name: "relative-art", path: "docs/schema.sql", description: "Relative path artifact" }, + { name: "absolute-art", path: "/absolute/path/schema.sql", description: "Absolute path artifact" }, + ], + }), + ); + + const originalEnv = process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = globalDir; + try { + const config = await loadConfig(projectDir); + expect(config).not.toBeNull(); + // Relative path should be resolved against globalDir, not projectDir + expect(path.isAbsolute(config!.artifacts![0].path)).toBe(true); + expect(config!.artifacts![0].path).toBe(path.resolve(globalDir, "docs/schema.sql")); + // Absolute path should remain unchanged + expect(config!.artifacts![1].path).toBe("/absolute/path/schema.sql"); + } finally { + if (originalEnv === undefined) { + delete process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + } else { + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = originalEnv; + } + } + }); + + it("does NOT resolve relative paths when using project-level config", async () => { + const projectDir = await createTempProject({ + ".socraticodecontextartifacts.json": JSON.stringify({ + artifacts: [ + { name: "local-schema", path: "./schema.sql", description: "Local schema" }, + ], + }), + }); + const config = await loadConfig(projectDir); + expect(config).not.toBeNull(); + // Project-level config should keep relative paths as-is (resolved downstream) + expect(config!.artifacts![0].path).toBe("./schema.sql"); + }); + + it("prefers project-level config over global config", async () => { + const globalDir = path.join(tempDir, `global-priority-${Date.now()}`); + await fsp.mkdir(globalDir, { recursive: true }); + await fsp.writeFile( + path.join(globalDir, ".socraticodecontextartifacts.json"), + JSON.stringify({ + artifacts: [ + { name: "global-schema", path: "./global.sql", description: "Global" }, + ], + }), + ); + const projectDir = await createTempProject({ + ".socraticodecontextartifacts.json": JSON.stringify({ + artifacts: [ + { name: "project-schema", path: "./project.sql", description: "Project" }, + ], + }), + }); + + const originalEnv = process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = globalDir; + try { + const config = await loadConfig(projectDir); + expect(config).not.toBeNull(); + expect(config?.artifacts?.[0].name).toBe("project-schema"); + } finally { + if (originalEnv === undefined) { + delete process.env.SOCRATICODE_GLOBAL_CONFIG_DIR; + } else { + process.env.SOCRATICODE_GLOBAL_CONFIG_DIR = originalEnv; + } + } + }); + it("throws on duplicate artifact names (case-insensitive)", async () => { const projectDir = await createTempProject({ ".socraticodecontextartifacts.json": JSON.stringify({ diff --git a/tests/unit/embedding-batch-size.test.ts b/tests/unit/embedding-batch-size.test.ts new file mode 100644 index 0000000..befd641 --- /dev/null +++ b/tests/unit/embedding-batch-size.test.ts @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Giancarlo Erra - Altaire Limited + +import { describe, expect, it } from "vitest"; + +/** + * BATCH_SIZE is evaluated at module load time via an IIFE, so we can't + * re-import with different env vars in the same process. Instead we test + * the validation logic directly — this is the exact same code used in + * src/services/embeddings.ts. + */ +function parseBatchSize(raw: string | undefined): number { + if (raw === undefined) return 32; + const num = Number(raw); + if (!Number.isInteger(num) || num <= 0) { + throw new Error( + `Invalid EMBEDDING_BATCH_SIZE: "${raw}". Must be a positive integer.`, + ); + } + return num; +} + +describe("EMBEDDING_BATCH_SIZE validation", () => { + it("returns default 32 when env var is undefined", () => { + expect(parseBatchSize(undefined)).toBe(32); + }); + + it("accepts a valid positive integer string", () => { + expect(parseBatchSize("64")).toBe(64); + expect(parseBatchSize("1")).toBe(1); + expect(parseBatchSize("128")).toBe(128); + }); + + it("rejects trailing non-digit chars like '64abc' (Number.parseInt would accept this)", () => { + expect(() => parseBatchSize("64abc")).toThrow("EMBEDDING_BATCH_SIZE"); + }); + + it("rejects float-like string '1.5' (Number.parseInt would truncate to 1)", () => { + expect(() => parseBatchSize("1.5")).toThrow("EMBEDDING_BATCH_SIZE"); + }); + + it("rejects zero", () => { + expect(() => parseBatchSize("0")).toThrow("EMBEDDING_BATCH_SIZE"); + }); + + it("rejects negative values", () => { + expect(() => parseBatchSize("-5")).toThrow("EMBEDDING_BATCH_SIZE"); + }); + + it("rejects empty string (Number('') === 0)", () => { + expect(() => parseBatchSize("")).toThrow("EMBEDDING_BATCH_SIZE"); + }); + + it("rejects whitespace-only string", () => { + expect(() => parseBatchSize(" ")).toThrow("EMBEDDING_BATCH_SIZE"); + }); + + it("rejects non-numeric string", () => { + expect(() => parseBatchSize("abc")).toThrow("EMBEDDING_BATCH_SIZE"); + }); +});