dsh-brain/lib/local-memory/departments/manager.js

257 lines
13 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { LocalMemoryManager, projectIdFor } from "../manager.js";
import { containsSecret, JsonMemoryStore } from "../storage.js";
import { DepartmentRegistry } from "./registry.js";
function text(value, max, required = false) {
const result = typeof value === 'string' ? value.trim().slice(0, max) : '';
if (required && result === '')
throw new Error('department_required_field');
return result;
}
function list(value) {
if (!Array.isArray(value))
return [];
return [...new Set(value.filter((item) => typeof item === 'string').map((item) => item.trim().slice(0, 200)).filter((item) => item !== ''))].slice(0, 50);
}
function hostName(value) {
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) {
return Math.max(1, Math.min(50, Math.trunc(value ?? 5)));
}
/** Persistent departments: private memory, reusable session references and bounded recall. */
export class DepartmentManager {
memory;
constructor(options) { this.memory = options.memory; }
root(scope) { return scope === 'global' ? this.memory.globalRoot : this.memory.projectRoot; }
registry(scope) { return new DepartmentRegistry(join(this.root(scope), 'departments', 'registry.json')); }
store(department) {
return new JsonMemoryStore(join(this.root(department.scope), 'departments', department.id, 'memory-space'), 'department', department.spaceId);
}
async activeStore(department) {
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;
}
async find(id) {
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);
}
async required(id) {
const department = await this.find(id);
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) {
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 = {
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) { return this.find(id); }
async list(scope) {
const scopes = 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, patch, expectedRevision) {
const current = await this.required(id);
if (expectedRevision !== undefined && current.revision !== expectedRevision)
throw new Error('revision_conflict');
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, host = 'dsh') {
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 = { 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, host, hostSessionId) {
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, input, expectedRevision) {
const current = await this.required(id);
if (expectedRevision !== undefined && current.revision !== expectedRevision)
throw new Error('revision_conflict');
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, input) {
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, query, k = 5, workspace) {
const department = await this.required(id);
const limit = limitOf(k);
const privateHits = await this.store(department).search(query, limit);
const shared = [];
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 = [
...privateHits.map((hit) => ({ ...hit, origin: 'department' })),
...shared.map((hit) => ({ ...hit, origin: hit.record.scope === 'global' ? 'global' : 'project' })),
];
const seen = new Set();
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, expectedRevision) {
const current = await this.required(id);
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;
});
}
}