forked from cflmy/deepseek-harness
types: make the downstream package strict-clean in the host aggregate
Register the package sources in the host typecheck program and fix the strict findings: explicit Error.name overrides, exact optional properties, index/array narrowing and the webserver route auth field. No behavior change; the same 28 tests pass and the host aggregate reports 0 errors. Part of marqdo#25.
This commit is contained in:
1 parent
25fc24eea4
commit
d28c5e4051
13 files changed
+121
-70
No files matched your search
@@ -17,7 +17,7 @@ export const DEFAULT_STALE_MS = 10 * 60 * 1000
|
||||
|
||||
/** Lock acquisition failure. */
|
||||
export class LockTimeoutError extends Error {
|
||||
name = 'LockTimeoutError'
|
||||
override name = 'LockTimeoutError'
|
||||
}
|
||||
|
||||
interface LockRecord {
|
||||
|
||||
@@ -166,7 +166,7 @@ function summarize(
|
||||
let status: ObservationStatus = 'incomplete'
|
||||
let value: unknown
|
||||
let error: unknown
|
||||
if (terminals.length === 1 && last === terminals[0]) {
|
||||
if (terminals.length === 1 && last !== undefined && last === terminals[0]) {
|
||||
if (last.kind === 'run.completed') {
|
||||
status = 'completed'
|
||||
value = last.payload.value
|
||||
|
||||
@@ -43,7 +43,7 @@ export interface RunResult {
|
||||
|
||||
/** Subprocess rejected before spawn. */
|
||||
export class ProcessRejectedError extends Error {
|
||||
name = 'ProcessRejectedError'
|
||||
override name = 'ProcessRejectedError'
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -59,7 +59,7 @@ const BLOCK = 512
|
||||
function numeric(field: Buffer, label: string): number {
|
||||
const text = field.toString('utf8').replace(/\0.*$/s, '').trim()
|
||||
if (text === '') return 0
|
||||
if ((field[0] & 0x80) !== 0) throw new Error(`tar ${label}: base-256 values are not accepted`)
|
||||
if (((field[0] ?? 0) & 0x80) !== 0) throw new Error(`tar ${label}: base-256 values are not accepted`)
|
||||
if (!/^[0-7]+$/.test(text)) throw new Error(`tar ${label}: invalid octal ${JSON.stringify(text)}`)
|
||||
const value = Number.parseInt(text, 8)
|
||||
if (!Number.isSafeInteger(value)) throw new Error(`tar ${label}: value out of range`)
|
||||
@@ -71,7 +71,7 @@ function verifyChecksum(header: Buffer): void {
|
||||
const stored = numeric(header.subarray(148, 156), 'checksum')
|
||||
let sum = 0
|
||||
for (let index = 0; index < BLOCK; index++) {
|
||||
sum += index >= 148 && index < 156 ? 0x20 : header[index]
|
||||
sum += index >= 148 && index < 156 ? 0x20 : (header[index] ?? 0)
|
||||
}
|
||||
if (sum !== stored) throw new Error('tar header checksum mismatch')
|
||||
}
|
||||
|
||||
@@ -27,11 +27,14 @@ export function scanUnsafeNumbers(json: string): UnsafeNumber[] {
|
||||
let index = 0
|
||||
while (index < json.length) {
|
||||
const char = json[index]
|
||||
if (char === undefined) break
|
||||
if (char === '"') {
|
||||
index++
|
||||
while (index < json.length) {
|
||||
if (json[index] === '\\') index += 2
|
||||
else if (json[index] === '"') { index++; break }
|
||||
const inner = json[index]
|
||||
if (inner === undefined) break
|
||||
if (inner === '\\') index += 2
|
||||
else if (inner === '"') { index++; break }
|
||||
else index++
|
||||
}
|
||||
continue
|
||||
@@ -66,8 +69,8 @@ function unsafeReason(literal: string): string | undefined {
|
||||
/** Parse JSON after proving every numeric literal round-trips exactly. */
|
||||
export function safeJsonParse<T = unknown>(text: string): T {
|
||||
const unsafe = scanUnsafeNumbers(text)
|
||||
if (unsafe.length > 0) {
|
||||
const first = unsafe[0]
|
||||
const first = unsafe[0]
|
||||
if (first !== undefined) {
|
||||
throw new Error(`ValueWire precision loss at offset ${first.offset}: ${first.reason} (${first.literal})`)
|
||||
}
|
||||
return JSON.parse(text) as T
|
||||
|
||||
@@ -104,7 +104,7 @@ export interface EcosystemStatus {
|
||||
|
||||
/** Environment manifest/identity failure. */
|
||||
export class EcosystemError extends Error {
|
||||
name = 'EcosystemError'
|
||||
override name = 'EcosystemError'
|
||||
}
|
||||
|
||||
/** Recompute the bundle digest from the extracted stdlib directory. */
|
||||
@@ -156,7 +156,8 @@ async function verifyRelease(root: string, candidate: ReleaseCandidate, platform
|
||||
async function locateRoot(tree: string): Promise<string> {
|
||||
const entries = (await readdir(tree, { withFileTypes: true })).filter(entry => entry.isDirectory())
|
||||
const files = await readdir(tree)
|
||||
if (files.length === 1 && entries.length === 1) return join(tree, entries[0].name)
|
||||
const only = entries[0]
|
||||
if (files.length === 1 && only !== undefined) return join(tree, only.name)
|
||||
return tree
|
||||
}
|
||||
|
||||
@@ -247,7 +248,7 @@ export class EcosystemManager {
|
||||
* Install one trusted runtime release and activate it atomically.
|
||||
* @param options - component (only `cli` installs a runtime), version, platform.
|
||||
*/
|
||||
async install(options: { version?: string; platform?: string } = {}): Promise<InstallResult> {
|
||||
async install(options: { version?: string | undefined; platform?: string | undefined } = {}): Promise<InstallResult> {
|
||||
return await withLock(join(this.#layout.ecosystem, 'install.lock'), async () => {
|
||||
const platform = options.platform ?? SUPPORTED_PLATFORM
|
||||
const candidate = await discoverRelease('cli', { version: options.version, platform })
|
||||
@@ -261,6 +262,8 @@ export class EcosystemManager {
|
||||
await extractTarGz(await readFile(archive), tree)
|
||||
const root = await locateRoot(tree)
|
||||
const info = await verifyRelease(root, candidate, platform)
|
||||
const stdlib = info.stdlib
|
||||
if (!stdlib) throw new EcosystemError('release manifest has no adjacent Bundle identity')
|
||||
if (info.product_version !== candidate.tag.replace(/^v/, '')) {
|
||||
throw new EcosystemError(`release version mismatch: manifest=${info.product_version}, tag=${candidate.tag}`)
|
||||
}
|
||||
@@ -298,9 +301,9 @@ export class EcosystemManager {
|
||||
asset: { name: candidate.assetName, size: candidate.assetSize ?? 0, sha256: candidate.assetSha256 },
|
||||
protocols: info.protocols ?? {},
|
||||
bundle: {
|
||||
version: info.stdlib.version,
|
||||
tree_digest: info.stdlib.tree_digest,
|
||||
aliases_digest: info.stdlib.aliases_digest ?? null,
|
||||
version: stdlib.version,
|
||||
tree_digest: stdlib.tree_digest,
|
||||
aliases_digest: stdlib.aliases_digest ?? null,
|
||||
},
|
||||
cli_path: 'marqdo',
|
||||
worker_path: 'marqdo-provider-worker',
|
||||
|
||||
@@ -64,7 +64,7 @@ export interface ReleaseCandidate {
|
||||
|
||||
/** Discovery failure. */
|
||||
export class ReleaseError extends Error {
|
||||
name = 'ReleaseError'
|
||||
override name = 'ReleaseError'
|
||||
}
|
||||
|
||||
interface GiteaAsset {
|
||||
@@ -122,7 +122,7 @@ function assetNameFor(component: ReleasedComponent, tag: string, platform: strin
|
||||
/** Parse a `.sha256` sidecar (`<hex> <name>`). */
|
||||
function parseShaSidecar(text: string): string | null {
|
||||
const match = /([0-9a-fA-F]{64})/.exec(text)
|
||||
return match ? match[1].toLowerCase() : null
|
||||
return match?.[1] !== undefined ? match[1].toLowerCase() : null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,7 +132,7 @@ function parseShaSidecar(text: string): string | null {
|
||||
*/
|
||||
export async function discoverRelease(
|
||||
component: ReleasedComponent,
|
||||
options: { version?: string; platform?: string } = {},
|
||||
options: { version?: string | undefined; platform?: string | undefined } = {},
|
||||
): Promise<ReleaseCandidate> {
|
||||
const source = COMPONENT_SOURCES[component]
|
||||
if (!source) throw new ReleaseError(`component is not installable from a release: ${component}`)
|
||||
|
||||
@@ -24,11 +24,11 @@ export type SandboxMode = 'pure' | 'project' | 'strict'
|
||||
|
||||
/** Explicit resource grants; every list is validated before argv construction. */
|
||||
export interface Grants {
|
||||
readonly read?: readonly string[]
|
||||
readonly write?: readonly string[]
|
||||
readonly net?: readonly string[]
|
||||
readonly env?: readonly string[]
|
||||
readonly process?: readonly string[]
|
||||
readonly read?: readonly string[] | undefined
|
||||
readonly write?: readonly string[] | undefined
|
||||
readonly net?: readonly string[] | undefined
|
||||
readonly env?: readonly string[] | undefined
|
||||
readonly process?: readonly string[] | undefined
|
||||
readonly random?: boolean
|
||||
readonly foreign?: boolean
|
||||
}
|
||||
@@ -56,7 +56,7 @@ export interface ExecutedDocument {
|
||||
|
||||
/** Rejected before any process starts. */
|
||||
export class ExecutionRejectedError extends Error {
|
||||
name = 'ExecutionRejectedError'
|
||||
override name = 'ExecutionRejectedError'
|
||||
}
|
||||
|
||||
/** Validate one grant string shared by read/write globs. */
|
||||
@@ -146,7 +146,13 @@ export class MarqdoCli {
|
||||
readonly #workspace: string
|
||||
readonly #tmp: string
|
||||
|
||||
constructor(options: { bin: string; workspace: string; tmp: string; version?: string; sourceSha?: string }) {
|
||||
constructor(options: {
|
||||
bin: string
|
||||
workspace: string
|
||||
tmp: string
|
||||
version?: string | undefined
|
||||
sourceSha?: string | undefined
|
||||
}) {
|
||||
if (!isAbsolute(options.bin)) throw new ExecutionRejectedError(`CLI path must be absolute: ${options.bin}`)
|
||||
this.bin = options.bin
|
||||
this.#workspace = resolve(options.workspace)
|
||||
@@ -185,12 +191,12 @@ export class MarqdoCli {
|
||||
async execute(options: {
|
||||
relativePath: string
|
||||
action: 'run' | 'call'
|
||||
functionName?: string
|
||||
args?: readonly string[]
|
||||
mode?: SandboxMode
|
||||
grants?: Grants
|
||||
expectedAnalysisDigest?: string
|
||||
limits?: RunLimits
|
||||
functionName?: string | undefined
|
||||
args?: readonly string[] | undefined
|
||||
mode?: SandboxMode | undefined
|
||||
grants?: Grants | undefined
|
||||
expectedAnalysisDigest?: string | undefined
|
||||
limits?: RunLimits | undefined
|
||||
}): Promise<ExecutedDocument> {
|
||||
documentPath(this.#workspace, options.relativePath)
|
||||
const mode = options.mode ?? 'pure'
|
||||
|
||||
@@ -114,7 +114,7 @@ export interface KnowledgeSearchResult {
|
||||
|
||||
/** Knowledge operation failure. */
|
||||
export class KnowledgeError extends Error {
|
||||
name = 'KnowledgeError'
|
||||
override name = 'KnowledgeError'
|
||||
}
|
||||
|
||||
/** Validate a collection name. */
|
||||
@@ -142,7 +142,7 @@ function normalizeSourcePath(value: string): string {
|
||||
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]
|
||||
if (match?.[1] !== undefined) return match[1]
|
||||
}
|
||||
return ''
|
||||
}
|
||||
@@ -164,8 +164,8 @@ function containsExecHeading(text: string): boolean {
|
||||
/** Knowledge collection manager. */
|
||||
export class KnowledgeManager {
|
||||
readonly #layout: MdhLayout
|
||||
readonly #cli: () => MarqdoCli | undefined
|
||||
readonly #toolHome: () => string | undefined
|
||||
readonly #cli: () => Promise<MarqdoCli | undefined>
|
||||
readonly #toolHome: () => Promise<string | undefined>
|
||||
readonly #collectionsFile: string
|
||||
|
||||
constructor(options: {
|
||||
@@ -236,8 +236,9 @@ export class KnowledgeManager {
|
||||
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() }
|
||||
const existing = file.collections[index]
|
||||
if (index === -1 || existing === undefined) throw new KnowledgeError(`unknown collection: ${id}`)
|
||||
const updated: KnowledgeCollection = { ...existing, enabled, updatedAt: new Date().toISOString() }
|
||||
file.collections[index] = updated
|
||||
await this.#writeFile(file)
|
||||
return updated
|
||||
@@ -263,8 +264,8 @@ export class KnowledgeManager {
|
||||
/** 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 }[]
|
||||
paths?: readonly string[] | undefined
|
||||
contents?: readonly { filename: string; content: string }[] | undefined
|
||||
}): 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}`)
|
||||
@@ -359,12 +360,14 @@ export class KnowledgeManager {
|
||||
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]))
|
||||
const existing = file.collections[index]
|
||||
if (existing === undefined) throw new KnowledgeError(`unknown collection: ${collection.id}`)
|
||||
const merged = new Map(existing.sources.map(source => [source.relPath, source]))
|
||||
for (const source of imported) merged.set(source.relPath, source)
|
||||
file.collections[index] = {
|
||||
...file.collections[index],
|
||||
...existing,
|
||||
sources: [...merged.values()].sort((a, b) => a.relPath.localeCompare(b.relPath, 'en')),
|
||||
revision: file.collections[index].revision + 1,
|
||||
revision: existing.revision + 1,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
await this.#writeFile(file)
|
||||
@@ -397,10 +400,10 @@ export class KnowledgeManager {
|
||||
async read(input: {
|
||||
collection: string
|
||||
relPath: string
|
||||
digest?: string
|
||||
start?: number
|
||||
end?: number
|
||||
maxBytes?: number
|
||||
digest?: string | undefined
|
||||
start?: number | undefined
|
||||
end?: number | undefined
|
||||
maxBytes?: number | undefined
|
||||
}): 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}`)
|
||||
@@ -511,7 +514,11 @@ export class KnowledgeManager {
|
||||
* 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> {
|
||||
async search(input: {
|
||||
query: string
|
||||
collections?: readonly string[] | undefined
|
||||
limit?: number | undefined
|
||||
}): 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))
|
||||
|
||||
@@ -75,7 +75,7 @@ export interface MdhStatus {
|
||||
}
|
||||
|
||||
/** Resolve one CLI path override safely. */
|
||||
async function overrideCli(): Promise<{ bin: string; version?: string; sourceSha?: string } | undefined> {
|
||||
async function overrideCli(): Promise<{ bin: string; version?: string | undefined; sourceSha?: string | undefined } | 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')
|
||||
@@ -190,7 +190,10 @@ export class MdhRuntime {
|
||||
* @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[]> {
|
||||
async find(
|
||||
query: string,
|
||||
options: { kind?: string | undefined; limit?: number | undefined; path?: string | undefined } = {},
|
||||
): Promise<FunctionCandidate[]> {
|
||||
const limit = Math.max(1, Math.min(options.limit ?? 8, 20))
|
||||
const needle = query.trim().toLocaleLowerCase()
|
||||
const candidates: FunctionCandidate[] = []
|
||||
@@ -259,10 +262,15 @@ export class MdhRuntime {
|
||||
* 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> {
|
||||
async read(
|
||||
id: string,
|
||||
options: { start?: number | undefined; end?: number | undefined; maxBytes?: number | undefined } = {},
|
||||
): Promise<ReadResult> {
|
||||
if (id.startsWith('knowledge:')) {
|
||||
const [, collection, ...rest] = id.split(':')
|
||||
const relPath = rest.join(':').split('#')[0]
|
||||
if (collection === undefined) throw new Error(`invalid knowledge candidate: ${id}`)
|
||||
const relPath = rest.join(':').split('#')[0] ?? ''
|
||||
if (relPath === '') throw new Error(`invalid knowledge candidate: ${id}`)
|
||||
const result = await this.knowledge.read({
|
||||
collection, relPath, start: options.start, end: options.end, maxBytes: options.maxBytes,
|
||||
})
|
||||
@@ -275,15 +283,21 @@ export class MdhRuntime {
|
||||
if (!id.startsWith('workspace:')) throw new Error(`unsupported candidate id: ${id}`)
|
||||
const body = id.slice('workspace:'.length)
|
||||
const [location, digestPart] = body.split('@')
|
||||
if (location === undefined) throw new Error(`invalid candidate id: ${id}`)
|
||||
const [relativePath, range] = location.split('#')
|
||||
const [rangeStart, rangeEnd] = (range ?? '').split('-').map(value => Number.parseInt(value, 10))
|
||||
if (relativePath === undefined) throw new Error(`invalid candidate id: ${id}`)
|
||||
const rangeParts = (range ?? '').split('-').map(value => Number.parseInt(value, 10))
|
||||
const rangeStart = rangeParts[0]
|
||||
const rangeEnd = rangeParts[1]
|
||||
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 fallbackStart = Number.isFinite(rangeStart) && rangeStart !== undefined ? rangeStart : 0
|
||||
const start = Math.max(0, Math.min(options.start ?? fallbackStart, bytes.byteLength))
|
||||
const fallbackEnd = Number.isFinite(rangeEnd) && rangeEnd !== undefined && rangeEnd > start ? rangeEnd : start + maxBytes
|
||||
const requestedEnd = options.end ?? fallbackEnd
|
||||
const end = Math.max(start, Math.min(requestedEnd, bytes.byteLength, start + maxBytes))
|
||||
return {
|
||||
id, kind: 'workspace', provenance: `workspace:${relativePath}`, digest,
|
||||
@@ -299,8 +313,8 @@ export class MdhRuntime {
|
||||
async execute(input: {
|
||||
relativePath: string
|
||||
action: 'run' | 'call'
|
||||
functionName?: string
|
||||
args?: readonly string[]
|
||||
functionName?: string | undefined
|
||||
args?: readonly string[] | undefined
|
||||
mode: SandboxMode
|
||||
grants: Grants
|
||||
checked: CheckedDocument
|
||||
@@ -352,6 +366,7 @@ export class MdhRuntime {
|
||||
violations: executed.observation.violations,
|
||||
stored: true,
|
||||
},
|
||||
result_artifact: null,
|
||||
}
|
||||
await this.evidence.save(record, executed.observationText)
|
||||
const stored = await this.evidence.read(record.run_id, this.workspace)
|
||||
@@ -360,7 +375,10 @@ export class MdhRuntime {
|
||||
}
|
||||
|
||||
/** Search enabled private knowledge collections. */
|
||||
async searchKnowledge(query: string, options: { collections?: readonly string[]; limit?: number } = {}): Promise<KnowledgeSearchResult> {
|
||||
async searchKnowledge(
|
||||
query: string,
|
||||
options: { collections?: readonly string[] | undefined; limit?: number | undefined } = {},
|
||||
): Promise<KnowledgeSearchResult> {
|
||||
return await this.knowledge.search({ query, collections: options.collections, limit: options.limit })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,14 +79,20 @@ function stringField(body: Record<string, unknown>, key: string): string {
|
||||
}
|
||||
|
||||
/** Register the routes for one runtime. */
|
||||
function registerRoutes(ctx: Context, runtime: MdhRuntime, config: { trustedHosts: readonly string[]; bindHost?: string }): void {
|
||||
function registerRoutes(
|
||||
ctx: Context,
|
||||
runtime: MdhRuntime,
|
||||
config: { trustedHosts: readonly string[]; bindHost?: string | undefined },
|
||||
): void {
|
||||
const webServer = ctx.get('webServer' as never) as {
|
||||
register(route: {
|
||||
kind: 'prefix'
|
||||
path: string
|
||||
auth?: string
|
||||
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>
|
||||
}): () => void
|
||||
}
|
||||
} | undefined
|
||||
if (!webServer) throw new Error('mdh-web requires the webServer service')
|
||||
const fence = (req: IncomingMessage): void => {
|
||||
const host = req.headers.host
|
||||
if (typeof host !== 'string' || host === '') throw new HttpError(403, 'missing Host header')
|
||||
@@ -208,6 +214,7 @@ async function handleApi(
|
||||
const collectionMatch = /^\/knowledge\/collections\/([a-z0-9-]+)(\/[a-z]+)?$/.exec(path)
|
||||
if (collectionMatch) {
|
||||
const id = collectionMatch[1]
|
||||
if (id === undefined) throw new HttpError(400, 'missing collection id')
|
||||
const sub = collectionMatch[2] ?? ''
|
||||
if (sub === '' && method === 'DELETE') {
|
||||
await runtime.knowledge.delete(id)
|
||||
@@ -315,7 +322,9 @@ async function handleApi(
|
||||
}
|
||||
const runMatch = /^\/runs\/([A-Za-z0-9._-]+)$/.exec(path)
|
||||
if (runMatch && method === 'GET') {
|
||||
const record = await runtime.evidence.read(runMatch[1], runtime.workspace)
|
||||
const runId = runMatch[1]
|
||||
if (runId === undefined) throw new HttpError(400, 'missing run id')
|
||||
const record = await runtime.evidence.read(runId, runtime.workspace)
|
||||
if (!record) throw new HttpError(404, 'unknown run')
|
||||
json(res, 200, { run: record })
|
||||
return
|
||||
@@ -338,7 +347,7 @@ async function handleApi(
|
||||
}
|
||||
|
||||
/** Register the workbench and its API over the DSH web server. */
|
||||
export function apply(ctx: Context, config: { trustedHosts?: readonly string[]; bindHost?: string } = {}): void {
|
||||
export function apply(ctx: Context, config: { trustedHosts?: readonly string[] | undefined; bindHost?: string | undefined } = {}): void {
|
||||
const runtime = ctx.get('mdhRuntime' as never) as MdhRuntime | undefined
|
||||
if (!runtime) throw new Error('mdh-web requires mdhRuntime')
|
||||
registerRoutes(ctx, runtime, { trustedHosts: config.trustedHosts ?? [], bindHost: config.bindHost })
|
||||
|
||||
@@ -38,8 +38,10 @@ test('plain Markdown is copied and executable documents are refused', async () =
|
||||
await writeFile(source, '# 校正规则\n\n对于非负读数 x,校正值为 2*x+1。\n')
|
||||
const result = await knowledge.import({ collection: collection.id, paths: [source] })
|
||||
assert.equal(result.imported.length, 1)
|
||||
assert.equal(result.imported[0].title, '校正规则')
|
||||
assert.match(result.imported[0].digest, /^sha256:[0-9a-f]{64}$/)
|
||||
const first = result.imported[0]
|
||||
assert.ok(first)
|
||||
assert.equal(first.title, '校正规则')
|
||||
assert.match(first.digest, /^sha256:[0-9a-f]{64}$/)
|
||||
// The original file is never modified.
|
||||
assert.match(await readFile(source, 'utf8'), /2\*x\+1/)
|
||||
|
||||
@@ -47,19 +49,19 @@ test('plain Markdown is copied and executable documents are refused', async () =
|
||||
await writeFile(executable, '# @knowledge\n\n## @exec 计算\n\n`return 1`\n')
|
||||
const refused = await knowledge.import({ collection: collection.id, paths: [executable] })
|
||||
assert.equal(refused.imported.length, 0)
|
||||
assert.match(refused.rejected[0].reason, /executable \.mq\.md/)
|
||||
assert.match(refused.rejected[0]?.reason ?? '', /executable \.mq\.md/)
|
||||
|
||||
const marker = join(root, 'marker.md')
|
||||
await writeFile(marker, '# 规则\n\n## @exec 隐藏计算\n\n`return 1`\n')
|
||||
const markerResult = await knowledge.import({ collection: collection.id, paths: [marker] })
|
||||
assert.equal(markerResult.imported.length, 0)
|
||||
assert.match(markerResult.rejected[0].reason, /@exec region/)
|
||||
assert.match(markerResult.rejected[0]?.reason ?? '', /@exec region/)
|
||||
|
||||
const binary = join(root, 'image.png')
|
||||
await writeFile(binary, Buffer.from([0x89, 0x50, 0x4e, 0x47]))
|
||||
const binaryResult = await knowledge.import({ collection: collection.id, paths: [binary] })
|
||||
assert.equal(binaryResult.imported.length, 0)
|
||||
assert.match(binaryResult.rejected[0].reason, /unsupported knowledge file type/)
|
||||
assert.match(binaryResult.rejected[0]?.reason ?? '', /unsupported knowledge file type/)
|
||||
})
|
||||
|
||||
test('symlinked imports and escaping paths are refused', async () => {
|
||||
@@ -71,7 +73,7 @@ test('symlinked imports and escaping paths are refused', async () => {
|
||||
await symlink(real, link)
|
||||
const result = await knowledge.import({ collection: collection.id, paths: [link] })
|
||||
assert.equal(result.imported.length, 0)
|
||||
assert.match(result.rejected[0].reason, /symbolic link/)
|
||||
assert.match(result.rejected[0]?.reason ?? '', /symbolic link/)
|
||||
})
|
||||
|
||||
test('browser uploads share the same import policy', async () => {
|
||||
@@ -82,7 +84,7 @@ test('browser uploads share the same import policy', async () => {
|
||||
contents: [{ filename: 'upload.md', content: '# 上传文档\n\n内容\n' }],
|
||||
})
|
||||
assert.equal(result.imported.length, 1)
|
||||
assert.equal(result.imported[0].origin, 'upload.md')
|
||||
assert.equal(result.imported[0]?.origin, 'upload.md')
|
||||
})
|
||||
|
||||
test('locator search is disclosed, bounded and keeps source identity', async () => {
|
||||
@@ -99,6 +101,7 @@ test('locator search is disclosed, bounded and keeps source identity', async ()
|
||||
assert.match(result.note, /read-only file locator/)
|
||||
assert.equal(result.hits.length, 1)
|
||||
const hit = result.hits[0]
|
||||
assert.ok(hit)
|
||||
assert.equal(hit.collection, collection.id)
|
||||
assert.equal(hit.rel_path, 'a.md')
|
||||
assert.equal(hit.title, '第一条')
|
||||
@@ -117,7 +120,8 @@ test('exact read verifies the digest and is bounded', async () => {
|
||||
const source = join(root, 'doc.md')
|
||||
await writeFile(source, '# 标题\n\nabcdefghij\n')
|
||||
const imported = await knowledge.import({ collection: collection.id, paths: [source] })
|
||||
const digest = imported.imported[0].digest
|
||||
const digest = imported.imported[0]?.digest
|
||||
assert.ok(digest)
|
||||
const read = await knowledge.read({ collection: collection.id, relPath: 'doc.md', digest, start: 0, end: 10 })
|
||||
assert.equal(read.text, '# 标题\n\n')
|
||||
await assert.rejects(
|
||||
@@ -138,7 +142,7 @@ test('re-import preserves a digest history and changes the source revision', asy
|
||||
const first = await knowledge.import({ collection: collection.id, paths: [source] })
|
||||
await writeFile(source, '# 第二版\n')
|
||||
const second = await knowledge.import({ collection: collection.id, paths: [source] })
|
||||
assert.notEqual(first.imported[0].digest, second.imported[0].digest)
|
||||
assert.notEqual(first.imported[0]?.digest, second.imported[0]?.digest)
|
||||
const updated = await knowledge.collection(collection.id)
|
||||
assert.equal(updated?.revision, 3)
|
||||
const history = await readdir(join(knowledge.sourceRoot(collection.id), '.history'))
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"rewriteRelativeImportExtensions": false
|
||||
},
|
||||
"include": [
|
||||
"packages/marqdo/harness/src/**/*.ts",
|
||||
"apps/web/tests/device-pairing.e2e.ts",
|
||||
"apps/web/tests/pairing-completion.e2e.ts",
|
||||
"apps/web/tests/pairing-recovery.e2e.ts",
|
||||
|
||||
Reference in new issue
Block a user