feat(mnemon): expose read-only Mnemon routes and order memory list by creation
Routes under /dsh-brain/mnemon/* call the host's registered mnemonRemote service (the same /dsh-mnemon-read handler) instead of going through HTTP with a browser cookie. Read-only: list / status / search / runtime / documents. Answers 503 when Mnemon is absent, 502 on source errors. Also lets /local-memory/memories take order=created|updated (default created, newest first) and return createdAt, sorting the full set before paging.
This commit is contained in:
parent
f409db279f
commit
b7f763460b
|
|
@ -9,6 +9,7 @@
|
||||||
*/
|
*/
|
||||||
import type { CloudMemoryContext } from '../context-types.ts'
|
import type { CloudMemoryContext } from '../context-types.ts'
|
||||||
import { brainKernel, VERSION } from '../kernel.ts'
|
import { brainKernel, VERSION } from '../kernel.ts'
|
||||||
|
import { mnemonReadFromContext } from '../mnemon/read-service.ts'
|
||||||
import { createCoreRoutes, legacyAliases } from '../routes.ts'
|
import { createCoreRoutes, legacyAliases } from '../routes.ts'
|
||||||
import { createSettingsUiRoutes } from '../settings-ui/routes.ts'
|
import { createSettingsUiRoutes } from '../settings-ui/routes.ts'
|
||||||
|
|
||||||
|
|
@ -50,7 +51,10 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
||||||
}
|
}
|
||||||
const routes = [
|
const routes = [
|
||||||
...createSettingsUiRoutes({ version: VERSION, store: kernel.store }),
|
...createSettingsUiRoutes({ version: VERSION, store: kernel.store }),
|
||||||
...createCoreRoutes(kernel.routeDeps()),
|
...createCoreRoutes({
|
||||||
|
...kernel.routeDeps(),
|
||||||
|
mnemon: () => mnemonReadFromContext(ctx),
|
||||||
|
}),
|
||||||
]
|
]
|
||||||
routes.push(...legacyAliases(routes))
|
routes.push(...legacyAliases(routes))
|
||||||
for (const route of routes) {
|
for (const route of routes) {
|
||||||
|
|
|
||||||
|
|
@ -240,7 +240,7 @@ export class LocalMemoryManager {
|
||||||
async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<LocalMemoryRecord[]> {
|
async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<LocalMemoryRecord[]> {
|
||||||
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record)
|
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record)
|
||||||
}
|
}
|
||||||
async list(options: { limit?: number; offset?: number; scope?: LocalMemoryScope } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> {
|
async list(options: { limit?: number; offset?: number; scope?: LocalMemoryScope; order?: 'created' | 'updated' } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> {
|
||||||
if (options.scope !== undefined) return this.scopedStore(options.scope, workspace).list(options)
|
if (options.scope !== undefined) return this.scopedStore(options.scope, workspace).list(options)
|
||||||
const projectStore = await this.ensureProject(workspace)
|
const projectStore = await this.ensureProject(workspace)
|
||||||
const records = [...(await this.globalStore.records()), ...(await projectStore.records())]
|
const records = [...(await this.globalStore.records()), ...(await projectStore.records())]
|
||||||
|
|
@ -250,8 +250,12 @@ export class LocalMemoryManager {
|
||||||
return record.scope === 'project' && record.projectId === projectId
|
return record.scope === 'project' && record.projectId === projectId
|
||||||
})
|
})
|
||||||
const seen = new Set<string>()
|
const seen = new Set<string>()
|
||||||
const ordered = scoped.filter((record) => { if (seen.has(record.id)) return false; seen.add(record.id); return true })
|
// The whole merged set is ordered before pagination (never just the page).
|
||||||
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id))
|
// `updated` keeps the historical order; `created` is the API's new default.
|
||||||
|
const compare = options.order === 'created'
|
||||||
|
? (a: LocalMemoryRecord, b: LocalMemoryRecord): number => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id)
|
||||||
|
: (a: LocalMemoryRecord, b: LocalMemoryRecord): number => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id)
|
||||||
|
const ordered = scoped.filter((record) => { if (seen.has(record.id)) return false; seen.add(record.id); return true }).sort(compare)
|
||||||
const offset = Math.max(0, Math.trunc(options.offset ?? 0))
|
const offset = Math.max(0, Math.trunc(options.offset ?? 0))
|
||||||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)))
|
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)))
|
||||||
return { items: ordered.slice(offset, offset + limit), total: ordered.length }
|
return { items: ordered.slice(offset, offset + limit), total: ordered.length }
|
||||||
|
|
|
||||||
|
|
@ -129,8 +129,17 @@ export class JsonMemoryStore {
|
||||||
const file = await this.readFile(); const q = query.trim().toLowerCase(); const terms = q.split(/\s+/).filter((term) => term !== '')
|
const file = await this.readFile(); const q = query.trim().toLowerCase(); const terms = q.split(/\s+/).filter((term) => term !== '')
|
||||||
return this.activeRecords(file).map((record) => { const haystack = (record.content + '\n' + (record.tags ?? []).join(' ') + '\n' + (record.category ?? '')).toLowerCase(); const score = terms.length === 0 ? 1 : terms.reduce((sum, term) => sum + (haystack.includes(term) ? 1 : 0), 0); return { record, score } }).filter((hit) => terms.length === 0 || hit.score > 0).sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)).slice(0, Math.max(1, Math.min(100, Math.trunc(k))))
|
return this.activeRecords(file).map((record) => { const haystack = (record.content + '\n' + (record.tags ?? []).join(' ') + '\n' + (record.category ?? '')).toLowerCase(); const score = terms.length === 0 ? 1 : terms.reduce((sum, term) => sum + (haystack.includes(term) ? 1 : 0), 0); return { record, score } }).filter((hit) => terms.length === 0 || hit.score > 0).sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)).slice(0, Math.max(1, Math.min(100, Math.trunc(k))))
|
||||||
}
|
}
|
||||||
async list(options: { limit?: number; offset?: number } = {}): Promise<{ items: LocalMemoryRecord[]; total: number }> {
|
async list(options: { limit?: number; offset?: number; order?: 'created' | 'updated' } = {}): Promise<{ items: LocalMemoryRecord[]; total: number }> {
|
||||||
const file = await this.readFile(); const records = this.activeRecords(file).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); const offset = Math.max(0, Math.trunc(options.offset ?? 0)); const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50))); return { items: records.slice(offset, offset + limit), total: records.length }
|
const file = await this.readFile()
|
||||||
|
const records = this.activeRecords(file)
|
||||||
|
// Order the whole set before slicing: paging must stay stable across pages.
|
||||||
|
// `updated` keeps the historical order; `created` is the API's new default.
|
||||||
|
const ordered = options.order === 'created'
|
||||||
|
? records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id))
|
||||||
|
: records.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
|
||||||
|
const offset = Math.max(0, Math.trunc(options.offset ?? 0))
|
||||||
|
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)))
|
||||||
|
return { items: ordered.slice(offset, offset + limit), total: ordered.length }
|
||||||
}
|
}
|
||||||
async update(id: string, patch: { content?: string; tags?: string[]; category?: string }, expectedRevision?: number): Promise<LocalMemoryRecord> {
|
async update(id: string, patch: { content?: string; tags?: string[]; category?: string }, expectedRevision?: number): Promise<LocalMemoryRecord> {
|
||||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined) throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict'); if (patch.content !== undefined) { const content = safeText(patch.content); if (content === '') throw new Error('记忆内容不能为空'); if (containsSecret(content)) throw new Error('secret_not_allowed'); record.content = content } if (patch.tags !== undefined) record.tags = tagsOf(patch.tags); if (patch.category !== undefined) record.category = patch.category; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record })
|
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined) throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict'); if (patch.content !== undefined) { const content = safeText(patch.content); if (content === '') throw new Error('记忆内容不能为空'); if (containsSecret(content)) throw new Error('secret_not_allowed'); record.content = content } if (patch.tags !== undefined) record.tags = tagsOf(patch.tags); if (patch.category !== undefined) record.category = patch.category; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record })
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
/**
|
||||||
|
* Read-only bridge to the live Mnemon Host RPC service.
|
||||||
|
*
|
||||||
|
* Mnemon registers `mnemonRemote` as a Typert service; its `read` method is the
|
||||||
|
* same read handler its own `/dsh-mnemon-read` channel serves. dsh-brain reads
|
||||||
|
* through that service instead of copying Mnemon data: no storage layout is
|
||||||
|
* touched, and no write/forget endpoint is exposed here.
|
||||||
|
*
|
||||||
|
* The service name is resolved lazily from the live Cordis context, so the
|
||||||
|
* plugin loads and runs when Mnemon is absent; the read routes then answer
|
||||||
|
* 503 instead of failing plugin activation.
|
||||||
|
*/
|
||||||
|
import { resolve } from 'node:path'
|
||||||
|
import type { CloudMemoryContext } from '../context-types.ts'
|
||||||
|
|
||||||
|
/** Failure shape carried by a Mnemon RPC result (subset of its wire error). */
|
||||||
|
export interface MnemonRpcError {
|
||||||
|
code?: string
|
||||||
|
message?: string
|
||||||
|
details?: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One Mnemon read result, kept byte-for-byte compatible with its RPC envelope. */
|
||||||
|
export type MnemonRpcResult =
|
||||||
|
| { ok: true; value: unknown }
|
||||||
|
| { ok: false; error: MnemonRpcError }
|
||||||
|
|
||||||
|
/** The narrow read face dsh-brain consumes from Mnemon. */
|
||||||
|
export interface MnemonReadRemote {
|
||||||
|
read(endpoint: string, payload: unknown, signal?: AbortSignal): Promise<MnemonRpcResult>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read face plus the host workspace lookup the read routes need. */
|
||||||
|
export interface MnemonReadBridge extends MnemonReadRemote {
|
||||||
|
/** Resolve a DSH workspace root path to the registry id Mnemon expects. */
|
||||||
|
workspaceIdForPath(path: string): string | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the live Mnemon read service from a host Context.
|
||||||
|
*
|
||||||
|
* `mnemonRemote` is provided by the installed `dsh-mnemon` Host entry. A
|
||||||
|
* missing service (Mnemon not installed, entry disabled, or a host without the
|
||||||
|
* web transport) returns undefined; the caller exposes that as a capability
|
||||||
|
* gap, never as a read of stale data.
|
||||||
|
*/
|
||||||
|
export function mnemonReadFromContext(ctx: CloudMemoryContext): MnemonReadBridge | undefined {
|
||||||
|
const get = (ctx as unknown as { get?: (name: string, strict?: boolean) => unknown }).get
|
||||||
|
if (typeof get !== 'function') return undefined
|
||||||
|
const lookup = (name: string): unknown => {
|
||||||
|
try {
|
||||||
|
return get.call(ctx, name, false)
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const candidate = lookup('mnemonRemote')
|
||||||
|
if (candidate === null || typeof candidate !== 'object') return undefined
|
||||||
|
const read = (candidate as { read?: unknown }).read
|
||||||
|
if (typeof read !== 'function') return undefined
|
||||||
|
const service = candidate as MnemonReadRemote
|
||||||
|
return {
|
||||||
|
read: (endpoint, payload, signal) => signal === undefined
|
||||||
|
? service.read(endpoint, payload)
|
||||||
|
: service.read(endpoint, payload, signal),
|
||||||
|
workspaceIdForPath: (path) => {
|
||||||
|
const registry = lookup('workspaceRegistry') as {
|
||||||
|
list?: () => ReadonlyArray<{ id?: unknown; path?: unknown }>
|
||||||
|
} | undefined
|
||||||
|
if (registry === undefined || typeof registry.list !== 'function') return undefined
|
||||||
|
let spaces: ReadonlyArray<{ id?: unknown; path?: unknown }>
|
||||||
|
try {
|
||||||
|
spaces = registry.list()
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
const target = resolve(path)
|
||||||
|
const found = spaces.find((space) => typeof space.id === 'string'
|
||||||
|
&& typeof space.path === 'string' && resolve(space.path) === target)
|
||||||
|
return typeof found?.id === 'string' ? found.id : undefined
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
101
src/routes.ts
101
src/routes.ts
|
|
@ -34,6 +34,7 @@ import type { SkillGroupManager } from './skill-groups.ts'
|
||||||
import type { MarketService } from './market.ts'
|
import type { MarketService } from './market.ts'
|
||||||
import type { SkillUpdater } from './skill-update.ts'
|
import type { SkillUpdater } from './skill-update.ts'
|
||||||
import type { ClientRegistry } from './clients.ts'
|
import type { ClientRegistry } from './clients.ts'
|
||||||
|
import type { MnemonReadBridge } from './mnemon/read-service.ts'
|
||||||
import { brainStatus, migrateLegacyFiles } from './brain-migration.ts'
|
import { brainStatus, migrateLegacyFiles } from './brain-migration.ts'
|
||||||
import { mcpCapability, type McpCapability } from './mcp.ts'
|
import { mcpCapability, type McpCapability } from './mcp.ts'
|
||||||
import { fail, json, jsonBody, readBody, sameOrigin } from './http.ts'
|
import { fail, json, jsonBody, readBody, sameOrigin } from './http.ts'
|
||||||
|
|
@ -56,6 +57,7 @@ export const ROUTES = {
|
||||||
migrate: '/dsh-brain/migrate',
|
migrate: '/dsh-brain/migrate',
|
||||||
localMemory: '/dsh-brain/local-memory',
|
localMemory: '/dsh-brain/local-memory',
|
||||||
departments: '/dsh-brain/departments',
|
departments: '/dsh-brain/departments',
|
||||||
|
mnemon: '/dsh-brain/mnemon',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/** Everything the routes need from the plugin core. */
|
/** Everything the routes need from the plugin core. */
|
||||||
|
|
@ -84,6 +86,8 @@ export interface RouteDeps {
|
||||||
localMemory?: LocalMemoryManager
|
localMemory?: LocalMemoryManager
|
||||||
/** Department registry (P1.5), when wired in. */
|
/** Department registry (P1.5), when wired in. */
|
||||||
departments?: DepartmentManager
|
departments?: DepartmentManager
|
||||||
|
/** Read-only bridge to the live Mnemon RPC service, when Mnemon is present. */
|
||||||
|
mnemon?: () => MnemonReadBridge | undefined
|
||||||
/** Bundle activation states reported to the total panel. */
|
/** Bundle activation states reported to the total panel. */
|
||||||
bundles?: Record<string, boolean>
|
bundles?: Record<string, boolean>
|
||||||
}
|
}
|
||||||
|
|
@ -253,10 +257,13 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv
|
||||||
json(res, 200, { ok: true, ...(await manager.storageStatus(workspace, scope)) })
|
json(res, 200, { ok: true, ...(await manager.storageStatus(workspace, scope)) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const orderParam = url.searchParams.get('order')
|
||||||
|
if (orderParam !== null && orderParam !== 'created' && orderParam !== 'updated') { fail(res, 400, 'invalid-order'); return }
|
||||||
|
const order = orderParam === 'updated' ? 'updated' : 'created'
|
||||||
const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50))
|
const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50))
|
||||||
const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0)
|
const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0)
|
||||||
const page = await manager.list({ limit, offset, scope }, workspace)
|
const page = await manager.list({ limit, offset, scope, order }, workspace)
|
||||||
json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) })
|
json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, createdAt: record.createdAt, updatedAt: record.updatedAt })) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (suffix === '/spaces') {
|
if (suffix === '/spaces') {
|
||||||
|
|
@ -351,6 +358,91 @@ async function serveMigrate(_deps: RouteDeps, req: IncomingMessage, res: ServerR
|
||||||
fail(res, 404, 'unknown-migrate-route')
|
fail(res, 404, 'unknown-migrate-route')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-only Mnemon bridge: `GET /dsh-brain/mnemon/<endpoint>`.
|
||||||
|
*
|
||||||
|
* The body is Mnemon's own RPC result envelope (`{ok,value}` / `{ok,error}`);
|
||||||
|
* query parameters map 1:1 onto the endpoint's payload. Only reads are
|
||||||
|
* exposed: there is no remember/forget route here, by design.
|
||||||
|
*/
|
||||||
|
async function serveMnemonRead(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
|
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||||
|
const bridge = deps.mnemon?.()
|
||||||
|
if (bridge === undefined) {
|
||||||
|
json(res, 503, { ok: false, error: { code: 'mnemon-unavailable', message: 'Mnemon 读服务未接入:当前宿主没有 mnemonRemote 服务。' } })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const url = new URL(req.url ?? '/', 'http://localhost')
|
||||||
|
const suffix = url.pathname.slice(ROUTES.mnemon.length).replace(/\/+$/, '')
|
||||||
|
const endpoints: Record<string, string> = {
|
||||||
|
'/list': 'list',
|
||||||
|
'/status': 'status',
|
||||||
|
'/search': 'search',
|
||||||
|
'/runtime': 'runtime-memory',
|
||||||
|
'/documents': 'documents',
|
||||||
|
}
|
||||||
|
const endpoint = endpoints[suffix]
|
||||||
|
if (endpoint === undefined) { fail(res, 404, 'unknown-mnemon-route'); return }
|
||||||
|
|
||||||
|
const workspaceIdParam = url.searchParams.get('workspaceId')?.trim()
|
||||||
|
const workspacePath = url.searchParams.get('workspace')?.trim()
|
||||||
|
const sessionId = url.searchParams.get('sessionId')?.trim() || undefined
|
||||||
|
const workspaceId = workspaceIdParam !== undefined && workspaceIdParam !== ''
|
||||||
|
? workspaceIdParam
|
||||||
|
: workspacePath !== undefined && workspacePath !== ''
|
||||||
|
? bridge.workspaceIdForPath(workspacePath)
|
||||||
|
: undefined
|
||||||
|
const scope = {
|
||||||
|
...(workspaceId === undefined ? {} : { workspaceId }),
|
||||||
|
...(sessionId === undefined ? {} : { sessionId }),
|
||||||
|
}
|
||||||
|
const ids = url.searchParams.getAll('memoryBodyIds').flatMap((value) => value.split(',')).map((value) => value.trim()).filter((value) => value !== '')
|
||||||
|
const memoryBodyIds = ids.length === 0 ? undefined : [...new Set(ids)]
|
||||||
|
const limit = (fallback: number): number => {
|
||||||
|
const parsed = Number.parseInt(url.searchParams.get('limit') ?? '', 10)
|
||||||
|
return Number.isFinite(parsed) ? Math.max(1, Math.min(1000, parsed)) : fallback
|
||||||
|
}
|
||||||
|
let payload: Record<string, unknown>
|
||||||
|
if (endpoint === 'list') {
|
||||||
|
const query = url.searchParams.get('query')?.trim()
|
||||||
|
const category = url.searchParams.get('category')?.trim()
|
||||||
|
payload = {
|
||||||
|
...scope,
|
||||||
|
limit: limit(50),
|
||||||
|
...(query === undefined || query === '' ? {} : { query }),
|
||||||
|
...(category === undefined || category === '' ? {} : { category }),
|
||||||
|
...(memoryBodyIds === undefined ? {} : { memoryBodyIds }),
|
||||||
|
}
|
||||||
|
} else if (endpoint === 'search') {
|
||||||
|
const query = (url.searchParams.get('q') ?? url.searchParams.get('query') ?? '').trim()
|
||||||
|
if (query === '') { fail(res, 400, 'query-required'); return }
|
||||||
|
const mode = url.searchParams.get('mode')?.trim()
|
||||||
|
const category = url.searchParams.get('category')?.trim()
|
||||||
|
const source = url.searchParams.get('source')?.trim()
|
||||||
|
const intent = url.searchParams.get('intent')?.trim()
|
||||||
|
payload = {
|
||||||
|
query,
|
||||||
|
...scope,
|
||||||
|
limit: limit(10),
|
||||||
|
...(mode === undefined || mode === '' ? {} : { mode }),
|
||||||
|
...(category === undefined || category === '' ? {} : { category }),
|
||||||
|
...(source === undefined || source === '' ? {} : { source }),
|
||||||
|
...(intent === undefined || intent === '' ? {} : { intent }),
|
||||||
|
...(memoryBodyIds === undefined ? {} : { memoryBodyIds }),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
payload = scope
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await bridge.read(endpoint, payload)
|
||||||
|
if (result.ok) { json(res, 200, { ok: true, value: result.value }); return }
|
||||||
|
const status = result.error.code === 'bad-request' ? 400 : 502
|
||||||
|
json(res, status, { ok: false, error: result.error })
|
||||||
|
} catch (error) {
|
||||||
|
json(res, 502, { ok: false, error: { code: 'mnemon-error', message: error instanceof Error ? error.message : String(error) } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pre-rename aliases (0.8.0): the same route objects under the old
|
* Pre-rename aliases (0.8.0): the same route objects under the old
|
||||||
* `/cloud-memory` prefix. Each sub-plugin entry aliases its own slice this
|
* `/cloud-memory` prefix. Each sub-plugin entry aliases its own slice this
|
||||||
|
|
@ -412,6 +504,11 @@ export function createCoreRoutes(deps: RouteDeps): CloudMemoryWebRoute[] {
|
||||||
path: ROUTES.departments,
|
path: ROUTES.departments,
|
||||||
handler: (req, res) => serveDepartments(deps, req, res),
|
handler: (req, res) => serveDepartments(deps, req, res),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
kind: 'prefix',
|
||||||
|
path: ROUTES.mnemon,
|
||||||
|
handler: (req, res) => serveMnemonRead(deps, req, res),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
kind: 'exact',
|
kind: 'exact',
|
||||||
path: ROUTES.status,
|
path: ROUTES.status,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,93 @@
|
||||||
|
// Read-only Mnemon bridge verification: parameter mapping, envelopes, error
|
||||||
|
// paths and the absence of write routes. Runs against the built lib/ output.
|
||||||
|
import http from 'node:http'
|
||||||
|
import { createCoreRoutes } from './lib/routes.js'
|
||||||
|
|
||||||
|
const checks = []
|
||||||
|
function check(name, ok, detail = '') {
|
||||||
|
checks.push({ name, ok })
|
||||||
|
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === '' ? '' : ` :: ${detail}`}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const calls = []
|
||||||
|
const bridge = {
|
||||||
|
read: async (endpoint, payload) => {
|
||||||
|
calls.push({ endpoint, payload })
|
||||||
|
return { ok: true, value: { endpoint, payload } }
|
||||||
|
},
|
||||||
|
workspaceIdForPath: (path) => path.endsWith('proj') ? 'ws-1' : undefined,
|
||||||
|
}
|
||||||
|
|
||||||
|
function serverFor(mnemon) {
|
||||||
|
const route = createCoreRoutes({ version: 'test', ...(mnemon === undefined ? {} : { mnemon }) })
|
||||||
|
.find((item) => item.path === '/dsh-brain/mnemon')
|
||||||
|
if (route === undefined) throw new Error('mnemon route is not registered')
|
||||||
|
const server = http.createServer((req, res) => route.handler(req, res))
|
||||||
|
return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function call(server, path, method = 'GET') {
|
||||||
|
const response = await fetch(`http://127.0.0.1:${server.address().port}${path}`, { method })
|
||||||
|
return { status: response.status, body: await response.json() }
|
||||||
|
}
|
||||||
|
|
||||||
|
const server = await serverFor(() => bridge)
|
||||||
|
|
||||||
|
const list = await call(server, '/dsh-brain/mnemon/list?limit=5&query=abc&category=rule&memoryBodyIds=a,b&memoryBodyIds=c&workspaceId=ws-1&sessionId=s1')
|
||||||
|
check('list maps query parameters onto Mnemon payload', list.status === 200
|
||||||
|
&& calls.at(-1).endpoint === 'list'
|
||||||
|
&& JSON.stringify(calls.at(-1).payload) === JSON.stringify({ workspaceId: 'ws-1', sessionId: 's1', limit: 5, query: 'abc', category: 'rule', memoryBodyIds: ['a', 'b', 'c'] }))
|
||||||
|
check('list preserves the Mnemon result envelope', list.body.ok === true && list.body.value.endpoint === 'list')
|
||||||
|
|
||||||
|
await call(server, '/dsh-brain/mnemon/runtime')
|
||||||
|
check('runtime maps to runtime-memory', calls.at(-1).endpoint === 'runtime-memory')
|
||||||
|
check('runtime sends only the optional scope', JSON.stringify(calls.at(-1).payload) === '{}')
|
||||||
|
|
||||||
|
await call(server, '/dsh-brain/mnemon/status?workspace=C:/x/proj')
|
||||||
|
check('status resolves a workspace path to a workspace id', calls.at(-1).endpoint === 'status'
|
||||||
|
&& JSON.stringify(calls.at(-1).payload) === JSON.stringify({ workspaceId: 'ws-1' }))
|
||||||
|
|
||||||
|
await call(server, '/dsh-brain/mnemon/search?q=docker&limit=3&mode=keyword&source=user')
|
||||||
|
check('search maps q/limit/mode/source', calls.at(-1).endpoint === 'search'
|
||||||
|
&& JSON.stringify(calls.at(-1).payload) === JSON.stringify({ query: 'docker', limit: 3, mode: 'keyword', source: 'user' }))
|
||||||
|
|
||||||
|
await call(server, '/dsh-brain/mnemon/documents')
|
||||||
|
check('documents is exposed read-only', calls.at(-1).endpoint === 'documents')
|
||||||
|
|
||||||
|
const noQuery = await call(server, '/dsh-brain/mnemon/search')
|
||||||
|
check('search without a query is 400', noQuery.status === 400 && noQuery.body.error === 'query-required')
|
||||||
|
|
||||||
|
const unknown = await call(server, '/dsh-brain/mnemon/forget')
|
||||||
|
check('write-like endpoints are 404 (no write route)', unknown.status === 404 && unknown.body.error === 'unknown-mnemon-route')
|
||||||
|
|
||||||
|
const post = await call(server, '/dsh-brain/mnemon/list', 'POST')
|
||||||
|
check('POST is rejected', post.status === 405)
|
||||||
|
|
||||||
|
const failing = await serverFor(() => ({
|
||||||
|
read: async () => ({ ok: false, error: { code: 'internal', message: 'boom', details: {} } }),
|
||||||
|
workspaceIdForPath: () => undefined,
|
||||||
|
}))
|
||||||
|
const failed = await call(failing, '/dsh-brain/mnemon/list')
|
||||||
|
check('Mnemon failure keeps its error envelope with 502', failed.status === 502
|
||||||
|
&& failed.body.ok === false && failed.body.error.message === 'boom')
|
||||||
|
failing.close()
|
||||||
|
|
||||||
|
const throwing = await serverFor(() => ({
|
||||||
|
read: async () => { throw new Error('transport down') },
|
||||||
|
workspaceIdForPath: () => undefined,
|
||||||
|
}))
|
||||||
|
const thrown = await call(throwing, '/dsh-brain/mnemon/list')
|
||||||
|
check('thrown read becomes a 502 envelope', thrown.status === 502
|
||||||
|
&& thrown.body.error.code === 'mnemon-error' && thrown.body.error.message === 'transport down')
|
||||||
|
throwing.close()
|
||||||
|
|
||||||
|
const absent = await serverFor(undefined)
|
||||||
|
const unavailable = await call(absent, '/dsh-brain/mnemon/list')
|
||||||
|
check('missing Mnemon answers 503 instead of failing activation', unavailable.status === 503
|
||||||
|
&& unavailable.body.error.code === 'mnemon-unavailable')
|
||||||
|
absent.close()
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
const failedChecks = checks.filter((item) => !item.ok)
|
||||||
|
console.log(`\n${checks.length - failedChecks.length}/${checks.length} checks passed`)
|
||||||
|
if (failedChecks.length > 0) process.exit(1)
|
||||||
Loading…
Reference in New Issue