Add project KV store for ephemeral state management

This commit is contained in:
Chris Scott committed 2026-03-07 22:46:24 -05:00
1 parent 35556ed44a
commit f03670dacf
14 files changed
+562 -6

No files matched your search

+13
View File
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.0.16] - 2026-03-07
### Added
- Project KV store for ephemeral project state with TTL management
- `memory-kv-set`, `memory-kv-get`, `memory-kv-delete`, `memory-kv-list` tools for managing project state
- Automatic cleanup of expired KV entries (30-minute interval)
- Default 24-hour TTL for KV entries
### Fixed
- KV `list()` method now handles malformed JSON data gracefully instead of throwing, consistent with `get()` behavior
## [0.0.12] - 2026-03-05
### Added
+14
View File
@@ -33,6 +33,7 @@ The local embedding model downloads automatically on install. For API-based embe
- **Automatic Deduplication** - Prevents duplicates via exact match and semantic similarity detection
- **Compaction Context Injection** - Injects conventions and decisions into session compaction for seamless continuity
- **Automatic Memory Injection** - Injects relevant project memories into user messages via semantic search with distance filtering and caching
- **Project KV Store** - Ephemeral key-value storage with TTL management for project state
- **Bundled Agents** - Ships with Code, Architect, and Memory agents preconfigured for memory-aware workflows
- **CLI Tools** - Export, import, list, stats, and cleanup commands via `ocm-mem` binary
- **Dimension Mismatch Detection** - Detects embedding model changes and guides recovery via reindex
@@ -54,6 +55,8 @@ The Architect agent operates in read-only mode (`temperature: 0.0`, all edits de
## Tools
### Memory Tools
| Tool | Description |
|------|-------------|
| `memory-read` | Search and retrieve project memories with semantic search |
@@ -63,6 +66,17 @@ The Architect agent operates in read-only mode (`temperature: 0.0`, all edits de
| `memory-health` | Health check or full reindex of the memory store |
| `memory-plan-execute` | Create a new Code session and send an approved plan as the first prompt |
### Project KV Tools
Ephemeral key-value storage for project state with automatic TTL-based expiration.
| Tool | Description |
|------|-------------|
| `memory-kv-set` | Store a value with optional TTL (default 24 hours) |
| `memory-kv-get` | Retrieve a value by key |
| `memory-kv-delete` | Delete a value by key |
| `memory-kv-list` | List all active KV entries for the project |
## CLI
Manage memories using the `ocm-mem` CLI. The CLI auto-detects the project ID from git and resolves the database path automatically.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.15",
"version": "0.0.16",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
+10
View File
@@ -64,6 +64,16 @@ Your messages may include \`<project-memory>\` blocks containing memories automa
These memories may be stale or irrelevant. Use your judgement — if a memory seems outdated, note it in your plan and recommend updating or deleting it via memory-edit or memory-delete.
## Project KV Store
You have access to a project-scoped key-value store with 24-hour TTL for ephemeral state:
- \`memory-kv-set\`: Store planning progress, research findings, or any project state
- \`memory-kv-get\`: Retrieve previously stored state
- \`memory-kv-list\`: See all active entries for the project
- \`memory-kv-delete\`: Remove entries no longer needed
KV entries are scoped to the current project and expire after 24 hours. Use this for state that needs to survive compaction but isn't permanent enough for memory-write.
## Workflow
1. **Research** — Read relevant files, search the codebase, delegate to @Memory subagent for conventions, decisions, and prior plans
+55 -3
View File
@@ -8,7 +8,7 @@ export const codeReviewAgent: AgentDefinition = {
mode: 'subagent',
temperature: 0.0,
tools: {
exclude: ['memory-plan-execute', 'memory-write', 'memory-edit', 'memory-delete'],
exclude: ['memory-plan-execute', 'memory-delete', 'memory-write', 'memory-edit'],
},
systemPrompt: `You are a code reviewer with access to project memory. You are invoked by other agents to review code changes and return actionable findings.
@@ -111,13 +111,65 @@ If no issues are found, say so clearly and briefly.
You are read-only on source code. Do not edit files, run destructive commands, or make any changes. Only read, search, analyze, and report findings.
If a memory seems outdated, update it with memory-edit or flag it for the calling agent.
## Persisting Findings
After completing a review, store each **bug** and **warning** finding in the project KV store so it can be retrieved in subsequent reviews. Do NOT store suggestions — only actionable issues.
Use \`memory-kv-set\` with a structured key and JSON value:
**Key pattern**: \`review-finding:<file_path>:<line_number>\`
**Value**: JSON object with the finding details
Example:
\`\`\`json
{
"severity": "bug",
"file": "src/services/auth.ts",
"line": 45,
"description": "Missing null check on user.session before accessing .token — throws TypeError when session expires mid-request.",
"scenario": "User's session expires between the auth check and token access on line 45.",
"status": "open",
"date": "2026-03-07"
}
\`\`\`
The KV store upserts by key, so storing a finding for the same file:line automatically updates the previous entry. No dedup checks needed.
When the calling agent reports that a finding has been fixed, update the finding by calling \`memory-kv-set\` with the same key and the status changed to "resolved" with a resolution date added.
Findings expire after 24 hours automatically. If an issue persists, the next review will re-discover it.
## Retrieving Past Findings
At the start of every review, before analyzing the diff:
1. Call \`memory-kv-list\` to get all active KV entries for the project
2. Filter entries with keys starting with \`review-finding:\` that match files in the current diff
3. If open findings exist for files being changed, include them under a "### Previously Identified Issues" heading before new findings
4. Check if any previously open findings have been addressed by the current changes — if so, update their status to "resolved" via \`memory-kv-set\` with the same key
## Memory Tools
You have access to these tools:
- **memory-read**: Search permanent memories for conventions and decisions (query, scope, limit)
- **memory-kv-set**: Store review findings with 24h TTL (key, value as JSON string)
- **memory-kv-get**: Retrieve a specific finding by key
- **memory-kv-list**: List all active KV entries for the project
- **memory-kv-delete**: Remove a finding that is no longer relevant
- **memory-health**: Check memory system status
## Project KV Store
Review findings are stored in the project KV store with 24-hour TTL. Use \`memory-kv-set\` to persist findings, \`memory-kv-get\` to retrieve specific findings, \`memory-kv-list\` to see all active entries, and \`memory-kv-delete\` to remove stale findings. Entries expire automatically after 24 hours.
## Injected Memory
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **[convention]**: Rules to check code against
- **[decision]**: Architectural constraints that may apply
- **[context]**: Reference information
- **[context]**: Reference information and persisted review findings
These memories may be stale or irrelevant. If a memory seems outdated, note it in your review observations. You do not have write access to memory — flag stale memories for the calling agent to handle.`,
These memories may be stale or irrelevant. If a memory seems outdated, note it in your review observations.`,
}
+4
View File
@@ -72,5 +72,9 @@ Your messages may include \`<project-memory>\` blocks containing memories automa
These memories may be stale or irrelevant to the current task. Use your judgement. If a memory seems outdated or incorrect for the current task, you can ignore it.
If you notice patterns of outdated or incorrect memories, consider asking the user to curate them. Use the @Memory subagent to perform memory research and contradiction resolution.
## Project KV Store
Use \`memory-kv-get\` to check for active project state (e.g., planning progress, code review patterns). Use \`memory-kv-set\` to store ephemeral findings. Entries expire after 24 hours. Use \`memory-kv-list\` to see all active entries.
`,
}
+1
View File
@@ -53,6 +53,7 @@ Use for:
- Domain-specific terminology (e.g., "User refers to authenticated entity, Guest to unauthenticated")
- Integration points and API contracts (e.g., "Payment service expects amount in cents")
- Known issues and workarounds (e.g., "Hot reload breaks with circular imports—restart required")
- Code review findings (prefixed with \`[review-finding]\`, stored by the Code Review agent)
- Technical debt notes (e.g., "Auth needs migration to JWT")
- Domain knowledge (e.g., "Prices stored as integers to avoid floating point issues")
+74 -1
View File
@@ -11,6 +11,7 @@ import { createVecService } from './storage/vec'
import { createEmbeddingProvider, checkServerHealth, isServerRunning, killEmbeddingServer } from './embedding'
import { createMemoryService } from './services/memory'
import { createEmbeddingSyncService } from './services/embedding-sync'
import { createKvService } from './services/kv'
import { loadPluginConfig } from './setup'
import { resolveLogPath } from './storage'
import { createLogger } from './utils/logger'
@@ -293,6 +294,9 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
memoryService.setDedupThreshold(config.dedupThreshold)
}
const kvService = createKvService(db, logger)
kvService.startCleanup()
const mismatchState: DimensionMismatchState = {
detected: false,
expected: null,
@@ -372,6 +376,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
cleaned = true
logger.log('Cleaning up plugin resources...')
memoryInjection.destroy()
kvService.destroy()
await memoryService.destroy()
closeDatabase(db)
logger.log('Plugin cleanup complete')
@@ -547,6 +552,74 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\nModel: ${modelInfo}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
},
}),
'memory-kv-set': tool({
description: 'Store a key-value pair for the current project. Values expire after 24 hours by default. Use for ephemeral project state like planning progress, code review patterns, or session context.',
args: {
key: z.string().describe('The key to store the value under'),
value: z.string().describe('The value to store (JSON string)'),
ttlMs: z.number().optional().describe('Time-to-live in milliseconds (default: 24 hours)'),
},
execute: async (args) => {
logger.log(`memory-kv-set: key="${args.key}"`)
let parsed: unknown
try {
parsed = JSON.parse(args.value)
} catch {
parsed = args.value
}
kvService.set(projectId, args.key, parsed, args.ttlMs)
const expiresAt = new Date(Date.now() + (args.ttlMs ?? 24 * 60 * 60 * 1000))
logger.log(`memory-kv-set: stored key="${args.key}", expires=${expiresAt.toISOString()}`)
return `Stored key "${args.key}" (expires ${expiresAt.toISOString()})`
},
}),
'memory-kv-get': tool({
description: 'Retrieve a value by key for the current project.',
args: {
key: z.string().describe('The key to retrieve'),
},
execute: async (args) => {
logger.log(`memory-kv-get: key="${args.key}"`)
const value = kvService.get(projectId, args.key)
if (value === null) {
logger.log(`memory-kv-get: key="${args.key}" not found`)
return `No value found for key "${args.key}"`
}
logger.log(`memory-kv-get: key="${args.key}" found`)
return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
},
}),
'memory-kv-delete': tool({
description: 'Delete a key-value pair for the current project.',
args: {
key: z.string().describe('The key to delete'),
},
execute: async (args) => {
logger.log(`memory-kv-delete: key="${args.key}"`)
kvService.delete(projectId, args.key)
logger.log(`memory-kv-delete: deleted key="${args.key}"`)
return `Deleted key "${args.key}"`
},
}),
'memory-kv-list': tool({
description: 'List all active key-value pairs for the current project.',
args: {},
execute: async () => {
logger.log('memory-kv-list')
const entries = kvService.list(projectId)
if (entries.length === 0) {
logger.log('memory-kv-list: no entries')
return 'No active KV entries for this project.'
}
const formatted = entries.map((e) => {
const expiresIn = Math.round((e.expiresAt - Date.now()) / 60000)
const dataPreview = typeof e.data === 'string' ? e.data.substring(0, 100) : JSON.stringify(e.data).substring(0, 100)
return `- **${e.key}** (expires in ${expiresIn}m)\n ${dataPreview}${dataPreview.length >= 100 ? '...' : ''}`
})
logger.log(`memory-kv-list: ${entries.length} entries`)
return `${entries.length} active KV entries:\n\n${formatted.join('\n')}`
},
}),
},
config: createConfigHandler(agents),
'chat.message': sessionHooks.onMessage,
@@ -623,7 +696,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
text: `<system-reminder>
Plan mode is active. You MUST NOT make any file edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-plan-execute).
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-plan-execute, memory-kv-set, memory-kv-get, memory-kv-delete, memory-kv-list).
</system-reminder>`,
synthetic: true,
})
+86
View File
@@ -0,0 +1,86 @@
import type { Database } from 'bun:sqlite'
import { createKvQuery } from '../storage/kv-queries'
import type { Logger } from '../types'
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
export interface KvEntry {
key: string
data: unknown
updatedAt: number
expiresAt: number
}
export interface KvService {
get<T = unknown>(projectId: string, key: string): T | null
set<T = unknown>(projectId: string, key: string, data: T, ttlMs?: number): void
delete(projectId: string, key: string): void
list(projectId: string): KvEntry[]
startCleanup(intervalMs?: number): void
destroy(): void
}
export function createKvService(db: Database, logger?: Logger): KvService {
const queries = createKvQuery(db)
let cleanupInterval: ReturnType<typeof setInterval> | null = null
return {
get<T = unknown>(projectId: string, key: string): T | null {
const row = queries.get(projectId, key)
if (!row) return null
try {
return JSON.parse(row.data) as T
} catch {
return null
}
},
set<T = unknown>(projectId: string, key: string, data: T, ttlMs?: number): void {
const expiresAt = Date.now() + (ttlMs ?? DEFAULT_TTL_MS)
const jsonData = JSON.stringify(data)
queries.set(projectId, key, jsonData, expiresAt)
},
delete(projectId: string, key: string): void {
queries.delete(projectId, key)
},
list(projectId: string): KvEntry[] {
const rows = queries.list(projectId)
return rows.map((row) => {
let data: unknown = null
try {
data = JSON.parse(row.data)
} catch {
}
return {
key: row.key,
data,
updatedAt: row.updatedAt,
expiresAt: row.expiresAt,
}
})
},
startCleanup(intervalMs: number = 30 * 60 * 1000): void {
if (cleanupInterval) return
cleanupInterval = setInterval(() => {
try {
const deleted = queries.deleteExpired()
if (deleted > 0) {
logger?.log(`KV cleanup: removed ${deleted} expired entries`)
}
} catch (error) {
logger?.error('KV cleanup failed', error)
}
}, intervalMs)
},
destroy(): void {
if (cleanupInterval) {
clearInterval(cleanupInterval)
cleanupInterval = null
}
},
}
}
+14
View File
@@ -107,6 +107,20 @@ export function initializeDatabase(dataDir: string): Database {
)
`)
db.run(`
CREATE TABLE IF NOT EXISTS project_kv (
project_id TEXT NOT NULL,
key TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (project_id, key)
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_project_kv_expires_at ON project_kv(expires_at)`)
return db
}
+2
View File
@@ -3,6 +3,8 @@ export { createVecService } from './vec'
export type { VecService, VecSearchResult, TableDimensionsResult } from './vec-types'
export { createMemoryQuery } from './memory-queries'
export { createMetadataQuery } from './metadata-queries'
export { createKvQuery } from './kv-queries'
export type { KvRow } from './kv-queries'
export type {
Memory,
+86
View File
@@ -0,0 +1,86 @@
import type { Database } from 'bun:sqlite'
export interface KvRow {
projectId: string
key: string
data: string
expiresAt: number
createdAt: number
updatedAt: number
}
interface KvRowRaw {
project_id: string
key: string
data: string
expires_at: number
created_at: number
updated_at: number
}
function mapRow(row: KvRowRaw): KvRow {
return {
projectId: row.project_id,
key: row.key,
data: row.data,
expiresAt: row.expires_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
}
export function createKvQuery(db: Database) {
const getStmt = db.prepare(
`SELECT project_id, key, data, expires_at, created_at, updated_at
FROM project_kv
WHERE project_id = ? AND key = ? AND expires_at > ?`
)
const setStmt = db.prepare(
`INSERT INTO project_kv (project_id, key, data, expires_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(project_id, key) DO UPDATE SET
data = excluded.data,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at`
)
const deleteStmt = db.prepare(`DELETE FROM project_kv WHERE project_id = ? AND key = ?`)
const listStmt = db.prepare(
`SELECT project_id, key, data, expires_at, created_at, updated_at
FROM project_kv
WHERE project_id = ? AND expires_at > ?
ORDER BY updated_at DESC`
)
const deleteExpiredStmt = db.prepare(
`DELETE FROM project_kv WHERE expires_at < ?`
)
return {
get(projectId: string, key: string): KvRow | undefined {
const row = getStmt.get(projectId, key, Date.now()) as KvRowRaw | null
return row ? mapRow(row) : undefined
},
set(projectId: string, key: string, data: string, expiresAt: number): void {
const now = Date.now()
setStmt.run(projectId, key, data, expiresAt, now, now)
},
delete(projectId: string, key: string): void {
deleteStmt.run(projectId, key)
},
list(projectId: string): KvRow[] {
const rows = listStmt.all(projectId, Date.now()) as KvRowRaw[]
return rows.map(mapRow)
},
deleteExpired(): number {
const result = deleteExpiredStmt.run(Date.now())
return result.changes
},
}
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.15'
export const VERSION = '0.0.16'
+201
View File
@@ -0,0 +1,201 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createKvQuery } from '../src/storage/kv-queries'
import { createKvService } from '../src/services/kv'
const TEST_DIR = '/tmp/opencode-manager-kv-test-' + Date.now()
function createTestDb(): Database {
const db = new Database(`${TEST_DIR}-${Math.random().toString(36).slice(2)}.db`)
db.run(`
CREATE TABLE IF NOT EXISTS project_kv (
project_id TEXT NOT NULL,
key TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (project_id, key)
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_project_kv_expires_at ON project_kv(expires_at)`)
return db
}
describe('createKvQuery', () => {
let db: Database
beforeEach(() => {
db = createTestDb()
})
afterEach(() => {
db.close()
})
test('set and get round-trip', () => {
const queries = createKvQuery(db)
const expiresAt = Date.now() + 86400000
queries.set('project-1', 'test-key', '{"foo":"bar"}', expiresAt)
const row = queries.get('project-1', 'test-key')
expect(row).toBeDefined()
expect(row!.data).toBe('{"foo":"bar"}')
expect(row!.projectId).toBe('project-1')
expect(row!.key).toBe('test-key')
})
test('get returns undefined for non-existent key', () => {
const queries = createKvQuery(db)
const row = queries.get('project-1', 'non-existent')
expect(row).toBeUndefined()
})
test('get returns undefined for expired entry', async () => {
const queries = createKvQuery(db)
queries.set('project-1', 'expired-key', '"value"', Date.now() + 50)
await new Promise((resolve) => setTimeout(resolve, 60))
const row = queries.get('project-1', 'expired-key')
expect(row).toBeUndefined()
})
test('set upserts existing key', () => {
const queries = createKvQuery(db)
const expiresAt = Date.now() + 86400000
queries.set('project-1', 'key1', '"value1"', expiresAt)
queries.set('project-1', 'key1', '"value2"', expiresAt)
const row = queries.get('project-1', 'key1')
expect(row!.data).toBe('"value2"')
})
test('delete removes entry', () => {
const queries = createKvQuery(db)
queries.set('project-1', 'to-delete', '"value"', Date.now() + 86400000)
queries.delete('project-1', 'to-delete')
const row = queries.get('project-1', 'to-delete')
expect(row).toBeUndefined()
})
test('list returns all non-expired entries for project', () => {
const queries = createKvQuery(db)
const expiresAt = Date.now() + 86400000
queries.set('project-1', 'key1', '"value1"', expiresAt)
queries.set('project-1', 'key2', '"value2"', expiresAt)
queries.set('project-2', 'key3', '"value3"', expiresAt)
const rows = queries.list('project-1')
expect(rows.length).toBe(2)
})
test('list excludes expired entries', async () => {
const queries = createKvQuery(db)
queries.set('project-1', 'active', '"value"', Date.now() + 86400000)
queries.set('project-1', 'expired', '"value"', Date.now() + 50)
await new Promise((resolve) => setTimeout(resolve, 60))
const rows = queries.list('project-1')
expect(rows.length).toBe(1)
expect(rows[0]!.key).toBe('active')
})
test('deleteExpired cleans up expired entries', async () => {
const queries = createKvQuery(db)
queries.set('project-1', 'expired', '"value"', Date.now() + 50)
queries.set('project-1', 'active', '"value"', Date.now() + 86400000)
await new Promise((resolve) => setTimeout(resolve, 60))
const deleted = queries.deleteExpired()
expect(deleted).toBe(1)
expect(queries.get('project-1', 'active')).toBeDefined()
})
test('same key in different projects stores separate values', () => {
const queries = createKvQuery(db)
const expiresAt = Date.now() + 86400000
queries.set('project-1', 'shared-key', '"value1"', expiresAt)
queries.set('project-2', 'shared-key', '"value2"', expiresAt)
expect(queries.get('project-1', 'shared-key')!.data).toBe('"value1"')
expect(queries.get('project-2', 'shared-key')!.data).toBe('"value2"')
})
})
describe('KvService', () => {
let db: Database
let service: ReturnType<typeof createKvService>
beforeEach(() => {
db = createTestDb()
service = createKvService(db)
})
afterEach(() => {
service.destroy()
db.close()
})
test('set and get with JSON data', () => {
service.set('project-1', 'test', { foo: 'bar', count: 42 })
const result = service.get<{ foo: string; count: number }>('project-1', 'test')
expect(result).toEqual({ foo: 'bar', count: 42 })
})
test('get returns null for non-existent key', () => {
const result = service.get('project-1', 'non-existent')
expect(result).toBeNull()
})
test('TTL expiration', async () => {
service.set('project-1', 'ttl-key', 'value', 50)
expect(service.get('project-1', 'ttl-key')).toBe('value')
await new Promise((resolve) => setTimeout(resolve, 60))
expect(service.get('project-1', 'ttl-key')).toBeNull()
})
test('delete removes entry', () => {
service.set('project-1', 'to-delete', 'value')
service.delete('project-1', 'to-delete')
expect(service.get('project-1', 'to-delete')).toBeNull()
})
test('list returns parsed entries', () => {
service.set('project-1', 'key1', { a: 1 })
service.set('project-1', 'key2', { b: 2 })
const entries = service.list('project-1')
expect(entries.length).toBe(2)
expect(entries[0]!.key).toBeDefined()
expect(entries[0]!.data).toBeDefined()
expect(entries[0]!.updatedAt).toBeDefined()
expect(entries[0]!.expiresAt).toBeDefined()
})
test('list returns empty array for project with no entries', () => {
const entries = service.list('project-1')
expect(entries.length).toBe(0)
})
test('different projectIds store separate state', () => {
service.set('project-1', 'key', 'value1')
service.set('project-2', 'key', 'value2')
expect(service.get('project-1', 'key')).toBe('value1')
expect(service.get('project-2', 'key')).toBe('value2')
})
test('complex JSON objects round-trip', () => {
const complex = {
patterns: ['pattern1', 'pattern2'],
config: { nested: { deep: true } },
count: 42,
}
service.set('project-1', 'complex', complex)
const result = service.get('project-1', 'complex')
expect(result).toEqual(complex)
})
test('list handles malformed JSON data gracefully', () => {
const queries = createKvQuery(db)
queries.set('project-1', 'valid', '{"a":1}', Date.now() + 86400000)
queries.set('project-1', 'corrupt', '{invalid json', Date.now() + 86400000)
const entries = service.list('project-1')
expect(entries.length).toBe(2)
const corrupt = entries.find((e) => e.key === 'corrupt')
expect(corrupt!.data).toBeNull()
const valid = entries.find((e) => e.key === 'valid')
expect(valid!.data).toEqual({ a: 1 })
})
})