Files
marqdo-app-harness/packages/marqdo/harness/src/runtime.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

380 lines
16 KiB
TypeScript

/**
* Product runtime shared by the model tools and the `/mdh` workbench.
*
* One runtime owns the resolved home, workspace, ecosystem manager, knowledge
* manager, evidence store and the CLI adapter cache. The Cordis plugin provides
* it as `ctx.mdhRuntime` so the Web half uses the same state as the tools.
*
* @module @marqdo/mdh-harness/runtime
*/
import { readFile, stat } from 'node:fs/promises'
import { isAbsolute, join, resolve } from 'node:path'
import { digestFile } from './core/fsx.ts'
import { ensureMdhHome, resolveMdhHome } from './core/home.ts'
import type { MdhLayout } from './core/home.ts'
import { EcosystemManager } from './ecosystem/manager.ts'
import type { EcosystemStatus } from './ecosystem/manager.ts'
import { EvidenceStore } from './execution/evidence.ts'
import type { RunEvidence, RunRecord } from './execution/evidence.ts'
import { MarqdoCli } from './execution/cli.ts'
import type { CheckedDocument, ExecutedDocument, Grants, SandboxMode } from './execution/cli.ts'
import { formatSignature } from './execution/analysis.ts'
import type { AnalysisFunction } from './execution/analysis.ts'
import { KnowledgeManager } from './knowledge/manager.ts'
import type { KnowledgeSearchResult } from './knowledge/manager.ts'
import { ensureWorkspace, listDocuments, resolveDocument } from './workspace.ts'
/** Product configuration accepted from the profile row. */
export interface MdhConfig {
/** Application home; defaults to `$MDH_HOME` or the XDG data directory. */
home?: string
/** Task workspace; defaults to `$MDH_WORKSPACE` or `MDH_HOME/workspaces/default`. */
workspace?: string
/** Extra non-loopback authorities admitted by the `/mdh` API fence. */
trustedHosts?: string[]
/** The listener bind address, when the deployment binds a concrete literal. */
bindHost?: string
/** Upper bound for one Marqdo execution. */
maxRunMs?: number
}
/** One function candidate returned by `marqdo_find`. */
export interface FunctionCandidate {
readonly id: string
readonly kind: 'function' | 'document' | 'tool' | 'stdlib' | 'ext'
readonly title: string
readonly signature: string | null
readonly location: string
readonly summary: string
readonly availability: 'available' | 'unavailable'
readonly source: 'analysis' | 'knowledge' | 'ecosystem'
}
/** Result of reading an exact candidate. */
export interface ReadResult {
readonly id: string
readonly kind: string
readonly provenance: string
readonly digest: string
readonly start: number
readonly end: number
readonly text: string
readonly truncated: boolean
}
/** Aggregate status shown to models and the workbench. */
export interface MdhStatus {
readonly home: string
workspace: string
readonly ecosystem: EcosystemStatus
readonly knowledge: { readonly collections: number; readonly sources: number; readonly enabled: number }
readonly privacy: { readonly telemetry: false; readonly sessionUpload: false; readonly pluginInstall: false }
readonly platform: string
readonly node: string
}
/** Resolve one CLI path override safely. */
async function overrideCli(): Promise<{ bin: string; version?: string; sourceSha?: string } | undefined> {
const bin = process.env.MDH_CLI_BIN?.trim()
if (!bin) return undefined
if (!isAbsolute(bin)) throw new Error('MDH_CLI_BIN must be absolute')
await stat(bin)
return { bin, sourceSha: process.env.MDH_CLI_SOURCE_SHA }
}
/** The product runtime. */
export class MdhRuntime {
readonly config: MdhConfig
readonly layout: MdhLayout
workspace: string
readonly ecosystem: EcosystemManager
readonly knowledge: KnowledgeManager
readonly evidence: EvidenceStore
readonly #cliCache = new Map<string, { cli: MarqdoCli }>()
readonly #analysisCache = new Map<string, CheckedDocument>()
private constructor(config: MdhConfig, layout: MdhLayout, workspace: string) {
this.config = config
this.layout = layout
this.workspace = workspace
this.ecosystem = new EcosystemManager(layout)
this.evidence = new EvidenceStore(layout.runs)
this.knowledge = new KnowledgeManager({
layout,
cli: () => this.cli(),
toolHome: async () => {
const environment = await this.ecosystem.current()
return environment ? join(this.layout.environments, environment.id, environment.tool_home) : undefined
},
})
}
/**
* Create the runtime: resolve the home, create the layout and workspace, and
* return the shared managers. No network access and no environment install.
*/
static async create(config: MdhConfig = {}): Promise<MdhRuntime> {
const home = resolveMdhHome(config.home)
const layout = await ensureMdhHome(home)
const workspace = await ensureWorkspace(layout, config.workspace)
return new MdhRuntime(config, layout, workspace)
}
/** Configured workspace override applied at runtime (Web settings). */
async setWorkspace(workspace: string): Promise<void> {
if (!isAbsolute(workspace)) throw new Error('workspace must be an absolute path')
this.workspace = resolve(workspace)
}
/** The installed CLI, when an environment exists or an override is configured. */
async cli(): Promise<MarqdoCli | undefined> {
const override = await overrideCli()
const environment = await this.ecosystem.current()
const bin = override?.bin ?? (environment ? join(this.layout.environments, environment.id, environment.cli_path) : undefined)
if (!bin) return undefined
const cached = this.#cliCache.get(bin)
if (cached) return cached.cli
const cli = new MarqdoCli({
bin,
workspace: this.workspace,
tmp: this.layout.tmp,
version: override?.version ?? environment?.version,
sourceSha: override?.sourceSha ?? environment?.source_sha ?? undefined,
})
this.#cliCache.set(bin, { cli })
return cli
}
/** Resolve the Tool home asynchronously and cache a CLI first. */
async prepareCli(): Promise<{ cli: MarqdoCli; toolHome: string } | undefined> {
const cli = await this.cli()
const environment = await this.ecosystem.current()
if (!cli || !environment) return undefined
return { cli, toolHome: join(this.layout.environments, environment.id, environment.tool_home) }
}
/** Aggregate real state for the workbench and `marqdo_ecosystem(status)`. */
async status(): Promise<MdhStatus> {
const collections = await this.knowledge.collections()
return {
home: this.layout.home,
workspace: this.workspace,
ecosystem: await this.ecosystem.status(),
knowledge: {
collections: collections.length,
sources: collections.reduce((sum, collection) => sum + collection.sources.length, 0),
enabled: collections.filter(collection => collection.enabled).length,
},
privacy: { telemetry: false, sessionUpload: false, pluginInstall: false },
platform: `${process.platform}-${process.arch}`,
node: process.version,
}
}
/** Static check with a source-digest cache. */
async check(relativePath: string): Promise<CheckedDocument> {
const absolute = await resolveDocument(this.workspace, relativePath)
const digest = await digestFile(absolute)
const cached = this.#analysisCache.get(relativePath)
if (cached && cached.sourceDigest === digest) return cached
const cli = await this.cli()
if (!cli) throw new Error('no Marqdo CLI is installed; install a trusted runtime from the Ecosystem page')
const checked = await cli.check(relativePath)
this.#analysisCache.set(relativePath, checked)
return checked
}
/**
* Find installed/available capabilities relevant to a query.
* @param query - free text matched against names, signatures and titles.
* @param options - kind filter, result bound and optional workspace subtree.
*/
async find(query: string, options: { kind?: string; limit?: number; path?: string } = {}): Promise<FunctionCandidate[]> {
const limit = Math.max(1, Math.min(options.limit ?? 8, 20))
const needle = query.trim().toLocaleLowerCase()
const candidates: FunctionCandidate[] = []
const status = await this.ecosystem.status()
if (!options.kind || options.kind === 'tool') {
for (const tool of status.tools) {
if (!needle || tool.command.toLocaleLowerCase().includes(needle) || needle.includes(tool.command.toLocaleLowerCase())) {
candidates.push({
id: `tool:${tool.command}`, kind: 'tool', title: `marqdo ${tool.command}`,
signature: null, location: tool.path, summary: 'installed CLI Tool command',
availability: 'available', source: 'ecosystem',
})
}
}
}
if (!options.kind || options.kind === 'stdlib') {
for (const module of status.std.modules) {
const title = module.replace(/\.mq\.md$/, '')
if (!needle || title.toLocaleLowerCase().includes(needle)) {
candidates.push({
id: `stdlib:${module}`, kind: 'stdlib', title,
signature: null, location: `stdlib/${module}`, summary: 'module in the active stdlib Bundle',
availability: status.std.installed ? 'available' : 'unavailable', source: 'ecosystem',
})
}
}
}
if (candidates.length >= limit) return candidates.slice(0, limit)
const documents = await listDocuments(this.workspace, { maxFiles: 40 })
const filtered = options.path
? documents.filter(document => document.relative.startsWith(options.path ?? ''))
: documents
let analyzed = 0
for (const document of filtered) {
if (analyzed >= 12) break
let checked: CheckedDocument
try {
checked = await this.check(document.relative)
} catch {
continue
}
analyzed++
for (const fn of checked.analysis.functions) {
const signature = formatSignature(fn)
const haystack = `${fn.localName} ${fn.namespace ?? ''} ${signature}`.toLocaleLowerCase()
if (!needle || haystack.includes(needle)) {
const span = fn.span
candidates.push({
id: `workspace:${document.relative}#${span?.start ?? 0}-${span?.end ?? 0}@${checked.sourceDigest}`,
kind: 'function',
title: fn.namespace ? `${fn.namespace}.${fn.localName}` : fn.localName,
signature,
location: `${document.relative}:${span?.start ?? 0}-${span?.end ?? 0}`,
summary: `Marqdo function in ${document.relative}; effects: ${fn.effects.join(', ') || 'none declared'}`,
availability: 'available',
source: 'analysis',
})
}
if (candidates.length >= limit) return candidates.slice(0, limit)
}
}
return candidates.slice(0, limit)
}
/**
* Read one exact candidate with a bounded range.
* @param id - `workspace:<rel>#<start>-<end>[@digest]` or `knowledge:<collection>:<rel>`.
*/
async read(id: string, options: { start?: number; end?: number; maxBytes?: number } = {}): Promise<ReadResult> {
if (id.startsWith('knowledge:')) {
const [, collection, ...rest] = id.split(':')
const relPath = rest.join(':').split('#')[0]
const result = await this.knowledge.read({
collection, relPath, start: options.start, end: options.end, maxBytes: options.maxBytes,
})
return {
id, kind: 'knowledge', provenance: `knowledge:${collection}:${relPath}`,
digest: result.digest, start: result.start, end: result.end, text: result.text,
truncated: result.end - result.start >= (options.maxBytes ?? 16 * 1024),
}
}
if (!id.startsWith('workspace:')) throw new Error(`unsupported candidate id: ${id}`)
const body = id.slice('workspace:'.length)
const [location, digestPart] = body.split('@')
const [relativePath, range] = location.split('#')
const [rangeStart, rangeEnd] = (range ?? '').split('-').map(value => Number.parseInt(value, 10))
const absolute = await resolveDocument(this.workspace, relativePath)
const digest = await digestFile(absolute)
if (digestPart && digestPart !== digest) throw new Error('candidate digest no longer matches the workspace source')
const bytes = await readFile(absolute)
const maxBytes = Math.max(1, Math.min(options.maxBytes ?? 12 * 1024, 128 * 1024))
const start = Math.max(0, Math.min(options.start ?? (Number.isFinite(rangeStart) ? rangeStart : 0), bytes.byteLength))
const requestedEnd = options.end ?? (Number.isFinite(rangeEnd) && rangeEnd > start ? rangeEnd : start + maxBytes)
const end = Math.max(start, Math.min(requestedEnd, bytes.byteLength, start + maxBytes))
return {
id, kind: 'workspace', provenance: `workspace:${relativePath}`, digest,
start, end, text: bytes.subarray(start, end).toString('utf8'),
truncated: end < bytes.byteLength,
}
}
/**
* Execute one checked document through the CLI and persist evidence.
* The caller has already obtained approval.
*/
async execute(input: {
relativePath: string
action: 'run' | 'call'
functionName?: string
args?: readonly string[]
mode: SandboxMode
grants: Grants
checked: CheckedDocument
}): Promise<{ executed: ExecutedDocument; evidence: RunEvidence; record: RunRecord }> {
const cli = await this.cli()
if (!cli) throw new Error('no Marqdo CLI is installed')
const executed = await cli.execute({
relativePath: input.relativePath,
action: input.action,
functionName: input.functionName,
args: input.args,
mode: input.mode,
grants: input.grants,
expectedAnalysisDigest: input.checked.analysis.digest,
limits: { timeoutMs: this.config.maxRunMs ?? 300_000 },
})
const environment = await this.ecosystem.current()
const record: RunEvidence = {
schema: 'marqdo.mdh.run-evidence',
schema_version: 1,
run_id: this.evidence.keyFor(executed.observation.runId ?? `run-${Date.now()}`),
created_at: new Date().toISOString(),
workspace: this.workspace,
document: input.relativePath,
document_digest: input.checked.sourceDigest,
analysis_digest: input.checked.analysis.digest,
environment_id: environment?.id ?? null,
cli: {
path: cli.bin,
version: cli.version ?? null,
source_sha: cli.sourceSha ?? null,
},
bundle_digest: environment?.bundle.tree_digest ?? null,
lock_digest: null,
action: input.action,
function_name: input.functionName ?? null,
arguments: [...(input.args ?? [])],
mode: input.mode,
grants: input.grants,
status: executed.observation.status,
terminal_kind: executed.observation.terminalKind ?? null,
result: {
value: executed.observation.value ?? null,
error: executed.observation.error ?? null,
value_render: renderResult(executed.observation.value),
},
observation: {
event_count: executed.observation.eventCount,
violations: executed.observation.violations,
stored: true,
},
}
await this.evidence.save(record, executed.observationText)
const stored = await this.evidence.read(record.run_id, this.workspace)
if (!stored) throw new Error('evidence record was not readable after save')
return { executed, evidence: record, record: stored }
}
/** Search enabled private knowledge collections. */
async searchKnowledge(query: string, options: { collections?: readonly string[]; limit?: number } = {}): Promise<KnowledgeSearchResult> {
return await this.knowledge.search({ query, collections: options.collections, limit: options.limit })
}
}
/** Render a completed ValueWire value without converting integers to JS numbers. */
function renderResult(value: unknown): string | null {
if (typeof value !== 'object' || value === null) return null
const record = value as Record<string, unknown>
if (typeof record.type === 'string' && typeof record.decimal === 'string') return record.decimal
return JSON.stringify(value)
}
/** Format one function for model-facing summaries. */
export function describeFunction(fn: AnalysisFunction): string {
return `${formatSignature(fn)} — ${fn.moduleId}`
}