Compare commits

..

1 Commits

Author SHA1 Message Date
xingyue 1e8ccb8962 feat: add ucas command alias to cli-json-cas bin field
Fixes #24

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-05-30 14:06:23 +08:00
11 changed files with 41 additions and 2874 deletions
-5
View File
@@ -10,7 +10,6 @@
"@changesets/cli": "^2.31.0",
"bun-types": "^1.3.14",
"typescript": "^5.8.0",
"ulidx": "^2.4.1",
},
},
"packages/cli-json-cas": {
@@ -201,8 +200,6 @@
"jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
"layerr": ["layerr@3.0.0", "", {}, "sha512-tv754Ki2dXpPVApOrjTyRo4/QegVb9eVFq4mjqp4+NM5NaX7syQvN5BBNfV/ZpAHCEHV24XdUVrBAoka4jt3pA=="],
"locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
"lodash.startcase": ["lodash.startcase@4.4.0", "", {}, "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg=="],
@@ -285,8 +282,6 @@
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"ulidx": ["ulidx@2.4.1", "", { "dependencies": { "layerr": "^3.0.0" } }, "sha512-xY7c8LPyzvhvew0Fn+Ek3wBC9STZAuDI/Y5andCKi9AX6/jvfaX45PhsDX8oxgPL0YFp0Jhr8qWMbS/p9375Xg=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
+1 -2
View File
@@ -9,8 +9,7 @@
"@changesets/changelog-github": "^0.7.0",
"@changesets/cli": "^2.31.0",
"bun-types": "^1.3.14",
"typescript": "^5.8.0",
"ulidx": "^2.4.1"
"typescript": "^5.8.0"
},
"scripts": {
"build": "tsc --build packages/json-cas packages/json-cas-fs",
+2 -1
View File
@@ -3,7 +3,8 @@
"version": "0.5.3",
"type": "module",
"bin": {
"json-cas": "./src/index.ts"
"json-cas": "./src/index.ts",
"ucas": "./src/index.ts"
},
"scripts": {
"test": "bun test",
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, test } from "bun:test";
import { resolve } from "node:path";
const pkgPath = resolve(import.meta.dir, "../package.json");
describe("ucas command alias", () => {
test("T1: ucas bin entry exists in package.json", async () => {
const pkg = await Bun.file(pkgPath).json();
expect(pkg.bin.ucas).toBe("./src/index.ts");
});
test("T2: json-cas bin entry is preserved in package.json", async () => {
const pkg = await Bun.file(pkgPath).json();
expect(pkg.bin["json-cas"]).toBe("./src/index.ts");
});
test("T3: ucas command is executable and shows help", async () => {
const entrypoint = resolve(import.meta.dir, "index.ts");
const proc = Bun.spawn(["bun", entrypoint, "--help"], {
stdout: "pipe",
stderr: "pipe",
});
const exitCode = await proc.exited;
const stdout = await new Response(proc.stdout).text();
expect(exitCode).toBe(0);
expect(stdout.length).toBeGreaterThan(0);
});
test("T4: both commands point to the same entrypoint", async () => {
const pkg = await Bun.file(pkgPath).json();
expect(pkg.bin.ucas).toBe(pkg.bin["json-cas"]);
});
});
+5 -342
View File
@@ -3,20 +3,13 @@
import { mkdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import type { Hash, JSONSchema, Store, VariableStore } from "@uncaged/json-cas";
import type { Hash, JSONSchema, Store } from "@uncaged/json-cas";
import {
bootstrap,
CasNodeNotFoundError,
computeHash,
createVariableStore,
getSchema,
InvalidScopeError,
InvalidTagFormatError,
putSchema,
refs,
SchemaMismatchError,
TagLabelConflictError,
VariableNotFoundError,
validate,
verify,
walk,
@@ -25,17 +18,10 @@ import { createFsStore } from "@uncaged/json-cas-fs";
// ---- Argument parsing ----
type Flags = Record<string, string | boolean | string[]>;
type Flags = Record<string, string | boolean>;
/** Flags that consume the next token as their value. All others are boolean. */
const VALUE_FLAGS = new Set([
"store",
"format",
"scope",
"value",
"var-db",
"tag",
]);
const VALUE_FLAGS = new Set(["store", "format"]);
function parseArgs(argv: string[]): { flags: Flags; positional: string[] } {
const flags: Flags = {};
@@ -48,19 +34,7 @@ function parseArgs(argv: string[]): { flags: Flags; positional: string[] } {
if (VALUE_FLAGS.has(key)) {
const next = argv[i + 1];
if (next !== undefined && !next.startsWith("--")) {
// Handle repeatable flags (like --tag)
if (key === "tag") {
const existing = flags[key];
if (Array.isArray(existing)) {
existing.push(next);
} else if (typeof existing === "string") {
flags[key] = [existing, next];
} else {
flags[key] = [next];
}
} else {
flags[key] = next;
}
flags[key] = next;
i++;
} else {
flags[key] = true;
@@ -83,10 +57,6 @@ const storePath =
typeof flags.store === "string" ? flags.store : defaultStorePath;
const compact = flags.json === true;
const defaultVarDbPath = join(storePath, "variables.db");
const varDbPath =
typeof flags["var-db"] === "string" ? flags["var-db"] : defaultVarDbPath;
// ---- Helpers ----
function out(data: unknown): void {
@@ -110,95 +80,6 @@ function openStore(): Store {
return createFsStore(resolve(storePath));
}
function openVarStore(): VariableStore {
const store = openStore();
mkdirSync(resolve(storePath), { recursive: true });
return createVariableStore(resolve(varDbPath), store);
}
/**
* Get the Variable schema's CAS hash
* This is the type hash used in JSON envelopes
*/
async function getVariableSchemaHash(): Promise<Hash> {
const store = openStore();
// Define the Variable JSON Schema (simple version for envelope)
const variableSchema: JSONSchema = {
title: "Variable",
type: "object",
properties: {
id: { type: "string" },
scope: { type: "string" },
value: { type: "string" },
schema: { type: "string" },
created: { type: "number" },
updated: { type: "number" },
tags: { type: "object" },
labels: { type: "array", items: { type: "string" } },
},
required: [
"id",
"scope",
"value",
"schema",
"created",
"updated",
"tags",
"labels",
],
};
// Compute hash or retrieve from store
const hash = await putSchema(store, variableSchema);
return hash;
}
/**
* Wrap Variable output in JSON envelope
*/
async function wrapVariableEnvelope(
variable: unknown,
): Promise<{ type: Hash; value: unknown }> {
const typeHash = await getVariableSchemaHash();
return {
type: typeHash,
value: variable,
};
}
/**
* Parse tag/label arguments
* Returns: { tags: Record<string, string>, labels: string[], deleteNames: string[] }
*/
function parseTagsLabels(args: string[]): {
tags: Record<string, string>;
labels: string[];
deleteNames: string[];
} {
const tags: Record<string, string> = {};
const labels: string[] = [];
const deleteNames: string[] = [];
for (const arg of args) {
if (arg.startsWith(":")) {
// Deletion syntax: :name
deleteNames.push(arg.slice(1));
} else if (arg.includes(":")) {
// Tag: key:value (split on first colon)
const colonIdx = arg.indexOf(":");
const key = arg.slice(0, colonIdx);
const value = arg.slice(colonIdx + 1);
tags[key] = value;
} else {
// Label: bare identifier
labels.push(arg);
}
}
return { tags, labels, deleteNames };
}
// ---- Commands ----
async function cmdInit(): Promise<void> {
@@ -369,189 +250,6 @@ async function cmdCat(args: string[]): Promise<void> {
}
}
async function cmdVarCreate(_args: string[]): Promise<void> {
const scope = flags.scope as string | undefined;
const value = flags.value as string | undefined;
const tagFlags = flags.tag;
if (!scope) die("Usage: json-cas var create --scope <scope> --value <hash>");
if (!value) die("Usage: json-cas var create --scope <scope> --value <hash>");
const varStore = openVarStore();
try {
// Parse tags/labels from --tag flags
const tagArgs = Array.isArray(tagFlags)
? tagFlags
: typeof tagFlags === "string"
? [tagFlags]
: [];
const { tags, labels, deleteNames } = parseTagsLabels(tagArgs);
// Check for conflicts in initial tags/labels
if (deleteNames.length > 0) {
die("Error: Cannot use deletion syntax (:name) in var create");
}
const variable = varStore.create(scope, value, {
tags: Object.keys(tags).length > 0 ? tags : undefined,
labels: labels.length > 0 ? labels : undefined,
});
const envelope = await wrapVariableEnvelope(variable);
out(envelope);
} catch (e) {
if (
e instanceof InvalidScopeError ||
e instanceof CasNodeNotFoundError ||
e instanceof TagLabelConflictError
) {
die(`Error: ${e.message}`);
}
throw e;
} finally {
varStore.close();
}
}
async function cmdVarGet(args: string[]): Promise<void> {
const id = args[0];
if (!id) die("Usage: json-cas var get <id>");
const varStore = openVarStore();
try {
const variable = varStore.get(id);
if (variable === null) {
die(`Error: Variable not found: ${id}`);
}
const envelope = await wrapVariableEnvelope(variable);
out(envelope);
} finally {
varStore.close();
}
}
async function cmdVarUpdate(args: string[]): Promise<void> {
const id = args[0];
const value = args[1];
if (!id || !value) {
die("Usage: json-cas var update <id> <hash>");
}
const varStore = openVarStore();
try {
const variable = varStore.update(id, value);
const envelope = await wrapVariableEnvelope(variable);
out(envelope);
} catch (e) {
if (
e instanceof VariableNotFoundError ||
e instanceof SchemaMismatchError ||
e instanceof CasNodeNotFoundError
) {
die(`Error: ${e.message}`);
}
throw e;
} finally {
varStore.close();
}
}
async function cmdVarDelete(args: string[]): Promise<void> {
const id = args[0];
if (!id) die("Usage: json-cas var delete <id>");
const varStore = openVarStore();
try {
const variable = varStore.delete(id);
const envelope = await wrapVariableEnvelope(variable);
out(envelope);
} catch (e) {
if (e instanceof VariableNotFoundError) {
die(`Error: ${e.message}`);
}
throw e;
} finally {
varStore.close();
}
}
async function cmdVarTag(args: string[]): Promise<void> {
const id = args[0];
if (!id) die("Usage: json-cas var tag <id> <tag>...");
const tagArgs = args.slice(1);
if (tagArgs.length === 0) {
die("Usage: json-cas var tag <id> <tag>...");
}
const varStore = openVarStore();
try {
const { tags, labels, deleteNames } = parseTagsLabels(tagArgs);
const variable = varStore.tag(id, {
add: Object.keys(tags).length > 0 ? tags : undefined,
addLabels: labels.length > 0 ? labels : undefined,
delete: deleteNames.length > 0 ? deleteNames : undefined,
});
const envelope = await wrapVariableEnvelope(variable);
out(envelope);
} catch (e) {
if (
e instanceof VariableNotFoundError ||
e instanceof TagLabelConflictError ||
e instanceof InvalidTagFormatError
) {
die(`Error: ${e.message}`);
}
throw e;
} finally {
varStore.close();
}
}
async function cmdVarList(_args: string[]): Promise<void> {
const scope = (flags.scope as string | undefined) ?? "";
const tagFlags = flags.tag;
const varStore = openVarStore();
try {
// Parse tags/labels from --tag flags
const tagArgs = Array.isArray(tagFlags)
? tagFlags
: typeof tagFlags === "string"
? [tagFlags]
: [];
const { tags, labels, deleteNames } = parseTagsLabels(tagArgs);
// Check for invalid deletion syntax in filters
if (deleteNames.length > 0) {
die("Error: Cannot use deletion syntax (:name) in var list filters");
}
const variables = varStore.list({
scope,
tags: Object.keys(tags).length > 0 ? tags : undefined,
labels: labels.length > 0 ? labels : undefined,
});
const envelope = await wrapVariableEnvelope(variables);
out(envelope);
} catch (e) {
if (e instanceof InvalidScopeError) {
die(`Error: ${e.message}`);
}
throw e;
} finally {
varStore.close();
}
}
function printUsage(): void {
console.log(`\
Usage: json-cas [--store <path>] [--json] <command> [args]
@@ -571,18 +269,10 @@ Commands:
walk <hash> [--format tree] Recursive traversal
hash <type-hash> <file.json> Compute hash without storing (dry run)
cat <hash> [--payload] Output node (--payload for payload only)
var create --scope <s> --value <h> [--tag <tag>...] Create a variable
var get <id> Get a variable by ID
var update <id> <hash> Update variable value
var delete <id> Delete a variable
var tag <id> <tag>... Add/update/delete tags and labels
var list [--scope <prefix>] [--tag <tag>...] List variables (filter by scope/tags/labels)
Flags:
--store <path> Store directory (default: ~/.uncaged/json-cas)
--var-db <path> Variable database path (default: <store>/variables.db)
--json Compact JSON output
--tag <tag> Tag/label (can be repeated): key:value (tag), name (label), :name (delete)`);
--json Compact JSON output`);
}
// ---- Dispatch ----
@@ -656,33 +346,6 @@ switch (cmd) {
await cmdCat(rest);
break;
case "var": {
const [sub, ...subRest] = rest;
switch (sub) {
case "create":
await cmdVarCreate(subRest);
break;
case "get":
await cmdVarGet(subRest);
break;
case "update":
await cmdVarUpdate(subRest);
break;
case "delete":
await cmdVarDelete(subRest);
break;
case "tag":
await cmdVarTag(subRest);
break;
case "list":
await cmdVarList(subRest);
break;
default:
die(`Unknown var subcommand: ${sub ?? "(none)"}`);
}
break;
}
default:
die(`Unknown command: ${cmd}`);
}
-822
View File
@@ -1,822 +0,0 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
describe("CLI var commands", () => {
let storePath: string;
let varDbPath: string;
let cliPath: string;
let schemaHash: string;
let hashA: string;
let hashB: string;
let testCounter = 0;
beforeEach(async () => {
// Create temporary paths with counter to ensure uniqueness
testCounter++;
storePath = join(tmpdir(), `test-cli-store-${Date.now()}-${testCounter}`);
varDbPath = join(storePath, "variables.db");
cliPath = join(import.meta.dir, "index.ts");
// Initialize store and create test data
const initResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "init"],
{
encoding: "utf-8",
},
);
expect(initResult.status).toBe(0);
// Create a schema
const schemaFile = join(tmpdir(), `schema-${Date.now()}.json`);
await Bun.write(
schemaFile,
JSON.stringify({
type: "object",
properties: { name: { type: "string" } },
}),
);
const schemaPutResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "schema", "put", schemaFile],
{ encoding: "utf-8" },
);
expect(schemaPutResult.status).toBe(0);
schemaHash = schemaPutResult.stdout.trim();
// Create test CAS nodes
const dataFileA = join(tmpdir(), `data-a-${Date.now()}.json`);
await Bun.write(dataFileA, JSON.stringify({ name: "hello" }));
const putResultA = spawnSync(
"bun",
[cliPath, "--store", storePath, "put", schemaHash, dataFileA],
{ encoding: "utf-8" },
);
expect(putResultA.status).toBe(0);
hashA = putResultA.stdout.trim();
const dataFileB = join(tmpdir(), `data-b-${Date.now()}.json`);
await Bun.write(dataFileB, JSON.stringify({ name: "world" }));
const putResultB = spawnSync(
"bun",
[cliPath, "--store", storePath, "put", schemaHash, dataFileB],
{ encoding: "utf-8" },
);
expect(putResultB.status).toBe(0);
hashB = putResultB.stdout.trim();
});
afterEach(() => {
// Cleanup
try {
unlinkSync(varDbPath);
} catch {
// Ignore
}
});
describe("Test Group 1: Variable Creation", () => {
test("1.1: Create variable with valid scope", () => {
const result = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(result.status).toBe(0);
const output = JSON.parse(result.stdout);
// Expect envelope format
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
// Check the actual variable in the value field
const variable = output.value;
expect(variable.id).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/);
expect(variable.scope).toBe("uwf/thread/");
expect(variable.value).toBe(hashA);
expect(variable.schema).toBe(schemaHash);
expect(variable.created).toBeGreaterThan(Date.now() - 5000);
expect(variable.updated).toBe(variable.created);
});
test("1.2: Create variable fails with scope not ending in /", () => {
const result = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(result.status).not.toBe(0);
expect(result.stderr).toContain("scope must end with /");
});
test("1.3: Create variable fails with non-existent CAS node", () => {
const fakeHash = "FAKEHASH00000";
const result = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/",
"--value",
fakeHash,
],
{ encoding: "utf-8" },
);
expect(result.status).not.toBe(0);
expect(result.stderr).toContain("CAS node not found");
});
});
describe("Test Group 2: Variable Retrieval", () => {
test("2.1: Get existing variable", () => {
// Create a variable first
const createResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const created = JSON.parse(createResult.stdout).value;
// Get the variable
const result = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", created.id],
{ encoding: "utf-8" },
);
expect(result.status).toBe(0);
const output = JSON.parse(result.stdout);
// Expect envelope format
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
// Check the actual variable in the value field
const variable = output.value;
expect(variable.id).toBe(created.id);
expect(variable.scope).toBe("uwf/thread/");
expect(variable.value).toBe(hashA);
expect(variable.schema).toBe(schemaHash);
});
test("2.2: Get non-existent variable", () => {
const fakeId = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
const result = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", fakeId],
{ encoding: "utf-8" },
);
expect(result.status).not.toBe(0);
expect(result.stderr).toContain("Variable not found");
});
});
describe("Test Group 3: Variable Update (Schema Consistent)", () => {
test("3.1: Update variable with matching schema", async () => {
// Create a variable
const createResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const created = JSON.parse(createResult.stdout).value;
// Wait a bit to ensure different timestamp
await new Promise((resolve) => setTimeout(resolve, 10));
// Update the variable
const result = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "update", created.id, hashB],
{ encoding: "utf-8" },
);
expect(result.status).toBe(0);
const output = JSON.parse(result.stdout);
// Expect envelope format
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
// Check the actual variable in the value field
const variable = output.value;
expect(variable.id).toBe(created.id);
expect(variable.value).toBe(hashB);
expect(variable.schema).toBe(schemaHash);
expect(variable.updated).toBeGreaterThan(created.created);
});
});
describe("Test Group 4: Variable Update (Schema Mismatch)", () => {
test("4.1: Update variable fails with schema mismatch", async () => {
// Create another schema
const schema2File = join(tmpdir(), `schema2-${Date.now()}.json`);
await Bun.write(
schema2File,
JSON.stringify({
type: "object",
properties: { count: { type: "number" } },
}),
);
const schema2PutResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "schema", "put", schema2File],
{ encoding: "utf-8" },
);
const schemaHash2 = schema2PutResult.stdout.trim();
// Create a node with the second schema
const dataFileC = join(tmpdir(), `data-c-${Date.now()}.json`);
await Bun.write(dataFileC, JSON.stringify({ count: 42 }));
const putResultC = spawnSync(
"bun",
[cliPath, "--store", storePath, "put", schemaHash2, dataFileC],
{ encoding: "utf-8" },
);
const hashC = putResultC.stdout.trim();
// Create a variable with first schema
const createResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const created = JSON.parse(createResult.stdout).value;
// Try to update with different schema
const result = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "update", created.id, hashC],
{ encoding: "utf-8" },
);
expect(result.status).not.toBe(0);
expect(result.stderr.toLowerCase()).toContain("schema mismatch");
});
});
describe("Test Group 5: Variable Deletion", () => {
test("5.1: Delete existing variable", () => {
// Create a variable
const createResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const created = JSON.parse(createResult.stdout).value;
// Delete the variable
const result = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "delete", created.id],
{ encoding: "utf-8" },
);
expect(result.status).toBe(0);
const output = JSON.parse(result.stdout);
// Expect envelope format
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
// Check the actual variable in the value field
const variable = output.value;
expect(variable.id).toBe(created.id);
// Verify it's deleted
const getResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", created.id],
{ encoding: "utf-8" },
);
expect(getResult.status).not.toBe(0);
});
test("5.3: Delete non-existent variable", () => {
const fakeId = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
const result = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "delete", fakeId],
{ encoding: "utf-8" },
);
expect(result.status).not.toBe(0);
expect(result.stderr).toContain("Variable not found");
});
});
describe("Test Group 6: Variable Listing", () => {
test("6.1: List variables with scope prefix", () => {
// Create variables with different scopes
const createResult1 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(createResult1.status).toBe(0);
const var1 = JSON.parse(createResult1.stdout).value;
const createResult2 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashB,
],
{ encoding: "utf-8" },
);
expect(createResult2.status).toBe(0);
const var2 = JSON.parse(createResult2.stdout).value;
const createResult3 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/agent/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(createResult3.status).toBe(0);
const var3 = JSON.parse(createResult3.stdout).value;
const createResult4 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"app/config/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(createResult4.status).toBe(0);
// List all variables with uwf/ prefix
const listResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "list", "--scope", "uwf/"],
{ encoding: "utf-8" },
);
expect(listResult.status).toBe(0);
const output = JSON.parse(listResult.stdout);
// Expect envelope format
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
expect(Array.isArray(output.value)).toBe(true);
// Check the actual variables in the value field
const variables = output.value;
expect(variables).toHaveLength(3);
expect(
variables.every((v: { scope: string }) => v.scope.startsWith("uwf/")),
).toBe(true);
// Verify ordering by created timestamp
expect(variables[0].id).toBe(var1.id);
expect(variables[1].id).toBe(var2.id);
expect(variables[2].id).toBe(var3.id);
});
test("6.2: List all variables when no scope specified", () => {
// Create variables with different scopes
const createResult1 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(createResult1.status).toBe(0);
const createResult2 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"app/config/",
"--value",
hashB,
],
{ encoding: "utf-8" },
);
expect(createResult2.status).toBe(0);
// List all variables without scope filter
const listResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "list"],
{ encoding: "utf-8" },
);
expect(listResult.status).toBe(0);
const output = JSON.parse(listResult.stdout);
// Expect envelope format
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
expect(Array.isArray(output.value)).toBe(true);
const variables = output.value;
expect(variables).toHaveLength(2);
});
test("6.3: List returns empty array when no matches", () => {
// Create a variable
const createResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(createResult.status).toBe(0);
// List with non-matching scope
const listResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"list",
"--scope",
"nonexistent/",
],
{ encoding: "utf-8" },
);
expect(listResult.status).toBe(0);
const output = JSON.parse(listResult.stdout);
expect(output.type).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
expect(output.value).toBeDefined();
expect(Array.isArray(output.value)).toBe(true);
expect(output.value).toHaveLength(0);
});
test("6.4: List fails with invalid scope format", () => {
const listResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "list", "--scope", "uwf"],
{ encoding: "utf-8" },
);
expect(listResult.status).not.toBe(0);
expect(listResult.stderr).toContain("scope must end with /");
});
});
describe("Test Group 7: Integration Tests", () => {
test("7.1: Full lifecycle workflow", async () => {
// Create variable
const createResult = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
expect(createResult.status).toBe(0);
const var1 = JSON.parse(createResult.stdout).value;
expect(var1.value).toBe(hashA);
// Get variable
const getResult1 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var1.id],
{ encoding: "utf-8" },
);
expect(getResult1.status).toBe(0);
const retrieved1 = JSON.parse(getResult1.stdout).value;
expect(retrieved1.value).toBe(hashA);
// Wait to ensure different timestamp
await new Promise((resolve) => setTimeout(resolve, 10));
// Update variable
const updateResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "update", var1.id, hashB],
{ encoding: "utf-8" },
);
expect(updateResult.status).toBe(0);
const updated = JSON.parse(updateResult.stdout).value;
expect(updated.value).toBe(hashB);
// Get updated variable
const getResult2 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var1.id],
{ encoding: "utf-8" },
);
expect(getResult2.status).toBe(0);
const retrieved2 = JSON.parse(getResult2.stdout).value;
expect(retrieved2.value).toBe(hashB);
// Delete variable
const deleteResult = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "delete", var1.id],
{ encoding: "utf-8" },
);
expect(deleteResult.status).toBe(0);
// Verify deletion
const getResult3 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var1.id],
{ encoding: "utf-8" },
);
expect(getResult3.status).not.toBe(0);
});
test("7.2: Multiple variables with same scope", () => {
// Create two variables
const createResult1 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const var1 = JSON.parse(createResult1.stdout).value;
const createResult2 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashB,
],
{ encoding: "utf-8" },
);
const var2 = JSON.parse(createResult2.stdout).value;
// Verify independence
expect(var1.id).not.toBe(var2.id);
const getResult1 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var1.id],
{ encoding: "utf-8" },
);
const retrieved1 = JSON.parse(getResult1.stdout).value;
expect(retrieved1.value).toBe(hashA);
const getResult2 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var2.id],
{ encoding: "utf-8" },
);
const retrieved2 = JSON.parse(getResult2.stdout).value;
expect(retrieved2.value).toBe(hashB);
// Delete var1, verify var2 still exists
spawnSync("bun", [
cliPath,
"--store",
storePath,
"var",
"delete",
var1.id,
]);
const getResult2Final = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var2.id],
{ encoding: "utf-8" },
);
expect(getResult2Final.status).toBe(0);
const retrieved2Final = JSON.parse(getResult2Final.stdout).value;
expect(retrieved2Final.value).toBe(hashB);
});
test("7.3: Variables with hierarchical scopes", () => {
const createResult1 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const var1 = JSON.parse(createResult1.stdout).value;
const createResult2 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/thread/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const var2 = JSON.parse(createResult2.stdout).value;
const createResult3 = spawnSync(
"bun",
[
cliPath,
"--store",
storePath,
"var",
"create",
"--scope",
"uwf/workflow/",
"--value",
hashA,
],
{ encoding: "utf-8" },
);
const var3 = JSON.parse(createResult3.stdout).value;
expect(var1.scope).toBe("uwf/");
expect(var2.scope).toBe("uwf/thread/");
expect(var3.scope).toBe("uwf/workflow/");
// Verify all exist
const get1 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var1.id],
{ encoding: "utf-8" },
);
expect(get1.status).toBe(0);
const get2 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var2.id],
{ encoding: "utf-8" },
);
expect(get2.status).toBe(0);
const get3 = spawnSync(
"bun",
[cliPath, "--store", storePath, "var", "get", var3.id],
{ encoding: "utf-8" },
);
expect(get3.status).toBe(0);
});
});
});
-11
View File
@@ -14,15 +14,4 @@ export {
} from "./schema.js";
export { createMemoryStore } from "./store.js";
export type { CasNode, Hash, Store } from "./types.js";
export type { Variable, VariableId } from "./variable.js";
export {
CasNodeNotFoundError,
createVariableStore,
InvalidScopeError,
InvalidTagFormatError,
SchemaMismatchError,
TagLabelConflictError,
VariableNotFoundError,
VariableStore,
} from "./variable-store.js";
export { verify } from "./verify.js";
@@ -1,407 +0,0 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createMemoryStore } from "./store.js";
import type { Store } from "./types.js";
import {
CasNodeNotFoundError,
InvalidScopeError,
SchemaMismatchError,
VariableNotFoundError,
VariableStore,
} from "./variable-store.js";
describe("VariableStore", () => {
let store: Store;
let varStore: VariableStore;
let dbPath: string;
let schemaA: string;
let schemaB: string;
let hashA: string;
let hashB: string;
let hashC: string;
beforeEach(async () => {
// Create a temporary database
dbPath = join(tmpdir(), `test-variables-${Date.now()}.db`);
// Create a CAS store with test data
store = createMemoryStore();
// Create two different schemas
schemaA = await store.put("BOOTSTRAPHASH", {
type: "object",
properties: { name: { type: "string" } },
});
schemaB = await store.put("BOOTSTRAPHASH", {
type: "object",
properties: { count: { type: "number" } },
});
// Create CAS nodes with different schemas
hashA = await store.put(schemaA, { name: "hello" });
hashB = await store.put(schemaA, { name: "world" });
hashC = await store.put(schemaB, { count: 42 });
// Create variable store
varStore = new VariableStore(dbPath, store);
});
afterEach(() => {
varStore.close();
try {
unlinkSync(dbPath);
} catch {
// Ignore cleanup errors
}
});
describe("Test Group 1: Variable Creation", () => {
test("1.1: Create variable with valid scope", () => {
const variable = varStore.create("uwf/thread/", hashA);
expect(variable.id).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/);
expect(variable.scope).toBe("uwf/thread/");
expect(variable.value).toBe(hashA);
expect(variable.schema).toBe(schemaA);
expect(variable.created).toBeGreaterThan(Date.now() - 5000);
expect(variable.created).toBeLessThanOrEqual(Date.now());
expect(variable.updated).toBe(variable.created);
expect(variable.tags).toEqual({});
expect(variable.labels).toEqual([]);
// Verify persistence
const retrieved = varStore.get(variable.id);
expect(retrieved).not.toBeNull();
expect(retrieved?.id).toBe(variable.id);
expect(retrieved?.scope).toBe(variable.scope);
expect(retrieved?.value).toBe(variable.value);
expect(retrieved?.tags).toEqual({});
expect(retrieved?.labels).toEqual([]);
});
test("1.2: Create variable fails with scope not ending in /", () => {
expect(() => varStore.create("uwf/thread", hashA)).toThrow(
InvalidScopeError,
);
expect(() => varStore.create("uwf/thread", hashA)).toThrow(
"scope must end with /",
);
});
test("1.3: Create variable fails with non-existent CAS node", () => {
const fakeHash = "FAKEHASH00000";
expect(() => varStore.create("uwf/", fakeHash)).toThrow(
CasNodeNotFoundError,
);
expect(() => varStore.create("uwf/", fakeHash)).toThrow(
`CAS node not found: ${fakeHash}`,
);
});
});
describe("Test Group 2: Variable Retrieval", () => {
test("2.1: Get existing variable", () => {
const created = varStore.create("uwf/thread/", hashA);
const retrieved = varStore.get(created.id);
expect(retrieved).not.toBeNull();
expect(retrieved?.id).toBe(created.id);
expect(retrieved?.scope).toBe("uwf/thread/");
expect(retrieved?.value).toBe(hashA);
expect(retrieved?.schema).toBe(schemaA);
expect(retrieved?.created).toBe(created.created);
expect(retrieved?.updated).toBe(created.updated);
});
test("2.2: Get non-existent variable", () => {
const fakeId = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
const result = varStore.get(fakeId);
expect(result).toBeNull();
});
});
describe("Test Group 3: Variable Update (Schema Consistent)", () => {
test("3.1: Update variable with matching schema", async () => {
const created = varStore.create("uwf/thread/", hashA);
const t1 = created.created;
// Wait a bit to ensure different timestamp
await new Promise((resolve) => setTimeout(resolve, 10));
const updated = varStore.update(created.id, hashB);
expect(updated.id).toBe(created.id);
expect(updated.scope).toBe("uwf/thread/");
expect(updated.value).toBe(hashB);
expect(updated.schema).toBe(schemaA);
expect(updated.created).toBe(t1);
expect(updated.updated).toBeGreaterThan(t1);
expect(updated.updated).toBeGreaterThan(Date.now() - 5000);
expect(updated.updated).toBeLessThanOrEqual(Date.now());
// Verify persistence
const retrieved = varStore.get(created.id);
expect(retrieved?.value).toBe(hashB);
expect(retrieved?.updated).toBe(updated.updated);
});
test("3.2: Update variable to same value is idempotent", () => {
const created = varStore.create("uwf/thread/", hashA);
const updated = varStore.update(created.id, hashA);
expect(updated.value).toBe(hashA);
expect(updated.schema).toBe(schemaA);
// Updated timestamp may change, this is implementation-defined
});
});
describe("Test Group 4: Variable Update (Schema Mismatch)", () => {
test("4.1: Update variable fails with schema mismatch", () => {
const created = varStore.create("uwf/thread/", hashA);
expect(() => varStore.update(created.id, hashC)).toThrow(
SchemaMismatchError,
);
const error = (() => {
try {
varStore.update(created.id, hashC);
return null;
} catch (e) {
return e as SchemaMismatchError;
}
})();
expect(error).not.toBeNull();
expect(error?.expected).toBe(schemaA);
expect(error?.actual).toBe(schemaB);
expect(error?.message.toLowerCase()).toContain("schema mismatch");
// Verify variable is unchanged
const retrieved = varStore.get(created.id);
expect(retrieved?.value).toBe(hashA);
});
test("4.2: Update variable fails with non-existent CAS node", () => {
const created = varStore.create("uwf/thread/", hashA);
const fakeHash = "FAKEHASH00000";
expect(() => varStore.update(created.id, fakeHash)).toThrow(
CasNodeNotFoundError,
);
});
test("4.3: Update non-existent variable", () => {
const fakeId = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
expect(() => varStore.update(fakeId, hashA)).toThrow(
VariableNotFoundError,
);
expect(() => varStore.update(fakeId, hashA)).toThrow(
`Variable not found: ${fakeId}`,
);
});
});
describe("Test Group 5: Variable Deletion", () => {
test("5.1: Delete existing variable", () => {
const created = varStore.create("uwf/thread/", hashA);
const deleted = varStore.delete(created.id);
expect(deleted.id).toBe(created.id);
expect(deleted.scope).toBe(created.scope);
expect(deleted.value).toBe(created.value);
expect(deleted.schema).toBe(created.schema);
// Verify it's removed from database
const retrieved = varStore.get(created.id);
expect(retrieved).toBeNull();
});
test("5.2: Get deleted variable", () => {
const created = varStore.create("uwf/thread/", hashA);
varStore.delete(created.id);
const retrieved = varStore.get(created.id);
expect(retrieved).toBeNull();
});
test("5.3: Delete non-existent variable", () => {
const fakeId = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
expect(() => varStore.delete(fakeId)).toThrow(VariableNotFoundError);
expect(() => varStore.delete(fakeId)).toThrow(
`Variable not found: ${fakeId}`,
);
});
});
describe("Test Group 6: Variable Listing", () => {
test("6.1: list() returns all variables with matching scope prefix", async () => {
const var1 = varStore.create("uwf/thread/", hashA);
const var2 = varStore.create("uwf/thread/", hashB);
const var3 = varStore.create("uwf/agent/", hashA);
varStore.create("app/config/", hashA);
// Wait a bit to ensure different timestamps
await new Promise((resolve) => setTimeout(resolve, 10));
const results = varStore.list({ scope: "uwf/" });
expect(results).toHaveLength(3);
expect(results.every((v) => v.scope.startsWith("uwf/"))).toBe(true);
// Verify ordering by created timestamp
expect(results[0]?.id).toBe(var1.id);
expect(results[1]?.id).toBe(var2.id);
expect(results[2]?.id).toBe(var3.id);
});
test("6.2: list() returns empty array when no matches", () => {
varStore.create("uwf/thread/", hashA);
const results = varStore.list({ scope: "nonexistent/" });
expect(results).toHaveLength(0);
expect(Array.isArray(results)).toBe(true);
});
test("6.3: list() returns all variables when scope is empty string", () => {
const var1 = varStore.create("uwf/thread/", hashA);
const var2 = varStore.create("app/config/", hashB);
const var3 = varStore.create("test/", hashC);
const results = varStore.list({ scope: "" });
expect(results).toHaveLength(3);
expect(results.map((v) => v.id)).toContain(var1.id);
expect(results.map((v) => v.id)).toContain(var2.id);
expect(results.map((v) => v.id)).toContain(var3.id);
});
test("6.4: list() validates scope format (must end with /)", () => {
varStore.create("uwf/thread/", hashA);
expect(() => varStore.list({ scope: "uwf" })).toThrow(InvalidScopeError);
expect(() => varStore.list({ scope: "uwf" })).toThrow(
"scope must end with /",
);
});
test("6.5: list() returns exact scope match and sub-scopes", () => {
varStore.create("uwf/thread/", hashA);
varStore.create("uwf/thread/active/", hashB);
const results = varStore.list({ scope: "uwf/thread/" });
expect(results).toHaveLength(2);
expect(results[0]?.scope).toBe("uwf/thread/");
expect(results[1]?.scope).toBe("uwf/thread/active/");
});
test("6.6: list() result ordering is deterministic", async () => {
// Create 5 variables with the same scope prefix
const var1 = varStore.create("test/", hashA);
await new Promise((resolve) => setTimeout(resolve, 2));
const var2 = varStore.create("test/", hashB);
await new Promise((resolve) => setTimeout(resolve, 2));
const var3 = varStore.create("test/", hashA);
await new Promise((resolve) => setTimeout(resolve, 2));
const var4 = varStore.create("test/", hashB);
await new Promise((resolve) => setTimeout(resolve, 2));
const var5 = varStore.create("test/", hashA);
// Call list multiple times
const results1 = varStore.list({ scope: "test/" });
const results2 = varStore.list({ scope: "test/" });
const results3 = varStore.list({ scope: "test/" });
// All results should be identical
expect(results1.map((v) => v.id)).toEqual(results2.map((v) => v.id));
expect(results2.map((v) => v.id)).toEqual(results3.map((v) => v.id));
// Verify ordering by created timestamp (oldest first)
expect(results1[0]?.id).toBe(var1.id);
expect(results1[1]?.id).toBe(var2.id);
expect(results1[2]?.id).toBe(var3.id);
expect(results1[3]?.id).toBe(var4.id);
expect(results1[4]?.id).toBe(var5.id);
});
});
describe("Test Group 7: Integration Tests", () => {
test("7.1: Full lifecycle workflow", async () => {
// Create variable
const var1 = varStore.create("uwf/thread/", hashA);
expect(var1.value).toBe(hashA);
// Get variable
const retrieved1 = varStore.get(var1.id);
expect(retrieved1?.value).toBe(hashA);
// Wait to ensure different timestamp
await new Promise((resolve) => setTimeout(resolve, 10));
// Update variable
const updated = varStore.update(var1.id, hashB);
expect(updated.value).toBe(hashB);
expect(updated.updated).toBeGreaterThan(var1.created);
// Get updated variable
const retrieved2 = varStore.get(var1.id);
expect(retrieved2?.value).toBe(hashB);
// Delete variable
const deleted = varStore.delete(var1.id);
expect(deleted.value).toBe(hashB);
// Verify deletion
const retrieved3 = varStore.get(var1.id);
expect(retrieved3).toBeNull();
});
test("7.2: Multiple variables with same scope", () => {
const var1 = varStore.create("uwf/thread/", hashA);
const var2 = varStore.create("uwf/thread/", hashB);
// Verify independence
expect(var1.id).not.toBe(var2.id);
const retrieved1 = varStore.get(var1.id);
const retrieved2 = varStore.get(var2.id);
expect(retrieved1?.value).toBe(hashA);
expect(retrieved2?.value).toBe(hashB);
// Update var1, verify var2 is unaffected
varStore.update(var1.id, hashB);
const retrieved2After = varStore.get(var2.id);
expect(retrieved2After?.value).toBe(hashB);
expect(retrieved2After?.updated).toBe(var2.updated);
// Delete var1, verify var2 still exists
varStore.delete(var1.id);
const retrieved2Final = varStore.get(var2.id);
expect(retrieved2Final).not.toBeNull();
expect(retrieved2Final?.value).toBe(hashB);
});
test("7.3: Variables with hierarchical scopes", () => {
const var1 = varStore.create("uwf/", hashA);
const var2 = varStore.create("uwf/thread/", hashA);
const var3 = varStore.create("uwf/workflow/", hashA);
expect(var1.scope).toBe("uwf/");
expect(var2.scope).toBe("uwf/thread/");
expect(var3.scope).toBe("uwf/workflow/");
// All should exist independently
expect(varStore.get(var1.id)).not.toBeNull();
expect(varStore.get(var2.id)).not.toBeNull();
expect(varStore.get(var3.id)).not.toBeNull();
});
});
});
-524
View File
@@ -1,524 +0,0 @@
import { Database } from "bun:sqlite";
import { ulid } from "ulidx";
import type { Store } from "./types.js";
import type { Variable, VariableId } from "./variable.js";
/**
* Custom error types for variable operations
*/
export class VariableNotFoundError extends Error {
constructor(id: VariableId) {
super(`Variable not found: ${id}`);
this.name = "VariableNotFoundError";
}
}
export class SchemaMismatchError extends Error {
constructor(
public expected: string,
public actual: string,
) {
super(`Schema mismatch: expected ${expected}, got ${actual}`);
this.name = "SchemaMismatchError";
}
}
export class InvalidScopeError extends Error {
constructor(scope: string) {
super(`Invalid scope: scope must end with / (got: ${scope})`);
this.name = "InvalidScopeError";
}
}
export class CasNodeNotFoundError extends Error {
constructor(hash: string) {
super(`CAS node not found: ${hash}`);
this.name = "CasNodeNotFoundError";
}
}
export class TagLabelConflictError extends Error {
constructor(
public conflictName: string,
public existingType: "tag" | "label",
public attemptedType: "tag" | "label",
) {
super(`Conflict: '${conflictName}' already exists as a ${existingType}`);
this.name = "TagLabelConflictError";
}
}
export class InvalidTagFormatError extends Error {
constructor(tag: string) {
super(`Invalid tag format: ${tag}`);
this.name = "InvalidTagFormatError";
}
}
/**
* Variable store with SQLite backend
*/
export class VariableStore {
private db: Database;
constructor(
dbPath: string,
private casStore: Store,
) {
this.db = new Database(dbPath, { create: true });
this.initDb();
}
private initDb(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS variables (
id TEXT PRIMARY KEY,
scope TEXT NOT NULL,
value TEXT NOT NULL,
schema TEXT NOT NULL,
created INTEGER NOT NULL,
updated INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_var_scope ON variables(scope);
CREATE INDEX IF NOT EXISTS idx_var_value ON variables(value);
CREATE INDEX IF NOT EXISTS idx_var_schema ON variables(schema);
CREATE TABLE IF NOT EXISTS variable_tags (
variable_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (variable_id, key),
FOREIGN KEY (variable_id) REFERENCES variables(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS variable_labels (
variable_id TEXT NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (variable_id, name),
FOREIGN KEY (variable_id) REFERENCES variables(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_var_tag_key ON variable_tags(key);
CREATE INDEX IF NOT EXISTS idx_var_tag_key_value ON variable_tags(key, value);
CREATE INDEX IF NOT EXISTS idx_var_label_name ON variable_labels(name);
`);
}
/**
* Validate that scope ends with /
*/
private validateScope(scope: string): void {
if (!scope.endsWith("/")) {
throw new InvalidScopeError(scope);
}
}
/**
* Extract schema hash from CAS node
*/
private extractSchema(hash: string): string {
const node = this.casStore.get(hash);
if (node === null) {
throw new CasNodeNotFoundError(hash);
}
return node.type;
}
/**
* Create a new variable
*/
create(
scope: string,
value: string,
options?: {
tags?: Record<string, string>;
labels?: string[];
},
): Variable {
this.validateScope(scope);
const schema = this.extractSchema(value);
const tags = options?.tags ?? {};
const labels = options?.labels ?? [];
// Check for tag/label conflicts
const tagKeys = Object.keys(tags);
for (const key of tagKeys) {
if (labels.includes(key)) {
throw new TagLabelConflictError(key, "label", "tag");
}
}
const id = ulid();
const now = Date.now();
this.db.exec("BEGIN TRANSACTION");
try {
const stmt = this.db.prepare(`
INSERT INTO variables (id, scope, value, schema, created, updated)
VALUES (?, ?, ?, ?, ?, ?)
`);
stmt.run(id, scope, value, schema, now, now);
// Insert tags
if (tagKeys.length > 0) {
const tagStmt = this.db.prepare(`
INSERT INTO variable_tags (variable_id, key, value)
VALUES (?, ?, ?)
`);
for (const [key, val] of Object.entries(tags)) {
tagStmt.run(id, key, val);
}
}
// Insert labels
if (labels.length > 0) {
const labelStmt = this.db.prepare(`
INSERT INTO variable_labels (variable_id, name)
VALUES (?, ?)
`);
for (const name of labels) {
labelStmt.run(id, name);
}
}
this.db.exec("COMMIT");
} catch (e) {
this.db.exec("ROLLBACK");
throw e;
}
return {
id,
scope,
value,
schema,
created: now,
updated: now,
tags,
labels: [...labels],
};
}
/**
* Load tags for a variable
*/
private loadTags(id: VariableId): Record<string, string> {
const stmt = this.db.prepare(`
SELECT key, value
FROM variable_tags
WHERE variable_id = ?
`);
const rows = stmt.all(id) as Array<{ key: string; value: string }>;
const tags: Record<string, string> = {};
for (const row of rows) {
tags[row.key] = row.value;
}
return tags;
}
/**
* Load labels for a variable
*/
private loadLabels(id: VariableId): string[] {
const stmt = this.db.prepare(`
SELECT name
FROM variable_labels
WHERE variable_id = ?
ORDER BY name ASC
`);
const rows = stmt.all(id) as Array<{ name: string }>;
return rows.map((row) => row.name);
}
/**
* Get a variable by ID
*/
get(id: VariableId): Variable | null {
const stmt = this.db.prepare(`
SELECT id, scope, value, schema, created, updated
FROM variables
WHERE id = ?
`);
const row = stmt.get(id) as
| {
id: string;
scope: string;
value: string;
schema: string;
created: number;
updated: number;
}
| undefined
| null;
if (row === undefined || row === null) {
return null;
}
const tags = this.loadTags(row.id);
const labels = this.loadLabels(row.id);
return {
id: row.id,
scope: row.scope,
value: row.value,
schema: row.schema,
created: row.created,
updated: row.updated,
tags,
labels,
};
}
/**
* Update a variable's value (with schema validation)
*/
update(id: VariableId, value: string): Variable {
const existing = this.get(id);
if (existing === null) {
throw new VariableNotFoundError(id);
}
const newSchema = this.extractSchema(value);
if (newSchema !== existing.schema) {
throw new SchemaMismatchError(existing.schema, newSchema);
}
const now = Date.now();
const stmt = this.db.prepare(`
UPDATE variables
SET value = ?, updated = ?
WHERE id = ?
`);
stmt.run(value, now, id);
return {
...existing,
value,
updated: now,
};
}
/**
* Delete a variable
*/
delete(id: VariableId): Variable {
const existing = this.get(id);
if (existing === null) {
throw new VariableNotFoundError(id);
}
const stmt = this.db.prepare(`
DELETE FROM variables WHERE id = ?
`);
stmt.run(id);
return existing;
}
/**
* List variables matching a scope prefix
*/
list(options?: {
scope?: string;
tags?: Record<string, string>;
labels?: string[];
}): Variable[] {
const scope = options?.scope ?? "";
const filterTags = options?.tags ?? {};
const filterLabels = options?.labels ?? [];
// Validate scope format (must end with / if non-empty)
if (scope !== "" && !scope.endsWith("/")) {
throw new InvalidScopeError(scope);
}
// Build query with tag/label filtering
let query = `
SELECT DISTINCT v.id, v.scope, v.value, v.schema, v.created, v.updated
FROM variables v
`;
const params: (string | number)[] = [];
// Tag filters (AND logic)
const tagKeys = Object.keys(filterTags);
for (let i = 0; i < tagKeys.length; i++) {
const key = tagKeys[i] as string;
const value = filterTags[key] as string;
query += `
INNER JOIN variable_tags t${i} ON v.id = t${i}.variable_id
AND t${i}.key = ? AND t${i}.value = ?
`;
params.push(key, value);
}
// Label filters (AND logic)
for (let i = 0; i < filterLabels.length; i++) {
const label = filterLabels[i] as string;
query += `
INNER JOIN variable_labels l${i} ON v.id = l${i}.variable_id
AND l${i}.name = ?
`;
params.push(label);
}
// Scope filter (always present)
query += " WHERE v.scope LIKE ? || '%'";
params.push(scope);
query += " ORDER BY v.created ASC";
const stmt = this.db.prepare(query);
const rows = stmt.all(...params) as Array<{
id: string;
scope: string;
value: string;
schema: string;
created: number;
updated: number;
}>;
return rows.map((row) => ({
id: row.id,
scope: row.scope,
value: row.value,
schema: row.schema,
created: row.created,
updated: row.updated,
tags: this.loadTags(row.id),
labels: this.loadLabels(row.id),
}));
}
/**
* Add/update/delete tags and labels
*/
tag(
id: VariableId,
operations: {
add?: Record<string, string>; // tags to add/update
addLabels?: string[]; // labels to add
delete?: string[]; // tag keys or label names to delete
},
): Variable {
const existing = this.get(id);
if (existing === null) {
throw new VariableNotFoundError(id);
}
const addTags = operations.add ?? {};
const addLabels = operations.addLabels ?? [];
const deleteNames = operations.delete ?? [];
// Check for conflicts between tags and labels
const newTagKeys = Object.keys(addTags);
for (const key of newTagKeys) {
// Check if this key is being added as a label in the same operation
if (addLabels.includes(key)) {
throw new TagLabelConflictError(key, "label", "tag");
}
// Check if this key already exists as a label (and not being deleted)
if (existing.labels.includes(key) && !deleteNames.includes(key)) {
throw new TagLabelConflictError(key, "label", "tag");
}
}
for (const name of addLabels) {
// Check if this name is being added as a tag in the same operation
if (newTagKeys.includes(name)) {
throw new TagLabelConflictError(name, "tag", "label");
}
// Check if this name already exists as a tag key (and not being deleted)
if (existing.tags[name] !== undefined && !deleteNames.includes(name)) {
throw new TagLabelConflictError(name, "tag", "label");
}
}
const now = Date.now();
this.db.exec("BEGIN TRANSACTION");
try {
// Update timestamp
const updateStmt = this.db.prepare(`
UPDATE variables SET updated = ? WHERE id = ?
`);
updateStmt.run(now, id);
// Delete tags and labels
if (deleteNames.length > 0) {
const deleteTagStmt = this.db.prepare(`
DELETE FROM variable_tags WHERE variable_id = ? AND key = ?
`);
const deleteLabelStmt = this.db.prepare(`
DELETE FROM variable_labels WHERE variable_id = ? AND name = ?
`);
for (const name of deleteNames) {
deleteTagStmt.run(id, name);
deleteLabelStmt.run(id, name);
}
}
// Add or update tags
if (newTagKeys.length > 0) {
const tagStmt = this.db.prepare(`
INSERT OR REPLACE INTO variable_tags (variable_id, key, value)
VALUES (?, ?, ?)
`);
for (const [key, value] of Object.entries(addTags)) {
tagStmt.run(id, key, value);
}
}
// Add labels (with conflict handling)
if (addLabels.length > 0) {
const labelStmt = this.db.prepare(`
INSERT OR IGNORE INTO variable_labels (variable_id, name)
VALUES (?, ?)
`);
for (const name of addLabels) {
labelStmt.run(id, name);
}
}
this.db.exec("COMMIT");
} catch (e) {
this.db.exec("ROLLBACK");
throw e;
}
// Return updated variable
const updated = this.get(id);
if (updated === null) {
throw new VariableNotFoundError(id);
}
return updated;
}
/**
* Close the database connection
*/
close(): void {
this.db.close();
}
}
/**
* Create a variable store
*/
export function createVariableStore(
dbPath: string,
casStore: Store,
): VariableStore {
return new VariableStore(dbPath, casStore);
}
@@ -1,740 +0,0 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createMemoryStore } from "./store.js";
import type { Store } from "./types.js";
import {
TagLabelConflictError,
VariableNotFoundError,
VariableStore,
} from "./variable-store.js";
describe("VariableStore - Tags and Labels (RFC-20 Phase 2)", () => {
let store: Store;
let varStore: VariableStore;
let dbPath: string;
let schemaHash: string;
let hashA: string;
let hashB: string;
let hashC: string;
beforeEach(async () => {
dbPath = join(tmpdir(), `test-variables-phase2-${Date.now()}.db`);
store = createMemoryStore();
// Create test schema
schemaHash = await store.put("BOOTSTRAPHASH", {
type: "object",
properties: { name: { type: "string" } },
});
// Create test CAS nodes
hashA = await store.put(schemaHash, { name: "a" });
hashB = await store.put(schemaHash, { name: "b" });
hashC = await store.put(schemaHash, { name: "c" });
varStore = new VariableStore(dbPath, store);
});
afterEach(() => {
varStore.close();
try {
unlinkSync(dbPath);
} catch {
// Ignore cleanup errors
}
});
describe("Test Group 0: Setup and Backward Compatibility", () => {
test("0.1: Create variable without tags/labels", () => {
const variable = varStore.create("uwf/thread/", hashA);
expect(variable.tags).toEqual({});
expect(variable.labels).toEqual([]);
expect(variable.id).toMatch(/^[0-9A-HJKMNP-TV-Z]{26}$/);
expect(variable.scope).toBe("uwf/thread/");
expect(variable.value).toBe(hashA);
});
test("0.2: Get variable returns empty tags and labels", () => {
const created = varStore.create("uwf/thread/", hashA);
const retrieved = varStore.get(created.id);
expect(retrieved).not.toBeNull();
expect(retrieved?.tags).toEqual({});
expect(retrieved?.labels).toEqual([]);
});
test("0.3: Create variable with initial tags", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active", workflow: "solve-issue" },
});
expect(variable.tags).toEqual({
status: "active",
workflow: "solve-issue",
});
expect(variable.labels).toEqual([]);
});
test("0.4: Create variable with initial labels", () => {
const variable = varStore.create("uwf/workflow/", hashC, {
labels: ["pinned"],
});
expect(variable.tags).toEqual({});
expect(variable.labels).toEqual(["pinned"]);
});
test("0.5: Create variable with both tags and labels", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
labels: ["pinned"],
});
expect(variable.tags).toEqual({ status: "active" });
expect(variable.labels).toEqual(["pinned"]);
});
test("0.6: Create variable with conflicting tag/label throws error", () => {
expect(() =>
varStore.create("uwf/thread/", hashA, {
tags: { workflow: "solve-issue" },
labels: ["workflow"],
}),
).toThrow(TagLabelConflictError);
});
});
describe("Test Group 1: Tag Operations", () => {
test("1.1: Add tag to existing variable", async () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
await new Promise((resolve) => setTimeout(resolve, 10));
const updated = varStore.tag(variable.id, {
add: { priority: "high" },
});
expect(updated.tags).toEqual({
status: "active",
priority: "high",
});
expect(updated.updated).toBeGreaterThan(variable.updated);
});
test("1.2: Tag same-key override", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
const updated = varStore.tag(variable.id, {
add: { status: "completed" },
});
expect(updated.tags).toEqual({ status: "completed" });
expect(Object.keys(updated.tags)).toHaveLength(1);
});
test("1.3: Delete tag using delete array", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active", workflow: "solve-issue" },
});
const updated = varStore.tag(variable.id, {
delete: ["status"],
});
expect(updated.tags).toEqual({ workflow: "solve-issue" });
expect(updated.tags.status).toBeUndefined();
});
test("1.4: Delete non-existent tag is idempotent", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
const updated = varStore.tag(variable.id, {
delete: ["nonexistent"],
});
expect(updated.tags).toEqual({ status: "active" });
});
test("1.5: Multiple tag operations in single call", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active", workflow: "solve-issue" },
});
const updated = varStore.tag(variable.id, {
add: { env: "production", region: "us-west" },
delete: ["workflow"],
});
expect(updated.tags).toEqual({
status: "active",
env: "production",
region: "us-west",
});
});
test("1.6: Delete then add same key in single operation", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
const updated = varStore.tag(variable.id, {
delete: ["status"],
add: { status: "new" },
});
expect(updated.tags).toEqual({ status: "new" });
});
});
describe("Test Group 2: Label Operations", () => {
test("2.1: Add label to existing variable", () => {
const variable = varStore.create("uwf/thread/", hashA);
const updated = varStore.tag(variable.id, {
addLabels: ["archived"],
});
expect(updated.labels).toContain("archived");
expect(updated.labels).toHaveLength(1);
});
test("2.2: Delete label using delete array", () => {
const variable = varStore.create("uwf/thread/", hashA, {
labels: ["archived", "pinned"],
});
const updated = varStore.tag(variable.id, {
delete: ["archived"],
});
expect(updated.labels).toEqual(["pinned"]);
});
test("2.3: Add duplicate label is idempotent", () => {
const variable = varStore.create("uwf/workflow/", hashC, {
labels: ["pinned"],
});
const updated = varStore.tag(variable.id, {
addLabels: ["pinned"],
});
expect(updated.labels).toEqual(["pinned"]);
});
test("2.4: Multiple label operations in single call", () => {
const variable = varStore.create("uwf/thread/", hashA, {
labels: ["archived"],
});
const updated = varStore.tag(variable.id, {
addLabels: ["experimental", "deprecated"],
delete: ["archived"],
});
expect(updated.labels).toHaveLength(2);
expect(updated.labels).toContain("experimental");
expect(updated.labels).toContain("deprecated");
expect(updated.labels).not.toContain("archived");
});
});
describe("Test Group 3: Tag/Label Mutual Exclusion", () => {
test("3.1: Label conflicts with existing tag key", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { workflow: "solve-issue" },
});
expect(() =>
varStore.tag(variable.id, {
addLabels: ["workflow"],
}),
).toThrow(TagLabelConflictError);
// Verify variable state unchanged
const retrieved = varStore.get(variable.id);
expect(retrieved?.tags).toEqual({ workflow: "solve-issue" });
expect(retrieved?.labels).toEqual([]);
});
test("3.2: Tag conflicts with existing label", () => {
const variable = varStore.create("uwf/workflow/", hashC, {
labels: ["pinned"],
});
expect(() =>
varStore.tag(variable.id, {
add: { pinned: "true" },
}),
).toThrow(TagLabelConflictError);
// Verify variable state unchanged
const retrieved = varStore.get(variable.id);
expect(retrieved?.tags).toEqual({});
expect(retrieved?.labels).toEqual(["pinned"]);
});
test("3.3: Delete then add resolves conflict", () => {
const variable = varStore.create("uwf/workflow/", hashC, {
labels: ["pinned"],
});
const updated = varStore.tag(variable.id, {
delete: ["pinned"],
add: { pinned: "true" },
});
expect(updated.tags).toEqual({ pinned: "true" });
expect(updated.labels).toEqual([]);
});
test("3.4: Simultaneous conflicting operations in same call", () => {
const variable = varStore.create("uwf/thread/", hashA);
expect(() =>
varStore.tag(variable.id, {
add: { newkey: "value" },
addLabels: ["newkey"],
}),
).toThrow(TagLabelConflictError);
});
});
describe("Test Group 4: Query - Scope Filtering", () => {
test("4.1: List with exact scope match", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
const var2 = varStore.create("uwf/thread/", hashB, {
tags: { status: "completed" },
});
varStore.create("uwf/workflow/", hashC);
const results = varStore.list({ scope: "uwf/thread/" });
expect(results).toHaveLength(2);
expect(results.map((v) => v.id)).toContain(var1.id);
expect(results.map((v) => v.id)).toContain(var2.id);
});
test("4.2: List with scope prefix match", () => {
const var1 = varStore.create("uwf/thread/", hashA);
const var2 = varStore.create("uwf/thread/", hashB);
const var3 = varStore.create("uwf/workflow/", hashC);
const results = varStore.list({ scope: "uwf/" });
expect(results).toHaveLength(3);
expect(results.map((v) => v.id)).toContain(var1.id);
expect(results.map((v) => v.id)).toContain(var2.id);
expect(results.map((v) => v.id)).toContain(var3.id);
});
test("4.3: List all variables (no scope filter)", () => {
const var1 = varStore.create("uwf/thread/", hashA);
const var2 = varStore.create("app/config/", hashB);
const results = varStore.list();
expect(results).toHaveLength(2);
expect(results.map((v) => v.id)).toContain(var1.id);
expect(results.map((v) => v.id)).toContain(var2.id);
});
test("4.4: List with non-matching scope returns empty", () => {
varStore.create("uwf/thread/", hashA);
const results = varStore.list({ scope: "app/config/" });
expect(results).toEqual([]);
});
});
describe("Test Group 5: Query - Tag Filtering", () => {
test("5.1: Filter by tag key-value pair", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "completed" },
});
const var2 = varStore.create("uwf/thread/", hashB, {
tags: { status: "completed" },
});
varStore.create("uwf/thread/", hashC, {
tags: { status: "active" },
});
const results = varStore.list({
tags: { status: "completed" },
});
expect(results).toHaveLength(2);
expect(results.map((v) => v.id)).toContain(var1.id);
expect(results.map((v) => v.id)).toContain(var2.id);
});
test("5.2: Filter by non-existent tag returns empty", () => {
varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
const results = varStore.list({
tags: { nonexistent: "value" },
});
expect(results).toEqual([]);
});
test("5.3: Multiple tag filters use AND logic", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "completed", priority: "high" },
});
varStore.create("uwf/thread/", hashB, {
tags: { status: "completed", priority: "low" },
});
varStore.create("uwf/thread/", hashC, {
tags: { status: "active", priority: "high" },
});
const results = varStore.list({
tags: { status: "completed", priority: "high" },
});
expect(results).toHaveLength(1);
expect(results[0]?.id).toBe(var1.id);
});
});
describe("Test Group 6: Query - Label Filtering", () => {
test("6.1: Filter by label", () => {
const var1 = varStore.create("uwf/workflow/", hashA, {
labels: ["pinned"],
});
varStore.create("uwf/workflow/", hashB);
const results = varStore.list({
labels: ["pinned"],
});
expect(results).toHaveLength(1);
expect(results[0]?.id).toBe(var1.id);
});
test("6.2: Filter by non-existent label returns empty", () => {
varStore.create("uwf/workflow/", hashA, {
labels: ["pinned"],
});
const results = varStore.list({
labels: ["nonexistent"],
});
expect(results).toEqual([]);
});
test("6.3: Multiple label filters use AND logic", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
labels: ["experimental", "deprecated"],
});
varStore.create("uwf/thread/", hashB, {
labels: ["experimental"],
});
const results = varStore.list({
labels: ["experimental", "deprecated"],
});
expect(results).toHaveLength(1);
expect(results[0]?.id).toBe(var1.id);
});
});
describe("Test Group 7: Query - Combined Filtering", () => {
test("7.1: Scope + tag filter", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "completed" },
});
const var2 = varStore.create("uwf/thread/", hashB, {
tags: { status: "completed" },
});
varStore.create("uwf/workflow/", hashC, {
tags: { status: "completed" },
});
const results = varStore.list({
scope: "uwf/thread/",
tags: { status: "completed" },
});
expect(results).toHaveLength(2);
expect(results.map((v) => v.id)).toContain(var1.id);
expect(results.map((v) => v.id)).toContain(var2.id);
});
test("7.2: Scope + label filter", () => {
const var1 = varStore.create("uwf/workflow/", hashA, {
labels: ["pinned"],
});
varStore.create("uwf/thread/", hashB, {
labels: ["pinned"],
});
const results = varStore.list({
scope: "uwf/workflow/",
labels: ["pinned"],
});
expect(results).toHaveLength(1);
expect(results[0]?.id).toBe(var1.id);
});
test("7.3: Scope + multiple filters", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "completed", priority: "high" },
});
varStore.create("uwf/thread/", hashB, {
tags: { status: "completed" },
});
varStore.create("uwf/workflow/", hashC, {
tags: { status: "completed", priority: "high" },
});
const results = varStore.list({
scope: "uwf/",
tags: { status: "completed", priority: "high" },
});
expect(results).toHaveLength(2);
expect(results.map((v) => v.id)).toContain(var1.id);
});
test("7.4: Combined filters with no matches", () => {
varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
const results = varStore.list({
scope: "app/",
tags: { status: "completed" },
});
expect(results).toEqual([]);
});
});
describe("Test Group 8: Edge Cases and Error Handling", () => {
test("8.1: Tag operation on non-existent variable", () => {
const fakeId = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
expect(() =>
varStore.tag(fakeId, {
add: { key: "value" },
}),
).toThrow(VariableNotFoundError);
});
test("8.2: Special characters in tag keys/values", () => {
const variable = varStore.create("uwf/thread/", hashA);
const updated = varStore.tag(variable.id, {
add: { "env:region": "prod-us_west.2" },
});
expect(updated.tags).toEqual({ "env:region": "prod-us_west.2" });
});
test("8.3: Unicode in tag/label names", () => {
const variable = varStore.create("uwf/thread/", hashA);
const updated = varStore.tag(variable.id, {
add: { : "中文" },
addLabels: ["测试"],
});
expect(updated.tags).toEqual({ : "中文" });
expect(updated.labels).toContain("测试");
// Verify persistence
const retrieved = varStore.get(variable.id);
expect(retrieved?.tags).toEqual({ : "中文" });
expect(retrieved?.labels).toContain("测试");
});
test("8.4: Empty tag key or value", () => {
const variable = varStore.create("uwf/thread/", hashA);
// Empty key
const updated1 = varStore.tag(variable.id, {
add: { "": "value" },
});
expect(updated1.tags).toEqual({ "": "value" });
// Empty value
const updated2 = varStore.tag(variable.id, {
add: { key: "" },
});
expect(updated2.tags.key).toBe("");
});
test("8.5: Very long tag key/value", () => {
const variable = varStore.create("uwf/thread/", hashA);
const longKey = "k".repeat(1000);
const longValue = "v".repeat(1000);
const updated = varStore.tag(variable.id, {
add: { [longKey]: longValue },
});
expect(updated.tags[longKey]).toBe(longValue);
});
});
describe("Test Group 9: Database Integrity", () => {
test("9.1: Cascade delete for tags", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active", workflow: "solve-issue" },
});
varStore.delete(variable.id);
// Verify variable is deleted
const retrieved = varStore.get(variable.id);
expect(retrieved).toBeNull();
});
test("9.2: Cascade delete for labels", () => {
const variable = varStore.create("uwf/workflow/", hashA, {
labels: ["pinned", "archived"],
});
varStore.delete(variable.id);
const retrieved = varStore.get(variable.id);
expect(retrieved).toBeNull();
});
test("9.3: Tag update preserves other variable data", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
varStore.tag(variable.id, {
add: { priority: "high" },
});
const retrieved = varStore.get(variable.id);
expect(retrieved?.id).toBe(variable.id);
expect(retrieved?.scope).toBe(variable.scope);
expect(retrieved?.value).toBe(variable.value);
expect(retrieved?.schema).toBe(variable.schema);
expect(retrieved?.created).toBe(variable.created);
});
});
describe("Test Group 10: Batch Operations and Atomicity", () => {
test("10.1: Atomic tag operations", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { status: "active", workflow: "solve-issue" },
});
const updated = varStore.tag(variable.id, {
add: { priority: "low" },
addLabels: ["archived"],
delete: ["status"],
});
expect(updated.tags).toEqual({
workflow: "solve-issue",
priority: "low",
});
expect(updated.labels).toContain("archived");
});
test("10.2: Rollback on conflict error", () => {
const variable = varStore.create("uwf/thread/", hashA, {
tags: { workflow: "solve-issue" },
});
expect(() =>
varStore.tag(variable.id, {
add: { priority: "high" },
addLabels: ["workflow"], // Conflict!
}),
).toThrow(TagLabelConflictError);
// Verify NO changes applied
const retrieved = varStore.get(variable.id);
expect(retrieved?.tags).toEqual({ workflow: "solve-issue" });
expect(retrieved?.labels).toEqual([]);
});
});
describe("Test Group 11: Integration Tests", () => {
test("11.1: Full workflow with tags and labels", async () => {
// Create with initial tags
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "active" },
});
await new Promise((resolve) => setTimeout(resolve, 10));
// Add more tags
varStore.tag(var1.id, {
add: { priority: "high", workflow: "solve-issue" },
});
// Add labels
varStore.tag(var1.id, {
addLabels: ["pinned"],
});
// Update variable value
const updated = varStore.update(var1.id, hashB);
// Verify tags/labels preserved
expect(updated.tags).toEqual({
status: "active",
priority: "high",
workflow: "solve-issue",
});
expect(updated.labels).toContain("pinned");
// Delete variable
varStore.delete(var1.id);
// Verify deletion
const retrieved = varStore.get(var1.id);
expect(retrieved).toBeNull();
});
test("11.2: Query with complex filtering", () => {
const var1 = varStore.create("uwf/thread/", hashA, {
tags: { status: "completed", priority: "high" },
labels: ["archived"],
});
varStore.create("uwf/thread/", hashB, {
tags: { status: "completed", priority: "low" },
});
varStore.create("uwf/workflow/", hashC, {
tags: { status: "completed", priority: "high" },
labels: ["archived"],
});
const results = varStore.list({
scope: "uwf/thread/",
tags: { status: "completed", priority: "high" },
labels: ["archived"],
});
expect(results).toHaveLength(1);
expect(results[0]?.id).toBe(var1.id);
});
});
});
-20
View File
@@ -1,20 +0,0 @@
import type { Hash } from "./types.js";
/**
* ULID identifier (26-character Crockford Base32)
*/
export type VariableId = string;
/**
* Variable: mutable binding to an immutable CAS node
*/
export type Variable = {
id: VariableId;
scope: string; // hierarchical path, must end with /
value: Hash; // CAS node hash
schema: Hash; // extracted from value's CAS node.type
created: number; // epoch ms
updated: number; // epoch ms
tags: Record<string, string>; // key-value pairs
labels: string[]; // bare identifiers
};