Files
marqdo-app-harness/packages/marqdo/harness/src/knowledge/manager.ts
T
cflmy 25fc24eea4 feat: add Marqdo Harness product services and workbench
Implement the downstream product in `packages/marqdo`:

- `@marqdo/mdh-harness`: application home layout, atomic writes, locks,
  bounded fixed-argv processes, safe tar extraction, Observation 1 and
  ValueWire validation;
- trusted Gitea release discovery, SHA-256/platform/Bundle verification,
  transactional environment install, rollback and cleanup, CLI Tool changes;
- private knowledge collections with strict import policy, the official
  `marqdo-knowledge` compile/query adapter and a disclosed locator fallback;
- Analysis 3 parsing, approved run/call execution, evidence and staleness;
- the six model operations (find/read/check/program/ecosystem/knowledge_search);
- the `/mdh` workbench over the existing web server with a same-origin fence;
- `mdh` launcher, CI/package/upstream scripts and a Woodpecker pipeline.

Tests: 28 node:test cases (27 PASS, one network-gated install test also PASS
with MDH_TEST_INSTALL=1). Product install/workbench evidence is recorded in
docs/mdh/evidence.

Part of marqdo#25 (MDH-03..MDH-08).
2026-11-28 10:41:39 +08:00

700 lines
31 KiB
TypeScript

