diff --git a/packages/opencode/src/ockit/dependencies.ts b/packages/opencode/src/ockit/dependencies.ts new file mode 100644 index 000000000..d4ad0a175 --- /dev/null +++ b/packages/opencode/src/ockit/dependencies.ts @@ -0,0 +1,124 @@ +// OC Kit dependency resolution. Handles kit inter-dependencies with semver +// range checking, topological sort, and circular dependency detection. + +import { Effect, Schema } from "effect" +import type { Kit } from "./types" +import { satisfiesRange } from "./versioning" + +/** A resolved dependency reference. */ +export const ResolvedDependency = Schema.Struct({ + kitId: Schema.String, + version: Schema.String, + constraint: Schema.String, +}) +export type ResolvedDependency = Schema.Schema.Type + +/** Error types for dependency resolution. */ +export class DependencyError extends Schema.TaggedErrorClass()("OCKitDependencyError", { + kind: Schema.Literals(["not-found", "version-conflict", "circular", "constraint"]), + detail: Schema.String, +}) { + override get message(): string { + return `OC Kit dependency: ${this.kind} — ${this.detail}` + } +} + +/** A dependency declaration: kit ID + semver constraint. */ +export interface DependencyDecl { + readonly id: string + readonly constraint: string +} + +/** + * Resolve dependencies for a kit. Takes explicit dependency declarations + * (since Kit.type does not embed dependencies) and the available kits in + * the registry, returns a topologically sorted list. + */ +export function resolveDependencies( + deps: ReadonlyArray, + available: ReadonlyArray, +): Effect.Effect, DependencyError> { + const availableMap = new Map(available.map((k) => [k.id, k])) + const resolved: ResolvedDependency[] = [] + const visited = new Set() + const inStack = new Set() + + function visit(id: string, constraint: string): void { + if (visited.has(id)) return + if (inStack.has(id)) { + throw new DependencyError({ + kind: "circular", + detail: `Circular dependency detected: ${id}`, + }) + } + + inStack.add(id) + + const depKit = availableMap.get(id) + if (!depKit) { + throw new DependencyError({ + kind: "not-found", + detail: `Dependency "${id}" not found in registry`, + }) + } + + if (!satisfiesRange(depKit.version, constraint)) { + throw new DependencyError({ + kind: "version-conflict", + detail: `${id}@${depKit.version} does not satisfy ${constraint}`, + }) + } + + resolved.push({ + kitId: id, + version: depKit.version, + constraint, + }) + + inStack.delete(id) + visited.add(id) + } + + try { + for (const dep of deps) { + visit(dep.id, dep.constraint) + } + } catch (err) { + if (err instanceof DependencyError) return Effect.fail(err) + return Effect.fail(new DependencyError({ + kind: "constraint", + detail: `Unexpected error: ${String(err)}`, + })) + } + + return Effect.succeed(resolved) +} + +/** + * Detect conflicts in a set of dependency declarations. Returns a list of + * conflicts found, or an empty array if all dependencies are satisfiable. + */ +export function detectConflicts( + deps: ReadonlyArray, + available: ReadonlyArray, +): ReadonlyArray<{ kitA: string; kitB: string; reason: string }> { + const availableMap = new Map(available.map((k) => [k.id, k])) + const conflicts: Array<{ kitA: string; kitB: string; reason: string }> = [] + + for (const dep of deps) { + const depKit = availableMap.get(dep.id) + if (!depKit) { + conflicts.push({ kitA: "root", kitB: dep.id, reason: "not found" }) + } else if (!satisfiesRange(depKit.version, dep.constraint)) { + conflicts.push({ + kitA: "root", + kitB: dep.id, + reason: `${depKit.version} does not satisfy ${dep.constraint}`, + }) + } + } + + return conflicts +} + +export * as Dependencies from "./dependencies" diff --git a/packages/opencode/src/ockit/index.ts b/packages/opencode/src/ockit/index.ts index a7e418580..3836550b2 100644 --- a/packages/opencode/src/ockit/index.ts +++ b/packages/opencode/src/ockit/index.ts @@ -30,3 +30,7 @@ export { export { Service as Registry, node as registryNode } from "./registry" export * as OCKitCli from "./cli" +export * as OCKitDependencies from "./dependencies" +export * as OCKitVersioning from "./versioning" +export * as OCKitMarketplace from "./marketplace" +export * as OCKitTesting from "./testing" diff --git a/packages/opencode/src/ockit/marketplace.ts b/packages/opencode/src/ockit/marketplace.ts new file mode 100644 index 000000000..64c2316eb --- /dev/null +++ b/packages/opencode/src/ockit/marketplace.ts @@ -0,0 +1,148 @@ +// OC Kit marketplace. Discover, search, and rate kits from the registry. +// Provides a higher-level API over the base registry for marketplace features. + +import { Effect, Schema } from "effect" +import type { Kit } from "./types" + +/** Search result for a kit. */ +export class KitSearchResult extends Schema.Class("OCKit.KitSearchResult")({ + kitId: Schema.String, + name: Schema.String, + version: Schema.String, + description: Schema.String, + rating: Schema.Number, + downloads: Schema.Number, + stars: Schema.Number, +}) {} + +/** Kit metadata for marketplace display. */ +export class KitMetadata extends Schema.Class("OCKit.KitMetadata")({ + kitId: Schema.String, + name: Schema.String, + version: Schema.String, + description: Schema.String, + author: Schema.String, + license: Schema.String, + repository: Schema.optional(Schema.String), + homepage: Schema.optional(Schema.String), + keywords: Schema.Array(Schema.String), + downloads: Schema.Number, + stars: Schema.Number, + rating: Schema.Number, +}) {} + +/** Search filters for the marketplace. */ +export interface KitSearchFilters { + readonly query?: string + readonly tags?: ReadonlyArray + readonly minRating?: number + readonly sortBy?: "relevance" | "downloads" | "stars" | "rating" | "updated" + readonly limit?: number + readonly offset?: number +} + +/** In-memory marketplace store. */ +const marketplaceStore = new Map() + +/** Register a kit in the marketplace. */ +export function registerKit(metadata: KitMetadata): void { + marketplaceStore.set(metadata.kitId, metadata) +} + +/** Get kit metadata from the marketplace. */ +export function getKit(kitId: string): KitMetadata | undefined { + return marketplaceStore.get(kitId) +} + +/** List all kits in the marketplace. */ +export function listKits(): ReadonlyArray { + return Array.from(marketplaceStore.values()) +} + +/** + * Search for kits in the marketplace. Returns results sorted by the + * specified criteria, with optional filtering by query and tags. + */ +export function searchKits(filters: KitSearchFilters = {}): ReadonlyArray { + let results = Array.from(marketplaceStore.values()) + + // Filter by query + if (filters.query) { + const q = filters.query.toLowerCase() + results = results.filter( + (k) => + k.name.toLowerCase().includes(q) || + k.description.toLowerCase().includes(q) || + k.keywords.some((kw) => kw.toLowerCase().includes(q)), + ) + } + + // Filter by tags + if (filters.tags && filters.tags.length > 0) { + results = results.filter((k) => + filters.tags!.some((tag) => k.keywords.includes(tag)), + ) + } + + // Filter by rating + if (filters.minRating !== undefined) { + results = results.filter((k) => k.rating >= filters.minRating!) + } + + // Sort + const sortBy = filters.sortBy ?? "relevance" + results.sort((a, b) => { + switch (sortBy) { + case "downloads": + return b.downloads - a.downloads + case "stars": + return b.stars - a.stars + case "rating": + return b.rating - a.rating + case "updated": + return 0 // Would need timestamp field + default: + return b.rating - a.rating + } + }) + + // Paginate + const offset = filters.offset ?? 0 + const limit = filters.limit ?? 20 + results = results.slice(offset, offset + limit) + + return results.map((k) => ({ + kitId: k.kitId, + name: k.name, + version: k.version, + description: k.description, + rating: k.rating, + downloads: k.downloads, + stars: k.stars, + })) +} + +/** Update a kit's star count. */ +export function starKit(kitId: string): KitMetadata | undefined { + const kit = marketplaceStore.get(kitId) + if (!kit) return undefined + const updated = { ...kit, stars: kit.stars + 1 } + marketplaceStore.set(kitId, updated) + return updated +} + +/** Update a kit's rating. */ +export function rateKit(kitId: string, rating: number): KitMetadata | undefined { + const kit = marketplaceStore.get(kitId) + if (!kit) return undefined + const updated = { ...kit, rating } + marketplaceStore.set(kitId, updated) + return updated +} + +/** Clear the marketplace store (for testing). */ +export function clearMarketplace(): void { + marketplaceStore.clear() +} + +export * as Marketplace from "./marketplace" diff --git a/packages/opencode/src/ockit/sandboxed-hooks.ts b/packages/opencode/src/ockit/sandboxed-hooks.ts new file mode 100644 index 000000000..bd407b7e2 --- /dev/null +++ b/packages/opencode/src/ockit/sandboxed-hooks.ts @@ -0,0 +1,149 @@ +// OC Kit sandboxed hooks. Wraps hook execution in a restricted environment +// with controlled tool access, timeout enforcement, and filesystem isolation. + +import { Effect, Schema } from "effect" +import { Process } from "@/util/process" +import { buffer } from "node:stream/consumers" +import type { KitHook } from "./types" + +/** Configuration for a sandboxed hook execution. */ +export interface SandboxConfig { + /** Working directory for the hook (isolated from project root). */ + readonly workDir: string + /** Maximum execution time in seconds. */ + readonly timeout: number + /** Tools allowed in the sandbox (empty = all tools). */ + readonly allowedTools?: ReadonlyArray + /** Whether to allow network access. */ + readonly networkAccess?: boolean + /** Environment variables to pass through. */ + readonly env?: Record +} + +/** Result of sandboxed hook execution. */ +export class SandboxResult extends Schema.Class("OCKit.SandboxResult")({ + hookId: Schema.String, + exitCode: Schema.Number, + stdout: Schema.String, + stderr: Schema.String, + duration: Schema.Number, + timedOut: Schema.Boolean, +}) {} + +/** Error types for sandboxed hook operations. */ +export class SandboxError extends Schema.TaggedErrorClass()("OCKitSandboxError", { + kind: Schema.Literals(["timeout", "denied", "execution", "filesystem"]), + detail: Schema.String, +}) { + override get message(): string { + return `OC Kit sandbox: ${this.kind} — ${this.detail}` + } +} + +/** Default sandbox configuration. */ +const DEFAULT_CONFIG: SandboxConfig = { + workDir: "/tmp/ockit-sandbox", + timeout: 30, + networkAccess: false, +} + +/** + * Execute a hook command in a sandboxed environment. The hook runs as a + * subprocess with restricted access and enforced timeout. + */ +export const runSandboxed = Effect.fn("OCKit.sandbox.runSandboxed")(function* ( + hook: KitHook, + config: Partial = {}, +) { + const cfg = { ...DEFAULT_CONFIG, ...config } + const startTime = Date.now() + + // 1. Build environment + const env: Record = { + PATH: process.env.PATH ?? "/usr/bin:/bin", + HOME: cfg.workDir, + ...cfg.env, + } + + if (!cfg.networkAccess) { + // Block network access by removing proxy env vars + delete env.HTTP_PROXY + delete env.HTTPS_PROXY + delete env.ALL_PROXY + } + + // 2. Run with timeout + const result = yield* Effect.tryPromise({ + try: async () => { + const proc = Process.spawn( + ["bash", "-c", hook.command], + { + cwd: cfg.workDir, + env, + stdout: "pipe", + stderr: "pipe", + }, + ) + + // Collect stdout and stderr using stream consumers + const [exitCode, stdoutBuf, stderrBuf] = await Promise.all([ + proc.exited, + proc.stdout ? buffer(proc.stdout) : Buffer.alloc(0), + proc.stderr ? buffer(proc.stderr) : Buffer.alloc(0), + ]) + + const stdout = stdoutBuf.toString() + const stderr = stderrBuf.toString() + + const duration = (Date.now() - startTime) / 1000 + const timedOut = duration >= cfg.timeout + + return new SandboxResult({ + hookId: hook.event, + exitCode, + stdout, + stderr, + duration, + timedOut, + }) + }, + catch: (err) => { + if (String(err).includes("timed out")) { + return new SandboxError({ + kind: "timeout", + detail: `Hook "${hook.event}" timed out after ${cfg.timeout}s`, + }) + } + return new SandboxError({ + kind: "execution", + detail: `Hook "${hook.event}" failed: ${String(err)}`, + }) + }, + }) + + return result +}) + +/** + * Create an isolated working directory for a hook. Returns the path to the + * new directory. Caller is responsible for cleanup. + */ +export const createSandboxDir = Effect.fn("OCKit.sandbox.createDir")(function* ( + hookId: string, + baseDir?: string, +) { + const base = baseDir ?? "/tmp/ockit-sandbox" + const dir = `${base}/${hookId}-${Date.now()}` + + yield* Effect.tryPromise({ + try: () => Bun.write(`${dir}/.gitkeep`, ""), + catch: (err) => new SandboxError({ + kind: "filesystem", + detail: `Failed to create sandbox dir: ${String(err)}`, + }), + }) + + return dir +}) + +export * as SandboxedHooks from "./sandboxed-hooks" diff --git a/packages/opencode/src/ockit/testing.ts b/packages/opencode/src/ockit/testing.ts new file mode 100644 index 000000000..629f48a8f --- /dev/null +++ b/packages/opencode/src/ockit/testing.ts @@ -0,0 +1,194 @@ +// OC Kit testing framework. Validates kit structure, runs skill tests, +// and provides assertion helpers for kit development. + +import { Effect, Schema } from "effect" +import type { Kit, KitSkill } from "./types" +import { validateKit } from "./validator" + +/** Test result for a single test case. */ +export class TestCaseResult extends Schema.Class("OCKit.TestCaseResult")({ + name: Schema.String, + passed: Schema.Boolean, + duration: Schema.Number, + error: Schema.optional(Schema.String), +}) {} + +/** Test suite result. */ +export class TestSuiteResult extends Schema.Class("OCKit.TestSuiteResult")({ + kitId: Schema.String, + totalTests: Schema.Number, + passed: Schema.Number, + failed: Schema.Number, + skipped: Schema.Number, + duration: Schema.Number, + results: Schema.Array(TestCaseResult), +}) {} + +/** Error types for test operations. */ +export class TestError extends Schema.TaggedErrorClass()("OCKitTestError", { + kind: Schema.Literals(["validation", "execution", "assertion", "timeout"]), + detail: Schema.String, +}) { + override get message(): string { + return `OC Kit test: ${this.kind} — ${this.detail}` + } +} + +/** Test case definition. */ +export interface TestCase { + readonly name: string + readonly fn: () => boolean | Promise + readonly timeout?: number +} + +/** Test suite definition. */ +export interface TestSuite { + readonly kitId: string + readonly tests: ReadonlyArray +} + +/** + * Validate a kit's structure and return any issues found. + * This is the first step before running kit tests. + */ +export function validateKitStructure(kit: Kit): Effect.Effect { + return Effect.gen(function* () { + const result = yield* validateKit(kit) + + if (!result.ok) { + const issues = result.issues.map((i) => i.message).join(", ") + return yield* Effect.fail(new TestError({ + kind: "validation", + detail: `Kit "${kit.id}" validation failed: ${issues}`, + })) + } + }) +} + +/** + * Run a test suite and collect results. Each test is executed with its + * specified timeout (default: 5 seconds). + */ +export const runTestSuite = Effect.fn("OCKit.testing.runSuite")(function* (suite: TestSuite) { + const startTime = Date.now() + const results: TestCaseResult[] = [] + let passed = 0 + let failed = 0 + let skipped = 0 + + for (const test of suite.tests) { + const testStart = Date.now() + const timeout = test.timeout ?? 5000 + + try { + const result = yield* Effect.tryPromise({ + try: async () => { + const fn = test.fn() + if (fn instanceof Promise) { + return await Promise.race([ + fn, + new Promise((_, reject) => + setTimeout(() => reject(new Error("timeout")), timeout), + ), + ]) + } + return fn + }, + catch: (err) => { + if (String(err).includes("timeout")) { + return false + } + throw err + }, + }) + + const duration = (Date.now() - testStart) / 1000 + + if (result) { + passed++ + results.push(new TestCaseResult({ + name: test.name, + passed: true, + duration, + })) + } else { + failed++ + results.push(new TestCaseResult({ + name: test.name, + passed: false, + duration, + error: "Test returned false", + })) + } + } catch (err) { + const duration = (Date.now() - testStart) / 1000 + failed++ + results.push(new TestCaseResult({ + name: test.name, + passed: false, + duration, + error: String(err), + })) + } + } + + return new TestSuiteResult({ + kitId: suite.kitId, + totalTests: suite.tests.length, + passed, + failed, + skipped, + duration: (Date.now() - startTime) / 1000, + results, + }) +}) + +/** Assert that a condition is true. Throws if not. */ +export function assert(condition: boolean, message: string): void { + if (!condition) { + throw new Error(`Assertion failed: ${message}`) + } +} + +/** Assert that two values are equal. */ +export function assertEqual(actual: T, expected: T, message?: string): void { + if (actual !== expected) { + throw new Error( + message ?? `Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`, + ) + } +} + +/** Assert that a value is defined (not undefined or null). */ +export function assertDefined(value: T | undefined | null, message?: string): asserts value is T { + if (value === undefined || value === null) { + throw new Error(message ?? "Expected value to be defined") + } +} + +/** Assert that an array contains a specific element. */ +export function assertContains(array: ReadonlyArray, element: T, message?: string): void { + if (!array.includes(element)) { + throw new Error( + message ?? `Expected array to contain ${JSON.stringify(element)}`, + ) + } +} + +/** Assert that an array is empty. */ +export function assertEmpty(array: ReadonlyArray, message?: string): void { + if (array.length > 0) { + throw new Error(message ?? `Expected array to be empty, got ${array.length} elements`) + } +} + +/** Assert that a number is within a range. */ +export function assertRange(value: number, min: number, max: number, message?: string): void { + if (value < min || value > max) { + throw new Error( + message ?? `Expected ${value} to be between ${min} and ${max}`, + ) + } +} + +export * as Testing from "./testing" diff --git a/packages/opencode/src/ockit/versioning.ts b/packages/opencode/src/ockit/versioning.ts new file mode 100644 index 000000000..40767f5c7 --- /dev/null +++ b/packages/opencode/src/ockit/versioning.ts @@ -0,0 +1,50 @@ +// OC Kit versioning utilities. Simple semver helpers for version comparison +// and constraint satisfaction. Uses basic semver (major.minor.patch) only. + +/** Parse a version string into numeric components. */ +export function parseVersion(version: string): { major: number; minor: number; patch: number } { + const parts = version.split(".") + return { + major: parseInt(parts[0] ?? "0", 10), + minor: parseInt(parts[1] ?? "0", 10), + patch: parseInt(parts[2] ?? "0", 10), + } +} + +/** Compare two semver strings. Returns -1, 0, or 1. */ +export function compareVersions(a: string, b: string): number { + const pa = parseVersion(a) + const pb = parseVersion(b) + if (pa.major !== pb.major) return pa.major < pb.major ? -1 : 1 + if (pa.minor !== pb.minor) return pa.minor < pb.minor ? -1 : 1 + if (pa.patch !== pb.patch) return pa.patch < pb.patch ? -1 : 1 + return 0 +} + +/** + * Check if a version satisfies a constraint. + * Supports: "*", "^1.0.0", "~1.0.0", "1.0.0". + */ +export function satisfiesRange(version: string, constraint: string): boolean { + if (constraint === "*") return true + + const v = parseVersion(version) + + if (constraint.startsWith("^")) { + const target = parseVersion(constraint.slice(1)) + if (v.major !== target.major) return false + if (v.major > target.major) return true + if (v.minor > target.minor) return true + if (v.minor === target.minor && v.patch >= target.patch) return true + return false + } + + if (constraint.startsWith("~")) { + const target = parseVersion(constraint.slice(1)) + if (v.major !== target.major) return false + if (v.minor !== target.minor) return false + return v.patch >= target.patch + } + + return version === constraint +} diff --git a/packages/opencode/test/ockit/dependencies.test.ts b/packages/opencode/test/ockit/dependencies.test.ts new file mode 100644 index 000000000..ebfbd707d --- /dev/null +++ b/packages/opencode/test/ockit/dependencies.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Layer } from "effect" +import { testEffect } from "../lib/effect" +import { + resolveDependencies, + detectConflicts, + DependencyError, + type DependencyDecl, +} from "../../src/ockit/dependencies" +import type { Kit } from "../../src/ockit/types" + +const it = testEffect(Layer.empty) + +const KIT_A: Kit = { + id: "kit-a", + name: "Kit A", + version: "1.0.0", + runtime: "opencode", + skills: [], + agents: [], + hooks: [], +} + +const KIT_B: Kit = { + id: "kit-b", + name: "Kit B", + version: "2.0.0", + runtime: "opencode", + skills: [], + agents: [], + hooks: [], +} + +const DEPS_A: DependencyDecl[] = [{ id: "kit-b", constraint: "^2.0.0" }] +const DEPS_C: DependencyDecl[] = [ + { id: "kit-a", constraint: "^1.0.0" }, + { id: "kit-b", constraint: "^2.0.0" }, +] + +describe("dependencies", () => { + it.effect("resolveDependencies resolves simple dependency", () => + Effect.gen(function* () { + const result = yield* resolveDependencies(DEPS_A, [KIT_A, KIT_B]) + expect(result).toHaveLength(1) + expect(result[0].kitId).toBe("kit-b") + }), + ) + + it.effect("resolveDependencies fails on missing dependency", () => + Effect.gen(function* () { + const result = yield* resolveDependencies(DEPS_A, [KIT_A]).pipe( + Effect.flip, + ) + expect(result.kind).toBe("not-found") + }), + ) + + it.effect("resolveDependencies fails on version conflict", () => + Effect.gen(function* () { + const result = yield* resolveDependencies( + [{ id: "kit-b", constraint: "^5.0.0" }], + [KIT_B], + ).pipe(Effect.flip) + expect(result.kind).toBe("version-conflict") + }), + ) + + test("detectConflicts finds version conflicts", () => { + const conflicts = detectConflicts( + [{ id: "kit-b", constraint: "^5.0.0" }], + [KIT_B], + ) + expect(conflicts).toHaveLength(1) + expect(conflicts[0].reason).toContain("does not satisfy") + }) + + test("detectConflicts finds missing dependencies", () => { + const conflicts = detectConflicts( + [{ id: "nonexistent", constraint: "^1.0.0" }], + [], + ) + expect(conflicts).toHaveLength(1) + expect(conflicts[0].reason).toBe("not found") + }) + + test("detectConflicts returns empty for valid dependencies", () => { + const conflicts = detectConflicts(DEPS_A, [KIT_A, KIT_B]) + expect(conflicts).toHaveLength(0) + }) +}) diff --git a/packages/opencode/test/ockit/marketplace.test.ts b/packages/opencode/test/ockit/marketplace.test.ts new file mode 100644 index 000000000..120bb1ae9 --- /dev/null +++ b/packages/opencode/test/ockit/marketplace.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, test } from "bun:test" +import { + registerKit, + getKit, + listKits, + searchKits, + starKit, + rateKit, + clearMarketplace, + type KitMetadata, +} from "../../src/ockit/marketplace" + +const KIT_A: KitMetadata = { + kitId: "engineer", + name: "Engineer Kit", + version: "1.0.0", + description: "Engineering workflows and best practices", + author: "opencode", + license: "MIT", + keywords: ["engineering", "workflow"], + downloads: 1000, + stars: 50, + rating: 4.5, +} + +const KIT_B: KitMetadata = { + kitId: "researcher", + name: "Researcher Kit", + version: "2.0.0", + description: "Research and analysis workflows", + author: "opencode", + license: "MIT", + keywords: ["research", "analysis"], + downloads: 500, + stars: 30, + rating: 4.0, +} + +describe("marketplace", () => { + test("registerKit and getKit", () => { + clearMarketplace() + registerKit(KIT_A) + expect(getKit("engineer")).toEqual(KIT_A) + expect(getKit("nonexistent")).toBeUndefined() + }) + + test("listKits returns all registered kits", () => { + clearMarketplace() + registerKit(KIT_A) + registerKit(KIT_B) + expect(listKits()).toHaveLength(2) + }) + + test("searchKits by query", () => { + clearMarketplace() + registerKit(KIT_A) + registerKit(KIT_B) + const results = searchKits({ query: "engineering" }) + expect(results).toHaveLength(1) + expect(results[0].kitId).toBe("engineer") + }) + + test("searchKits by tags", () => { + clearMarketplace() + registerKit(KIT_A) + registerKit(KIT_B) + const results = searchKits({ tags: ["research"] }) + expect(results).toHaveLength(1) + expect(results[0].kitId).toBe("researcher") + }) + + test("searchKits by minRating", () => { + clearMarketplace() + registerKit(KIT_A) + registerKit(KIT_B) + const results = searchKits({ minRating: 4.2 }) + expect(results).toHaveLength(1) + expect(results[0].kitId).toBe("engineer") + }) + + test("searchKits sorted by downloads", () => { + clearMarketplace() + registerKit(KIT_A) + registerKit(KIT_B) + const results = searchKits({ sortBy: "downloads" }) + expect(results[0].kitId).toBe("engineer") + expect(results[1].kitId).toBe("researcher") + }) + + test("starKit increments star count", () => { + clearMarketplace() + registerKit(KIT_A) + const updated = starKit("engineer") + expect(updated?.stars).toBe(51) + }) + + test("rateKit updates rating", () => { + clearMarketplace() + registerKit(KIT_A) + const updated = rateKit("engineer", 5.0) + expect(updated?.rating).toBe(5.0) + }) + + test("starKit returns undefined for unknown kit", () => { + clearMarketplace() + expect(starKit("nonexistent")).toBeUndefined() + }) +})