dsh-brain/src/local-memory/departments/manager.ts

245 lines
13 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { LocalMemoryManager, projectIdFor } from '../manager.ts'
import { containsSecret, JsonMemoryStore } from '../storage.ts'
import type { LocalMemoryAddInput, LocalMemoryRecord, LocalMemorySearchHit } from '../types.ts'
import { DepartmentRegistry } from './registry.ts'
import type { Department, DepartmentCreateInput, DepartmentRecallHit, DepartmentScope, DepartmentSessionRef, DepartmentUpdateInput } from './types.ts'
function text(value: unknown, max: number, required = false): string {
const result = typeof value === 'string' ? value.trim().slice(0, max) : ''
if (required && result === '') throw new Error('department_required_field')
return result
}
function list(value: unknown): string[] {
if (!Array.isArray(value)) return []
return [...new Set(value.filter((item): item is string => typeof item === 'string').map((item) => item.trim().slice(0, 200)).filter((item) => item !== ''))].slice(0, 50)
}
function hostName(value: string): string {
const host = text(value, 64, true)
if (!/^[a-z0-9][a-z0-9_-]*$/.test(host)) throw new Error('department_invalid_host')
return host
}
function limitOf(value: number | undefined): number {
return Math.max(1, Math.min(50, Math.trunc(value ?? 5)))
}
export interface DepartmentManagerOptions {
memory: LocalMemoryManager
}
/** Persistent departments: private memory, reusable session references and bounded recall. */
export class DepartmentManager {
readonly memory: LocalMemoryManager
constructor(options: DepartmentManagerOptions) { this.memory = options.memory }
private root(scope: DepartmentScope): string { return scope === 'global' ? this.memory.globalRoot : this.memory.projectRoot }
private registry(scope: DepartmentScope): DepartmentRegistry { return new DepartmentRegistry(join(this.root(scope), 'departments', 'registry.json')) }
private store(department: Department): JsonMemoryStore {
return new JsonMemoryStore(join(this.root(department.scope), 'departments', department.id, 'memory-space'), 'department', department.spaceId)
}
private async activeStore(department: Department): Promise<JsonMemoryStore> {
if (!department.active) throw new Error('department_disabled')
const store = this.store(department)
const meta = await store.init(department.name + ' 私有记忆')
if (!meta.active) throw new Error('department_disabled')
return store
}
private async find(id: string): Promise<Department | undefined> {
const global = (await this.registry('global').read()).departments.find((item) => item.id === id)
if (global !== undefined) return global
return (await this.registry('project').read()).departments.find((item) => item.id === id)
}
private async required(id: string, scope?: DepartmentScope): Promise<Department> {
const department = scope === undefined
? await this.find(id)
: (await this.registry(scope).read()).departments.find((item) => item.id === id && item.scope === scope)
if (department === undefined) throw new Error('department_not_found')
return department
}
/** Create once by scope + case-insensitive name; repeated calls return the existing department. */
async create(input: DepartmentCreateInput): Promise<{ department: Department; created: boolean }> {
const scope = input.scope ?? 'project'
const name = text(input.name, 100, true)
const role = text(input.role ?? '', 12000)
if (containsSecret(role)) throw new Error('secret_not_allowed')
await this.memory.ensureGlobal()
if (scope === 'project') await this.memory.ensureProject()
return this.registry(scope).update(async (file) => {
const existing = file.departments.find((item) => item.name.toLocaleLowerCase() === name.toLocaleLowerCase())
if (existing !== undefined) return { department: existing, created: false }
const id = 'dept_' + randomUUID()
const timestamp = new Date().toISOString()
const department: Department = {
id, name, role, scope,
...(scope === 'project' ? { projectId: projectIdFor(this.memory.projectRoot) } : {}),
spaceId: 'department_' + id.slice(5),
skills: list(input.skills), allowedTools: list(input.allowedTools),
memory: { readGlobal: input.readGlobal ?? true, readProject: input.readProject ?? true },
sessionRefs: {}, active: true, createdAt: timestamp, updatedAt: timestamp, revision: 1,
}
await this.activeStore(department)
file.departments.push(department)
return { department, created: true }
})
}
async get(id: string): Promise<Department | undefined> { return this.find(id) }
async list(scope?: DepartmentScope): Promise<Department[]> {
const scopes: DepartmentScope[] = scope === undefined ? ['project', 'global'] : [scope]
const files = await Promise.all(scopes.map((item) => this.registry(item).read()))
return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id))
}
async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
const current = await this.required(id, scope)
if (patch.role !== undefined && containsSecret(patch.role)) throw new Error('secret_not_allowed')
return this.registry(current.scope).update(async (file) => {
const department = file.departments.find((item) => item.id === id)
if (department === undefined) throw new Error('department_not_found')
if (expectedRevision !== undefined && department.revision !== expectedRevision) throw new Error('revision_conflict')
if (patch.name !== undefined) department.name = text(patch.name, 100, true)
if (patch.role !== undefined) department.role = text(patch.role, 12000)
if (patch.skills !== undefined) department.skills = list(patch.skills)
if (patch.allowedTools !== undefined) department.allowedTools = list(patch.allowedTools)
if (patch.readGlobal !== undefined || patch.readProject !== undefined) {
department.memory = {
readGlobal: patch.readGlobal ?? department.memory.readGlobal,
readProject: patch.readProject ?? department.memory.readProject,
}
}
department.revision += 1
department.updatedAt = new Date().toISOString()
return department
})
}
/** Return the same portable reference on every resume; a host session id can be attached separately. */
async resumeSession(id: string, host = 'dsh'): Promise<DepartmentSessionRef> {
const current = await this.required(id)
await this.activeStore(current)
const normalizedHost = hostName(host)
return this.registry(current.scope).update(async (file) => {
const department = file.departments.find((item) => item.id === id)
if (department === undefined) throw new Error('department_not_found')
if (!department.active) throw new Error('department_disabled')
const timestamp = new Date().toISOString()
const existing = department.sessionRefs[normalizedHost]
if (existing !== undefined) {
existing.lastUsedAt = timestamp
department.updatedAt = timestamp
return existing
}
const reference: DepartmentSessionRef = { id: 'ds_' + randomUUID(), host: normalizedHost, reusable: true, createdAt: timestamp, lastUsedAt: timestamp }
department.sessionRefs[normalizedHost] = reference
department.updatedAt = timestamp
return reference
})
}
/** Attach a real host session without replacing the portable reference. */
async attachSession(id: string, host: string, hostSessionId: string): Promise<DepartmentSessionRef> {
const normalizedHost = hostName(host)
const externalId = text(hostSessionId, 500, true)
const reference = await this.resumeSession(id, normalizedHost)
const current = await this.required(id)
await this.registry(current.scope).update(async (file) => {
const department = file.departments.find((item) => item.id === id)
if (department === undefined) throw new Error('department_not_found')
const target = department.sessionRefs[normalizedHost]
if (target === undefined) throw new Error('department_session_not_found')
target.hostSessionId = externalId
target.lastUsedAt = new Date().toISOString()
department.updatedAt = target.lastUsedAt
})
return { ...reference, hostSessionId: externalId }
}
async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
const current = await this.required(id, scope)
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000)
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000)
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff))) throw new Error('secret_not_allowed')
return this.registry(current.scope).update(async (file) => {
const department = file.departments.find((item) => item.id === id)
if (department === undefined) throw new Error('department_not_found')
if (expectedRevision !== undefined && department.revision !== expectedRevision) throw new Error('revision_conflict')
if (input.currentTask !== undefined) {
if (currentTask === '') delete department.currentTask
else department.currentTask = currentTask
}
if (input.handoff !== undefined) {
if (handoff === '') delete department.handoff
else department.handoff = handoff
}
department.revision += 1
department.updatedAt = new Date().toISOString()
return department
})
}
async remember(id: string, input: Omit<LocalMemoryAddInput, 'scope' | 'projectId' | 'departmentId'>): Promise<{ record: LocalMemoryRecord; duplicate: boolean }> {
const department = await this.required(id)
const store = await this.activeStore(department)
return store.add({
...input,
source: input.source ?? 'department:' + id,
departmentId: id,
...(department.projectId === undefined ? {} : { projectId: department.projectId }),
})
}
/** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */
async recall(id: string, query: string, k = 5, workspace?: string, scope?: DepartmentScope): Promise<DepartmentRecallHit[]> {
const department = await this.required(id, scope)
const limit = limitOf(k)
const privateHits = await this.store(department).search(query, limit)
const shared: LocalMemorySearchHit[] = []
if (scope !== undefined) {
const readShared = scope === 'global' ? department.memory.readGlobal : department.memory.readProject
if (readShared) shared.push(...await this.memory.searchHits(query, limit, workspace, undefined, scope))
} else if (department.memory.readProject && department.memory.readGlobal) {
shared.push(...await this.memory.searchHits(query, limit * 2, workspace))
} else if (department.memory.readGlobal) {
shared.push(...await this.memory.searchHits(query, limit, workspace, 'global'))
} else if (department.memory.readProject) {
shared.push(...await this.memory.searchHits(query, limit, workspace, department.projectId ?? projectIdFor(this.memory.projectRoot)))
}
const rank = { department: 3, project: 2, global: 1 }
const candidates: DepartmentRecallHit[] = [
...privateHits.map((hit) => ({ ...hit, origin: 'department' as const })),
...shared.map((hit) => ({ ...hit, origin: hit.record.scope === 'global' ? 'global' as const : 'project' as const })),
]
const seen = new Set<string>()
return candidates.sort((a, b) => b.score - a.score || rank[b.origin] - rank[a.origin] || b.record.updatedAt.localeCompare(a.record.updatedAt))
.filter((hit) => {
const key = hit.record.content.trim()
if (seen.has(key)) return false
seen.add(key)
return true
}).slice(0, limit)
}
/** Disable without deleting private memories or allowing automatic session recovery. */
async disable(id: string, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
const current = await this.required(id, scope)
// Fail on a stale revision before deactivating the space below: the update
// callback re-checks under the registry lock, but the deactivation has
// already happened by then.
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
const store = this.store(current)
if (await store.spaceMeta() !== undefined) await store.setActive(false)
return this.registry(current.scope).update(async (file) => {
const department = file.departments.find((item) => item.id === id)
if (department === undefined) throw new Error('department_not_found')
if (expectedRevision !== undefined && department.revision !== expectedRevision) throw new Error('revision_conflict')
department.active = false
department.revision += 1
department.updatedAt = new Date().toISOString()
return department
})
}
}