Merge pull request #25 from sb-giithub/feat/global-config-and-batch-size-env

feat: support global config fallback and configurable embedding batch size
This commit is contained in:
Giancarlo Erra
2026-04-14 17:43:43 +01:00
committed by GitHub
4 changed files with 226 additions and 5 deletions
+27 -2
View File
@@ -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,27 @@ export interface SocratiCodeConfig {
*/
export async function loadConfig(projectPath: string): Promise<SocratiCodeConfig | null> {
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;
let usingGlobalFallback = false;
try {
await fsp.access(configPath);
} catch {
return null; // file doesn't exist — that's fine
try {
await fsp.access(globalConfigPath);
actualPath = globalConfigPath;
usingGlobalFallback = true;
} 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);
@@ -109,6 +123,17 @@ export async function loadConfig(projectPath: string): Promise<SocratiCodeConfig
}
}
// When config was loaded from the global fallback directory, resolve relative
// artifact paths against that directory so downstream code (which assumes
// project-root resolution) receives correct absolute paths.
if (usingGlobalFallback && Array.isArray(config.artifacts)) {
const baseDir = path.dirname(actualPath);
config.artifacts = (config.artifacts as ContextArtifact[]).map((artifact) => ({
...artifact,
path: path.isAbsolute(artifact.path) ? artifact.path : path.resolve(baseDir, artifact.path),
}));
}
return config as SocratiCodeConfig;
}
+13 -1
View File
@@ -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 === 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;
})();
const MAX_RETRIES = 3;
const BASE_DELAY_MS = 500;
+125 -2
View File
@@ -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({
+61
View File
@@ -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");
});
});