/**
* Private static knowledge collections.
*
* The Harness owns collection lifecycle, import policy, user authorisation and
* source identity. Compilation and querying are delegated to the installed
* `marqdo-knowledge` CLI Tool through its current public command contract; when
* that tool is absent the Harness only offers an explicitly disclosed read-only
* file locator and never claims a compiled index.
*
* Knowledge is data: nothing imported here can execute, install or grant a
* capability. Executable Marqdo documents are refused as knowledge sources.
*
* @module @marqdo/mdh-harness/knowledge/manager
*/
import { randomBytes } from 'node:crypto'
import { cp, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { basename, dirname, extname, join, relative } from 'node:path'
import {
assertWithin, digestBytes, digestFile, isDirectory, isFile, listRegularFiles, readJson, readText,
writeJsonAtomic,
} from '../core/fsx.ts'
import type { MdhLayout } from '../core/home.ts'
import { runProcess } from '../core/process.ts'
import type { MarqdoCli } from '../execution/cli.ts'
import { firstLines } from '../execution/cli.ts'
/** Default import bounds. */
export const IMPORT_LIMITS = {
maxFiles: 500,
maxFileBytes: 8 * 1024 * 1024,
maxTotalBytes: 128 * 1024 * 1024,
allowedExtensions: ['.md', '.markdown'],
} as const
/** Collections metadata schema. */
export const COLLECTIONS_SCHEMA = 'marqdo.mdh.knowledge-collections'
/** One imported source document. */
export interface KnowledgeSource {
readonly id: string
readonly relPath: string
readonly title: string
readonly digest: string
readonly bytes: number
readonly importedAt: string
/** Original filename as selected by the user (display only). */
readonly origin: string
readonly okf: boolean
readonly executable: 'none' | 'checked'
}
/** One user collection. */
export interface KnowledgeCollection {
readonly id: string
readonly name: string
readonly description: string
readonly createdAt: string
readonly updatedAt: string
readonly revision: number
readonly enabled: boolean
readonly sources: readonly KnowledgeSource[]
}
/** Persisted collections file. */
interface CollectionsFile {
schema: typeof COLLECTIONS_SCHEMA
schema_version: 1
collections: KnowledgeCollection[]
}
/** Index state of one collection. */
interface IndexState {
readonly schema: 'marqdo.mdh.knowledge-index'
readonly schema_version: 1
readonly collection: string
readonly mode: 'compiled' | 'locator'
readonly compiled_at: string | null
readonly source_digest: string | null
readonly snapshot_digest: string | null
readonly okf: 'unchecked' | 'pass' | 'fail'
readonly tool: { name: string; version: string | null; path: string } | null
readonly note: string
}
/** One search hit. */
export interface KnowledgeHit {
readonly id: string
readonly collection: string
readonly collection_name: string
readonly rel_path: string
readonly title: string
readonly snippet: string
readonly digest: string
readonly span: { start: number; end: number } | null
readonly anchor: string | null
readonly score: number | null
readonly channels: readonly string[]
readonly callable: unknown
readonly stale: boolean
readonly mode: 'compiled' | 'locator'
}
/** Search response. */
export interface KnowledgeSearchResult {
readonly query: string
readonly mode: 'compiled' | 'locator'
readonly index_current: boolean
readonly hits: readonly KnowledgeHit[]
readonly collections: readonly string[]
readonly counts: { readonly sources: number; readonly indexed: number }
readonly note: string
}
/** Knowledge operation failure. */
export class KnowledgeError extends Error {
name = 'KnowledgeError'
}
/** Validate a collection name. */
function collectionName(name: string): string {
const trimmed = name.trim()
if (trimmed.length === 0 || trimmed.length > 120) throw new KnowledgeError('collection name must be 1..120 characters')
return trimmed
}
/** Normalize a source-relative path. */
function normalizeSourcePath(value: string): string {
const normalized = value.replaceAll('\\', '/').replace(/^\.\/+/, '')
if (normalized === '' || normalized.startsWith('/') || normalized.includes('\0')) {
throw new KnowledgeError(`invalid source path: ${value}`)
}
const segments = normalized.split('/')
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
throw new KnowledgeError(`unsafe source path: ${value}`)
}
if (normalized.normalize('NFC') !== normalized) throw new KnowledgeError(`source path must be NFC: ${value}`)
return normalized
}
/** The first Markdown heading, used as a display title without parsing the document format. */
function titleOf(text: string): string {
for (const line of text.split(/\r?\n/)) {
const match = /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/.exec(line)
if (match) return match[1]
}
return ''
}
/** Whether the document declares an OKF concept through front matter. */
function looksOkf(text: string): boolean {
if (!text.startsWith('---\n') && !text.startsWith('---\r\n')) return false
const end = text.indexOf('\n---', 3)
if (end === -1) return false
const front = text.slice(3, end)
return /^type:\s*\S+/m.test(front)
}
/** Conservative check for an execution declaration in plain Markdown. */
function containsExecHeading(text: string): boolean {
return /^\s{0,3}#{1,6}\s+@exec\b/m.test(text)
}
/** Knowledge collection manager. */
export class KnowledgeManager {
readonly #layout: MdhLayout
readonly #cli: () => MarqdoCli | undefined
readonly #toolHome: () => string | undefined
readonly #collectionsFile: string
constructor(options: {
layout: MdhLayout
cli: () => Promise<MarqdoCli | undefined>
toolHome: () => Promise<string | undefined>
}) {
this.#layout = options.layout
this.#cli = options.cli
this.#toolHome = options.toolHome
this.#collectionsFile = join(options.layout.knowledge, 'collections.json')
}
/** Read the collections file. */
async #readFile(): Promise<CollectionsFile> {
const text = await readText(this.#collectionsFile)
if (text === undefined) {
return { schema: COLLECTIONS_SCHEMA, schema_version: 1, collections: [] }
}
const parsed = JSON.parse(text) as CollectionsFile
if (parsed.schema !== COLLECTIONS_SCHEMA || parsed.schema_version !== 1 || !Array.isArray(parsed.collections)) {
throw new KnowledgeError('unsupported knowledge collections file')
}
return parsed
}
/** Persist the collections file. */
async #writeFile(file: CollectionsFile): Promise<void> {
await writeJsonAtomic(this.#collectionsFile, file)
}
/** List collections. */
async collections(): Promise<readonly KnowledgeCollection[]> {
return (await this.#readFile()).collections
}
/** Read one collection by id. */
async collection(id: string): Promise<KnowledgeCollection | undefined> {
if (!/^[a-z0-9][a-z0-9-]{3,63}$/.test(id)) throw new KnowledgeError(`invalid collection id: ${id}`)
return (await this.#readFile()).collections.find(collection => collection.id === id)
}
/** Create a collection with a stable local id. */
async create(input: { name: string; description?: string }): Promise<KnowledgeCollection> {
const name = collectionName(input.name)
const file = await this.#readFile()
if (file.collections.some(collection => collection.name === name)) {
throw new KnowledgeError(`collection already exists: ${name}`)
}
const now = new Date().toISOString()
const collection: KnowledgeCollection = {
id: `kc-${randomBytes(6).toString('hex')}`,
name,
description: (input.description ?? '').slice(0, 2000),
createdAt: now,
updatedAt: now,
revision: 1,
enabled: true,
sources: [],
}
file.collections.push(collection)
await this.#writeFile(file)
await mkdir(this.sourceRoot(collection.id), { recursive: true, mode: 0o700 })
return collection
}
/** Enable or disable a collection without deleting its data. */
async setEnabled(id: string, enabled: boolean): Promise<KnowledgeCollection> {
const file = await this.#readFile()
const index = file.collections.findIndex(collection => collection.id === id)
if (index === -1) throw new KnowledgeError(`unknown collection: ${id}`)
const updated: KnowledgeCollection = { ...file.collections[index], enabled, updatedAt: new Date().toISOString() }
file.collections[index] = updated
await this.#writeFile(file)
return updated
}
/** Delete a collection, its source copies and its index state. */
async delete(id: string): Promise<void> {
const file = await this.#readFile()
const index = file.collections.findIndex(collection => collection.id === id)
if (index === -1) throw new KnowledgeError(`unknown collection: ${id}`)
file.collections.splice(index, 1)
await this.#writeFile(file)
await rm(this.sourceRoot(id), { recursive: true, force: true })
await rm(join(this.#layout.knowledgeIndex, id), { recursive: true, force: true })
}
/** Absolute directory holding one collection's imported originals. */
sourceRoot(id: string): string {
if (!/^[a-z0-9][a-z0-9-]{3,63}$/.test(id)) throw new KnowledgeError(`invalid collection id: ${id}`)
return join(this.#layout.knowledgeSources, id)
}
/** Import files or directories. Nothing is written until all candidates pass. */
async import(input: {
collection: string
paths?: readonly string[]
contents?: readonly { filename: string; content: string }[]
}): Promise<{ imported: readonly KnowledgeSource[]; rejected: readonly { path: string; reason: string }[] }> {
const collection = await this.collection(input.collection)
if (!collection) throw new KnowledgeError(`unknown collection: ${input.collection}`)
const root = this.sourceRoot(collection.id)
await mkdir(root, { recursive: true, mode: 0o700 })
const candidates: { relPath: string; origin: string; bytes: Buffer }[] = []
const rejected: { path: string; reason: string }[] = []
let total = 0
for (const selected of input.paths ?? []) {
const info = await lstat(selected).catch(() => undefined)
if (!info) { rejected.push({ path: selected, reason: 'not found' }); continue }
if (info.isSymbolicLink()) { rejected.push({ path: selected, reason: 'symbolic link is not allowed' }); continue }
const files = info.isDirectory()
? await listRegularFiles(selected, { maxFiles: IMPORT_LIMITS.maxFiles }).catch((error: Error) => {
rejected.push({ path: selected, reason: error.message })
return []
})
: [{ relative: basename(selected), size: info.size }]
for (const file of files) {
const absolute = info.isDirectory() ? join(selected, file.relative) : selected
const relPath = info.isDirectory() ? normalizeSourcePath(file.relative) : normalizeSourcePath(basename(selected))
if (!IMPORT_LIMITS.allowedExtensions.includes(extname(relPath).toLowerCase() as '.md' | '.markdown')) {
rejected.push({ path: absolute, reason: `unsupported knowledge file type: ${extname(relPath) || '(none)'}` })
continue
}
if (file.size > IMPORT_LIMITS.maxFileBytes) { rejected.push({ path: absolute, reason: 'file exceeds the import size limit' }); continue }
const bytes = await readFile(absolute)
total += bytes.byteLength
if (total > IMPORT_LIMITS.maxTotalBytes) throw new KnowledgeError('import exceeds the total size limit')
candidates.push({ relPath, origin: basename(absolute), bytes })
}
}
for (const upload of input.contents ?? []) {
const relPath = normalizeSourcePath(basename(upload.filename))
if (!IMPORT_LIMITS.allowedExtensions.includes(extname(relPath).toLowerCase() as '.md' | '.markdown')) {
rejected.push({ path: upload.filename, reason: 'unsupported knowledge file type' })
continue
}
const bytes = Buffer.from(upload.content, 'utf8')
if (bytes.byteLength > IMPORT_LIMITS.maxFileBytes) { rejected.push({ path: upload.filename, reason: 'file exceeds the import size limit' }); continue }
total += bytes.byteLength
if (total > IMPORT_LIMITS.maxTotalBytes) throw new KnowledgeError('import exceeds the total size limit')
candidates.push({ relPath, origin: basename(upload.filename), bytes })
}
const imported: KnowledgeSource[] = []
const seen = new Set<string>()
for (const candidate of candidates) {
const key = candidate.relPath.toLowerCase()
if (seen.has(key)) { rejected.push({ path: candidate.relPath, reason: 'duplicate path in this import' }); continue }
seen.add(key)
const text = candidate.bytes.toString('utf8')
if (candidate.relPath.toLowerCase().endsWith('.mq.md')) {
rejected.push({ path: candidate.relPath, reason: 'executable .mq.md documents are not static knowledge' })
continue
}
if (containsExecHeading(text)) {
rejected.push({ path: candidate.relPath, reason: 'document declares an @exec region; import a reviewed static extract instead' })
continue
}
const semantic = await this.#checkExecutable(candidate.bytes, candidate.relPath).catch((error: Error) => {
rejected.push({ path: candidate.relPath, reason: error.message })
return 'rejected' as const
})
if (semantic === 'rejected') continue
const digest = digestBytes(candidate.bytes)
const target = join(root, candidate.relPath)
assertWithin(root, target)
await mkdir(dirname(target), { recursive: true, mode: 0o700 })
// Keep the previously confirmed version before replacing it.
if (await isFile(target)) {
const previous = await digestFile(target)
if (previous !== digest) {
const history = join(root, '.history', previous.slice('sha256:'.length), candidate.relPath)
assertWithin(root, history)
await mkdir(dirname(history), { recursive: true, mode: 0o700 })
await cp(target, history)
}
}
await writeFile(target, candidate.bytes, { mode: 0o600 })
imported.push({
id: `ks-${digest.slice('sha256:'.length, 'sha256:'.length + 16)}`,
relPath: candidate.relPath,
title: titleOf(text) || candidate.relPath,
digest,
bytes: candidate.bytes.byteLength,
importedAt: new Date().toISOString(),
origin: candidate.origin,
okf: looksOkf(text),
executable: semantic === 'checked' ? 'checked' : 'none',
})
}
if (imported.length > 0) {
const file = await this.#readFile()
const index = file.collections.findIndex(entry => entry.id === collection.id)
const merged = new Map(file.collections[index].sources.map(source => [source.relPath, source]))
for (const source of imported) merged.set(source.relPath, source)
file.collections[index] = {
...file.collections[index],
sources: [...merged.values()].sort((a, b) => a.relPath.localeCompare(b.relPath, 'en')),
revision: file.collections[index].revision + 1,
updatedAt: new Date().toISOString(),
}
await this.#writeFile(file)
}
return { imported, rejected }
}
/** Run the official static check when a CLI is available; otherwise refuse `.mq.md` only. */
async #checkExecutable(bytes: Buffer, relPath: string): Promise<'none' | 'checked' | 'rejected'> {
const cli = await this.#cli()
if (!cli) return 'none'
// Write a temporary copy outside the collection and let the CLI decide by AST.
const tmp = join(this.#layout.tmp, `knowledge-check-${randomBytes(6).toString('hex')}${extname(relPath) || '.md'}`)
await mkdir(this.#layout.tmp, { recursive: true, mode: 0o700 })
await writeFile(tmp, bytes, { mode: 0o600 })
try {
const result = await runProcess(cli.bin, ['check', tmp], {
cwd: this.#layout.tmp,
limits: { timeoutMs: 60_000, maxOutputBytes: 256 * 1024 },
})
// Exit 1 is invalid Markdown/Marqdo; it is not a knowledge candidate.
if (result.exitCode !== 0) throw new KnowledgeError(`static check failed: ${firstLines(result.stderr || result.stdout, 5)}`)
return 'checked'
} finally {
await rm(tmp, { force: true })
}
}
/** Read a bounded exact slice of one imported source. */
async read(input: {
collection: string
relPath: string
digest?: string
start?: number
end?: number
maxBytes?: number
}): Promise<{ relPath: string; digest: string; start: number; end: number; text: string }> {
const collection = await this.collection(input.collection)
if (!collection) throw new KnowledgeError(`unknown collection: ${input.collection}`)
const relPath = normalizeSourcePath(input.relPath)
const known = collection.sources.find(source => source.relPath === relPath)
if (!known) throw new KnowledgeError(`source is not part of this collection: ${relPath}`)
const target = join(this.sourceRoot(collection.id), relPath)
assertWithin(this.sourceRoot(collection.id), target)
const digest = await digestFile(target)
if (input.digest !== undefined && input.digest !== digest) throw new KnowledgeError('source digest does not match the requested version')
const bytes = await readFile(target)
const start = Math.max(0, Math.min(input.start ?? 0, bytes.byteLength))
const maxBytes = Math.max(1, Math.min(input.maxBytes ?? 16 * 1024, 256 * 1024))
const end = Math.max(start, Math.min(input.end ?? start + maxBytes, bytes.byteLength, start + maxBytes))
return { relPath, digest, start, end, text: bytes.subarray(start, end).toString('utf8') }
}
/** Current index state of one collection. */
async indexState(id: string): Promise<IndexState | undefined> {
const text = await readText(join(this.#layout.knowledgeIndex, id, 'state.json'))
if (text === undefined) return undefined
const parsed = JSON.parse(text) as IndexState
if (parsed.schema !== 'marqdo.mdh.knowledge-index' || parsed.schema_version !== 1) {
throw new KnowledgeError('unsupported knowledge index state')
}
return parsed
}
/** Compute the current source-tree digest for one collection. */
async sourceDigest(id: string): Promise<string> {
const root = this.sourceRoot(id)
const files = await listRegularFiles(root, { maxFiles: 10_000 }).catch(() => [])
const rows: string[] = []
for (const file of files) {
if (file.relative.startsWith('.history/') || file.relative.startsWith('.marqdo/')) continue
rows.push(`${file.relative}\t${await digestFile(join(root, file.relative))}`)
}
rows.sort()
return digestBytes(rows.join('\n'))
}
/** The installed knowledge command, if any. */
async #knowledgeTool(): Promise<{ cli: MarqdoCli; toolHome: string } | undefined> {
const cli = await this.#cli()
const toolHome = await this.#toolHome()
if (!cli || !toolHome) return undefined
const record = await readJson<Record<string, unknown>>(join(toolHome, 'knowledge', 'record.json'))
if (!record || record.command !== 'knowledge') return undefined
const manifest = await readJson<Record<string, unknown>>(join(toolHome, 'knowledge', 'tool.json'))
const requires = manifest?.requires as Record<string, unknown> | undefined
if (!manifest || requires?.api_revision !== 1 || requires?.analysis !== 3) return undefined
return { cli, toolHome }
}
/** Compile one collection through the official Knowledge Tool. */
async compile(id: string): Promise<IndexState> {
const collection = await this.collection(id)
if (!collection) throw new KnowledgeError(`unknown collection: ${id}`)
const tool = await this.#knowledgeTool()
if (!tool) {
const state: IndexState = {
schema: 'marqdo.mdh.knowledge-index', schema_version: 1, collection: id,
mode: 'locator', compiled_at: null, source_digest: await this.sourceDigest(id),
snapshot_digest: null, okf: 'unchecked', tool: null,
note: 'marqdo-knowledge is not installed; showing the read-only locator only',
}
await mkdir(join(this.#layout.knowledgeIndex, id), { recursive: true, mode: 0o700 })
await writeJsonAtomic(join(this.#layout.knowledgeIndex, id, 'state.json'), state)
return state
}
const root = this.sourceRoot(id)
const result = await runProcess(tool.cli.bin, ['knowledge', 'compile', root, '--json'], {
cwd: root,
env: { MARQDO_TOOL_HOME: tool.toolHome },
limits: { timeoutMs: 300_000, maxOutputBytes: 2 * 1024 * 1024 },
})
if (result.exitCode !== 0) throw new KnowledgeError(`knowledge compile failed: ${firstLines(result.stderr || result.stdout, 8)}`)
const envelope = JSON.parse(result.stdout) as Record<string, unknown>
if (envelope.schema !== 'marqdo.knowledge.result' || envelope.success !== true) {
throw new KnowledgeError('knowledge compile returned an unexpected envelope')
}
const okf = collection.sources.some(source => source.okf) ? await this.#checkOkf(root, tool) : 'unchecked'
const state: IndexState = {
schema: 'marqdo.mdh.knowledge-index', schema_version: 1, collection: id,
mode: 'compiled', compiled_at: new Date().toISOString(),
source_digest: await this.sourceDigest(id),
snapshot_digest: typeof envelope.snapshot_digest === 'string' ? envelope.snapshot_digest : null,
okf, tool: { name: 'marqdo-knowledge', version: null, path: tool.cli.bin },
note: 'compiled by marqdo-knowledge; query results carry exact source identity',
}
await mkdir(join(this.#layout.knowledgeIndex, id), { recursive: true, mode: 0o700 })
await writeJsonAtomic(join(this.#layout.knowledgeIndex, id, 'state.json'), state)
return state
}
/** Validate OKF only when the tool supports the explicit check. */
async #checkOkf(root: string, tool: { cli: MarqdoCli; toolHome: string }): Promise<'unchecked' | 'pass' | 'fail'> {
const result = await runProcess(tool.cli.bin, ['knowledge', 'check', root, '--okf', '--json'], {
cwd: root,
env: { MARQDO_TOOL_HOME: tool.toolHome },
limits: { timeoutMs: 120_000, maxOutputBytes: 512 * 1024 },
})
if (result.exitCode === 2) return 'unchecked'
return result.exitCode === 0 ? 'pass' : 'fail'
}
/**
* Search enabled (or explicitly selected) collections.
* @param input - query, collection filter and limit.
*/
async search(input: { query: string; collections?: readonly string[]; limit?: number }): Promise<KnowledgeSearchResult> {
const query = input.query.trim()
if (query.length === 0 || query.length > 500) throw new KnowledgeError('query must be 1..500 characters')
const limit = Math.max(1, Math.min(input.limit ?? 8, 30))
const file = await this.#readFile()
const selected = file.collections.filter(collection => input.collections && input.collections.length > 0
? input.collections.includes(collection.id)
: collection.enabled)
if (selected.length === 0) {
return { query, mode: 'locator', index_current: false, hits: [], collections: [], counts: { sources: 0, indexed: 0 }, note: 'no enabled collection matches the request' }
}
const tool = await this.#knowledgeTool()
if (!tool) {
const hits = await this.#locatorSearch(selected, query, limit)
return {
query, mode: 'locator', index_current: false,
hits, collections: selected.map(collection => collection.id),
counts: { sources: selected.reduce((sum, collection) => sum + collection.sources.length, 0), indexed: 0 },
note: 'marqdo-knowledge is not installed: results come from a bounded read-only file locator, not a compiled index',
}
}
const hits: KnowledgeHit[] = []
let indexCurrent = true
for (const collection of selected) {
const state = await this.#ensureCompiled(collection.id)
if (!state || state.mode !== 'compiled') { indexCurrent = false; continue }
const root = this.sourceRoot(collection.id)
const result = await runProcess(tool.cli.bin, [
'knowledge', 'query', query, '--root', root, '--format', 'json', '--limit', String(limit),
], {
cwd: root,
env: { MARQDO_TOOL_HOME: tool.toolHome },
limits: { timeoutMs: 120_000, maxOutputBytes: 2 * 1024 * 1024 },
})
if (result.exitCode === 2) {
indexCurrent = false
continue
}
if (result.exitCode !== 0) throw new KnowledgeError(`knowledge query failed: ${firstLines(result.stderr || result.stdout, 8)}`)
const envelope = JSON.parse(result.stdout) as Record<string, unknown>
if (envelope.schema !== 'marqdo.knowledge.result' || envelope.success !== true) {
throw new KnowledgeError('knowledge query returned an unexpected envelope')
}
if (envelope.current !== true) indexCurrent = false
const rawHits = Array.isArray(envelope.hits) ? envelope.hits : []
for (const raw of rawHits.slice(0, limit)) {
const mapped = await this.#mapHit(collection, raw)
if (mapped) hits.push(mapped)
}
}
hits.sort((a, b) => (b.score ?? 0) - (a.score ?? 0))
return {
query, mode: 'compiled', index_current: indexCurrent,
hits: hits.slice(0, limit),
collections: selected.map(collection => collection.id),
counts: { sources: selected.reduce((sum, collection) => sum + collection.sources.length, 0), indexed: hits.length },
note: indexCurrent ? 'compiled index is current' : 'index is stale or missing; results are marked accordingly',
}
}
/** Compile if the source tree changed; return undefined when compilation is impossible. */
async #ensureCompiled(id: string): Promise<IndexState | undefined> {
const state = await this.indexState(id)
const digest = await this.sourceDigest(id)
if (state && state.mode === 'compiled' && state.source_digest === digest) return state
return await this.compile(id)
}
/** Map one knowledge envelope hit to an exact collection source. */
async #mapHit(collection: KnowledgeCollection, raw: unknown): Promise<KnowledgeHit | undefined> {
if (typeof raw !== 'object' || raw === null) return undefined
const hit = raw as Record<string, unknown>
const source = hit.source
if (typeof source !== 'object' || source === null) return undefined
const record = source as Record<string, unknown>
if (typeof record.path !== 'string') return undefined
const relPath = normalizeSourcePath(record.path)
const known = collection.sources.find(entry => entry.relPath === relPath)
if (!known) return undefined
const target = join(this.sourceRoot(collection.id), relPath)
const digest = await digestFile(target).catch(() => null)
if (digest === null) return undefined
const declared = typeof record.digest === 'string' ? record.digest : undefined
const stale = declared !== undefined && declared !== digest
const spanRecord = record.span as Record<string, unknown> | undefined
const span = spanRecord && typeof spanRecord.start === 'number' && typeof spanRecord.end === 'number'
? { start: spanRecord.start, end: spanRecord.end }
: null
return {
id: typeof hit.id === 'string' ? hit.id : relPath,
collection: collection.id,
collection_name: collection.name,
rel_path: relPath,
title: typeof hit.title === 'string' ? hit.title : known.title,
snippet: typeof hit.snippet === 'string' ? hit.snippet.slice(0, 1200) : '',
digest: declared ?? digest,
span,
anchor: typeof record.anchor === 'string' ? record.anchor : null,
score: typeof hit.score === 'number' ? hit.score : null,
channels: Array.isArray(hit.matches) ? hit.matches.flatMap((match) => {
if (typeof match !== 'object' || match === null) return []
const channel = (match as Record<string, unknown>).channel
return typeof channel === 'string' ? [channel] : []
}) : [],
callable: hit.callable ?? null,
stale,
mode: 'compiled',
}
}
/** Disclosed read-only locator used only without the Knowledge Tool. */
async #locatorSearch(collections: readonly KnowledgeCollection[], query: string, limit: number): Promise<KnowledgeHit[]> {
const needle = query.toLocaleLowerCase()
const hits: KnowledgeHit[] = []
for (const collection of collections) {
const root = this.sourceRoot(collection.id)
const files = await listRegularFiles(root, { maxFiles: 2000 }).catch(() => [])
for (const file of files) {
if (file.relative.startsWith('.history/') || file.relative.startsWith('.marqdo/')) continue
if (file.size > 2 * 1024 * 1024) continue
const text = await readText(join(root, file.relative))
if (text === undefined) continue
const offset = text.toLocaleLowerCase().indexOf(needle)
if (offset === -1) continue
const digest = await digestFile(join(root, file.relative))
const before = text.lastIndexOf('\n', offset)
const lineStart = before === -1 ? 0 : before + 1
const snippet = text.slice(Math.max(0, lineStart - 200), Math.min(text.length, offset + 600)).trim()
hits.push({
id: `locator:${collection.id}:${file.relative}`,
collection: collection.id,
collection_name: collection.name,
rel_path: file.relative,
title: titleOf(text) || file.relative,
snippet,
digest,
span: null,
anchor: null,
score: null,
channels: ['substring'],
callable: null,
stale: false,
mode: 'locator',
})
if (hits.length >= limit) return hits
}
}
return hits
}
/** Export one collection without secrets, sessions or unrelated files. */
async export(id: string, destination: string): Promise<{ files: number; manifest: string }> {
const collection = await this.collection(id)
if (!collection) throw new KnowledgeError(`unknown collection: ${id}`)
const root = this.sourceRoot(id)
const files = await listRegularFiles(root, { maxFiles: 10_000 }).catch(() => [])
let count = 0
for (const file of files) {
if (file.relative.startsWith('.history/') || file.relative.startsWith('.marqdo/')) continue
const target = join(destination, file.relative)
assertWithin(destination, target)
await mkdir(dirname(target), { recursive: true, mode: 0o700 })
await cp(join(root, file.relative), target)
count++
}
const manifestPath = join(destination, 'mdh-knowledge-export.json')
await writeJsonAtomic(manifestPath, {
schema: 'marqdo.mdh.knowledge-export',
schema_version: 1,
collection: { id: collection.id, name: collection.name, description: collection.description, revision: collection.revision },
sources: collection.sources,
exported_at: new Date().toISOString(),
})
return { files: count, manifest: manifestPath }
}
/** Whether a path is a directory (used by the API for path imports). */
async isDirectory(path: string): Promise<boolean> {
return await isDirectory(path)
}
/** Relative display path of a source inside the application home. */
displayPath(id: string, relPath: string): string {
return relative(this.#layout.home, join(this.sourceRoot(id), relPath))
}
}