T-176: merge dev
This commit is contained in:
commit
fc2ca6f483
13 changed files with 3618 additions and 369 deletions
883
libs/research/src/mcp/adapters/library-cards.ts
Normal file
883
libs/research/src/mcp/adapters/library-cards.ts
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
/**
|
||||
* Read-only filesystem adapter for the MCP copilot `read_knowledge` tool,
|
||||
* implementing {@link KnowledgePort.listLibraryCards} over `<root>/library.yml`
|
||||
* and `<root>/cards/<sectionId>/<slug>.md`.
|
||||
*
|
||||
* Filesystem access is injected via {@link LibraryCardFs} for hermetic testing,
|
||||
* with {@link createNodeLibraryCardFs} provided for Node/Bun composition.
|
||||
*/
|
||||
|
||||
import { constants as fsConstants } from 'node:fs';
|
||||
import { type FileHandle, open, readdir, stat } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge';
|
||||
|
||||
const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/;
|
||||
const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/;
|
||||
const PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s](?:(?:[^,[\]{}#\s]| )*[^,[\]{}#\s])?$/;
|
||||
const BLOCK_SCALAR_RE = /^[|>][+-]?$/;
|
||||
|
||||
/** Error codes thrown by {@link LibraryCardError}. */
|
||||
export type LibraryCardErrorCode =
|
||||
| 'INVALID_FS'
|
||||
| 'INVALID_ROOT'
|
||||
| 'INVALID_LIBRARY'
|
||||
| 'INVALID_CARD';
|
||||
|
||||
/** Typed validation and I/O error thrown by the library card filesystem adapter. */
|
||||
export class LibraryCardError extends RangeError {
|
||||
readonly code: LibraryCardErrorCode;
|
||||
|
||||
constructor(code: LibraryCardErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = 'LibraryCardError';
|
||||
this.code = code;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/** Directory entry metadata returned by {@link LibraryCardFs.listDir}. */
|
||||
export interface LibraryCardDirEntry {
|
||||
readonly name: string;
|
||||
readonly isFile: boolean;
|
||||
readonly isDirectory: boolean;
|
||||
}
|
||||
|
||||
/** Anchored read-only directory handle for symlink-safe traversal below a configured root. */
|
||||
export interface LibraryCardDirHandle {
|
||||
listDir(): Promise<readonly LibraryCardDirEntry[]>;
|
||||
openSubdir(name: string): Promise<LibraryCardDirHandle>;
|
||||
readTextFile(name: string): Promise<string>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */
|
||||
export interface LibraryCardFs {
|
||||
readTextFile(filePath: string): Promise<string>;
|
||||
listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]>;
|
||||
openDir(dirPath: string): Promise<LibraryCardDirHandle>;
|
||||
}
|
||||
|
||||
/** Factory options for {@link createLibraryCardReader}. */
|
||||
export interface LibraryCardReaderOptions {
|
||||
readonly root: string;
|
||||
readonly fs: LibraryCardFs;
|
||||
}
|
||||
|
||||
/** Library-card subset of {@link KnowledgePort}. */
|
||||
export type LibraryCardReader = Pick<KnowledgePort, 'listLibraryCards'>;
|
||||
|
||||
interface ParsedLibraryManifest {
|
||||
readonly id: string;
|
||||
readonly sections: readonly string[];
|
||||
}
|
||||
|
||||
type FrontMatterValue = string | readonly string[];
|
||||
|
||||
function compareCodeUnits(a: string, b: string): number {
|
||||
if (a < b) {
|
||||
return -1;
|
||||
}
|
||||
if (a > b) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function isEnoentError(err: unknown): boolean {
|
||||
return (
|
||||
typeof err === 'object' &&
|
||||
err !== null &&
|
||||
(err as { readonly code?: unknown }).code === 'ENOENT'
|
||||
);
|
||||
}
|
||||
|
||||
function invalidLibrary(reason: string): LibraryCardError {
|
||||
return new LibraryCardError('INVALID_LIBRARY', `Invalid library.yml: ${reason}`);
|
||||
}
|
||||
|
||||
function invalidCard(relPath: string, reason: string): LibraryCardError {
|
||||
return new LibraryCardError('INVALID_CARD', `Invalid card "${relPath}": ${reason}`);
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: LibraryCardReaderOptions): {
|
||||
readonly resolvedRoot: string;
|
||||
readonly fs: LibraryCardFs;
|
||||
} {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new LibraryCardError(
|
||||
'INVALID_ROOT',
|
||||
'Invalid options: expected an object with root and fs.'
|
||||
);
|
||||
}
|
||||
|
||||
const { root, fs } = options;
|
||||
if (typeof root !== 'string' || root.trim().length === 0 || root.includes('\0')) {
|
||||
throw new LibraryCardError(
|
||||
'INVALID_ROOT',
|
||||
'Invalid root: expected a non-empty filesystem path without null bytes.'
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof fs !== 'object' ||
|
||||
fs === null ||
|
||||
typeof fs.readTextFile !== 'function' ||
|
||||
typeof fs.listDir !== 'function' ||
|
||||
typeof fs.openDir !== 'function'
|
||||
) {
|
||||
throw new LibraryCardError(
|
||||
'INVALID_FS',
|
||||
'Invalid fs: expected a LibraryCardFs implementing readTextFile, listDir, and openDir.'
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
resolvedRoot: path.resolve(root),
|
||||
fs,
|
||||
};
|
||||
}
|
||||
|
||||
function parseLibraryScalar(rawValue: string): string {
|
||||
if (rawValue.length === 0 || rawValue.startsWith('#')) {
|
||||
throw invalidLibrary('"id" must not be empty.');
|
||||
}
|
||||
if (rawValue.startsWith("'")) {
|
||||
throw invalidLibrary('single-quoted "id" values are not supported.');
|
||||
}
|
||||
if (rawValue.startsWith('"')) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawValue);
|
||||
} catch {
|
||||
throw invalidLibrary('invalid double-quoted "id" value.');
|
||||
}
|
||||
if (typeof parsed !== 'string') {
|
||||
throw invalidLibrary('invalid double-quoted "id" value.');
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
if (rawValue.startsWith('[') || rawValue.startsWith('{') || BLOCK_SCALAR_RE.test(rawValue)) {
|
||||
throw invalidLibrary('"id" must be a scalar string.');
|
||||
}
|
||||
return rawValue;
|
||||
}
|
||||
|
||||
function parseLibraryManifest(content: string): ParsedLibraryManifest {
|
||||
const lines = content.split(/\r?\n/);
|
||||
|
||||
let libraryId: string | undefined;
|
||||
let sawSections = false;
|
||||
let sectionsIndent: number | null = null;
|
||||
let currentTopLevelKey: string | null = null;
|
||||
const seenSectionKeys = new Set<string>();
|
||||
const validSections: string[] = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i] as string;
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0 || trimmed.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let indent = 0;
|
||||
while (indent < line.length && line[indent] === ' ') {
|
||||
indent += 1;
|
||||
}
|
||||
if (line[indent] === '\t') {
|
||||
throw invalidLibrary('tab indentation is not supported.');
|
||||
}
|
||||
|
||||
if (indent === 0) {
|
||||
const colonIdx = line.indexOf(':');
|
||||
if (colonIdx <= 0) {
|
||||
throw invalidLibrary('malformed top-level entry.');
|
||||
}
|
||||
const key = line.slice(0, colonIdx).trim();
|
||||
const rawValue = line.slice(colonIdx + 1).trim();
|
||||
if (key.length === 0 || /\s/.test(key)) {
|
||||
throw invalidLibrary('invalid top-level key.');
|
||||
}
|
||||
|
||||
currentTopLevelKey = key;
|
||||
|
||||
if (key === 'id') {
|
||||
if (libraryId !== undefined) {
|
||||
throw invalidLibrary('duplicate "id" declaration.');
|
||||
}
|
||||
const parsedId = parseLibraryScalar(rawValue);
|
||||
if (!LIBRARY_ID_RE.test(parsedId)) {
|
||||
throw invalidLibrary('"id" must match ^[a-z0-9][a-z0-9_-]*$.');
|
||||
}
|
||||
libraryId = parsedId;
|
||||
} else if (key === 'sections') {
|
||||
if (sawSections) {
|
||||
throw invalidLibrary('duplicate "sections" declaration.');
|
||||
}
|
||||
if (rawValue.length > 0) {
|
||||
throw invalidLibrary('"sections" must be an indented map.');
|
||||
}
|
||||
sawSections = true;
|
||||
sectionsIndent = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentTopLevelKey === null) {
|
||||
throw invalidLibrary('indented entry before any top-level declaration.');
|
||||
}
|
||||
if (currentTopLevelKey === 'id') {
|
||||
throw invalidLibrary('"id" must be a single-line scalar.');
|
||||
}
|
||||
if (currentTopLevelKey !== 'sections') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sectionsIndent === null) {
|
||||
sectionsIndent = indent;
|
||||
} else if (indent !== sectionsIndent) {
|
||||
throw invalidLibrary('inconsistent indentation inside "sections" map.');
|
||||
}
|
||||
|
||||
const body = line.slice(indent);
|
||||
if (body === '-' || body.startsWith('- ') || body.startsWith('-\t')) {
|
||||
throw invalidLibrary('sequence entries are not supported inside "sections" map.');
|
||||
}
|
||||
const colonIdx = body.indexOf(':');
|
||||
if (colonIdx <= 0) {
|
||||
throw invalidLibrary('malformed entry inside "sections" map.');
|
||||
}
|
||||
const rawKey = body.slice(0, colonIdx);
|
||||
const sectionKey = rawKey.trim();
|
||||
const afterColon = body.slice(colonIdx + 1);
|
||||
if (
|
||||
rawKey !== sectionKey ||
|
||||
!PLAIN_YAML_KEY_RE.test(sectionKey) ||
|
||||
(afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t')
|
||||
) {
|
||||
throw invalidLibrary('malformed entry inside "sections" map.');
|
||||
}
|
||||
const sectionTitle = afterColon.trim();
|
||||
if (sectionTitle.length === 0 || sectionTitle.startsWith('#')) {
|
||||
throw invalidLibrary('empty key or title inside "sections" map.');
|
||||
}
|
||||
if (seenSectionKeys.has(sectionKey)) {
|
||||
throw invalidLibrary('duplicate key inside "sections" map.');
|
||||
}
|
||||
seenSectionKeys.add(sectionKey);
|
||||
|
||||
if (SAFE_IDENT_RE.test(sectionKey)) {
|
||||
validSections.push(sectionKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (libraryId === undefined) {
|
||||
throw invalidLibrary('missing "id" declaration.');
|
||||
}
|
||||
if (!sawSections || seenSectionKeys.size === 0) {
|
||||
throw invalidLibrary('missing or empty "sections" map.');
|
||||
}
|
||||
|
||||
return {
|
||||
id: libraryId,
|
||||
sections: validSections,
|
||||
};
|
||||
}
|
||||
|
||||
function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue {
|
||||
if (rawValue.length === 0 || rawValue.startsWith('#')) {
|
||||
throw invalidCard(relPath, 'empty or multiline front-matter value.');
|
||||
}
|
||||
if (BLOCK_SCALAR_RE.test(rawValue)) {
|
||||
throw invalidCard(relPath, 'multiline front-matter values are not supported.');
|
||||
}
|
||||
if (rawValue.startsWith("'")) {
|
||||
throw invalidCard(relPath, 'single-quoted front-matter values are not supported.');
|
||||
}
|
||||
if (rawValue.startsWith('{')) {
|
||||
throw invalidCard(relPath, 'object front-matter values are not supported.');
|
||||
}
|
||||
|
||||
if (rawValue.startsWith('"')) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawValue);
|
||||
} catch {
|
||||
throw invalidCard(relPath, 'invalid double-quoted front-matter string.');
|
||||
}
|
||||
if (typeof parsed !== 'string') {
|
||||
throw invalidCard(relPath, 'invalid double-quoted front-matter string.');
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
if (rawValue.startsWith('[')) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawValue);
|
||||
} catch {
|
||||
throw invalidCard(relPath, 'invalid front-matter array.');
|
||||
}
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw invalidCard(relPath, 'invalid front-matter array.');
|
||||
}
|
||||
const items: string[] = [];
|
||||
for (let i = 0; i < parsed.length; i += 1) {
|
||||
const entry: unknown = parsed[i];
|
||||
if (typeof entry !== 'string') {
|
||||
throw invalidCard(relPath, 'front-matter array entries must be strings.');
|
||||
}
|
||||
items.push(entry);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
return rawValue;
|
||||
}
|
||||
|
||||
function parseCardDocument(
|
||||
content: string,
|
||||
libraryId: string,
|
||||
sectionId: string,
|
||||
slug: string
|
||||
): LibraryCardRecord {
|
||||
const relPath = `cards/${sectionId}/${slug}.md`;
|
||||
const lines = content.split(/\r?\n/);
|
||||
|
||||
if (lines[0] !== '---') {
|
||||
throw invalidCard(relPath, 'missing opening front-matter delimiter.');
|
||||
}
|
||||
|
||||
let closingIndex = -1;
|
||||
for (let i = 1; i < lines.length; i += 1) {
|
||||
if (lines[i] === '---') {
|
||||
closingIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (closingIndex === -1) {
|
||||
throw invalidCard(relPath, 'missing closing front-matter delimiter.');
|
||||
}
|
||||
|
||||
const fields = new Map<string, FrontMatterValue>();
|
||||
for (let i = 1; i < closingIndex; i += 1) {
|
||||
const line = lines[i] as string;
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0 || trimmed.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
if (line[0] === ' ' || line[0] === '\t') {
|
||||
throw invalidCard(relPath, 'multiline or indented front-matter values are not supported.');
|
||||
}
|
||||
|
||||
const colonIdx = line.indexOf(':');
|
||||
if (colonIdx <= 0) {
|
||||
throw invalidCard(relPath, 'malformed front-matter entry.');
|
||||
}
|
||||
const key = line.slice(0, colonIdx).trim();
|
||||
if (key.length === 0 || /\s/.test(key)) {
|
||||
throw invalidCard(relPath, 'invalid front-matter key.');
|
||||
}
|
||||
if (fields.has(key)) {
|
||||
throw invalidCard(relPath, 'duplicate front-matter key.');
|
||||
}
|
||||
|
||||
const rawValue = line.slice(colonIdx + 1).trim();
|
||||
fields.set(key, parseFrontMatterValue(rawValue, relPath));
|
||||
}
|
||||
|
||||
const rawTitle = fields.get('title');
|
||||
if (typeof rawTitle !== 'string' || rawTitle.trim().length === 0) {
|
||||
throw invalidCard(relPath, 'missing or empty "title".');
|
||||
}
|
||||
|
||||
const rawSummary = fields.get('summary');
|
||||
if (typeof rawSummary !== 'string' || rawSummary.trim().length === 0) {
|
||||
throw invalidCard(relPath, 'missing or empty "summary".');
|
||||
}
|
||||
|
||||
const rawMatches = fields.get('matches');
|
||||
if (rawMatches !== undefined && !Array.isArray(rawMatches)) {
|
||||
throw invalidCard(relPath, '"matches" must be an array of strings.');
|
||||
}
|
||||
|
||||
const tags: string[] = [];
|
||||
const seenTags = new Set<string>();
|
||||
const addTag = (raw: string): void => {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized.length > 0 && !seenTags.has(normalized)) {
|
||||
seenTags.add(normalized);
|
||||
tags.push(normalized);
|
||||
}
|
||||
};
|
||||
|
||||
addTag(sectionId);
|
||||
if (rawMatches !== undefined) {
|
||||
for (let i = 0; i < rawMatches.length; i += 1) {
|
||||
addTag(rawMatches[i] as string);
|
||||
}
|
||||
}
|
||||
|
||||
const body = lines
|
||||
.slice(closingIndex + 1)
|
||||
.join('\n')
|
||||
.trim();
|
||||
|
||||
return Object.freeze({
|
||||
id: `${libraryId}:${sectionId}/${slug}`,
|
||||
title: rawTitle,
|
||||
tags: Object.freeze(tags),
|
||||
summary: rawSummary,
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
function parseExactCardId(
|
||||
id: string,
|
||||
libraryId: string,
|
||||
declaredSections: ReadonlySet<string>
|
||||
): { readonly sectionId: string; readonly slug: string } | null {
|
||||
const prefix = `${libraryId}:`;
|
||||
if (!id.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
const rest = id.slice(prefix.length);
|
||||
const slashIdx = rest.indexOf('/');
|
||||
if (slashIdx <= 0 || rest.indexOf('/', slashIdx + 1) !== -1) {
|
||||
return null;
|
||||
}
|
||||
const sectionId = rest.slice(0, slashIdx);
|
||||
const slug = rest.slice(slashIdx + 1);
|
||||
if (!SAFE_IDENT_RE.test(sectionId) || !SAFE_IDENT_RE.test(slug)) {
|
||||
return null;
|
||||
}
|
||||
if (!declaredSections.has(sectionId)) {
|
||||
return null;
|
||||
}
|
||||
return { sectionId, slug };
|
||||
}
|
||||
|
||||
function assertSafeChildName(name: string): void {
|
||||
if (
|
||||
name.length === 0 ||
|
||||
name === '.' ||
|
||||
name === '..' ||
|
||||
name.includes('/') ||
|
||||
name.includes('\\') ||
|
||||
name.includes('\0')
|
||||
) {
|
||||
throw new Error('Invalid directory child entry name.');
|
||||
}
|
||||
}
|
||||
|
||||
function isValidDirHandle(value: unknown): value is LibraryCardDirHandle {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
typeof (value as { readonly listDir?: unknown }).listDir === 'function' &&
|
||||
typeof (value as { readonly openSubdir?: unknown }).openSubdir === 'function' &&
|
||||
typeof (value as { readonly readTextFile?: unknown }).readTextFile === 'function' &&
|
||||
typeof (value as { readonly close?: unknown }).close === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
async function safeOpenRootDir(
|
||||
fs: LibraryCardFs,
|
||||
resolvedRoot: string
|
||||
): Promise<LibraryCardDirHandle> {
|
||||
let handle: unknown;
|
||||
try {
|
||||
handle = await fs.openDir(resolvedRoot);
|
||||
} catch {
|
||||
throw new LibraryCardError(
|
||||
'INVALID_LIBRARY',
|
||||
'Invalid library.yml: failed to open library root directory.'
|
||||
);
|
||||
}
|
||||
if (!isValidDirHandle(handle)) {
|
||||
throw new LibraryCardError(
|
||||
'INVALID_LIBRARY',
|
||||
'Invalid library.yml: failed to open library root directory.'
|
||||
);
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
async function safeOpenSubdir(
|
||||
parent: LibraryCardDirHandle,
|
||||
name: string,
|
||||
errorMessage: string,
|
||||
allowMissing: boolean
|
||||
): Promise<LibraryCardDirHandle | null> {
|
||||
let handle: unknown;
|
||||
try {
|
||||
handle = await parent.openSubdir(name);
|
||||
} catch (err) {
|
||||
if (allowMissing && isEnoentError(err)) {
|
||||
return null;
|
||||
}
|
||||
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
|
||||
}
|
||||
if (!isValidDirHandle(handle)) {
|
||||
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
async function safeReadTextFileFromDir(
|
||||
dir: LibraryCardDirHandle,
|
||||
name: string,
|
||||
errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD',
|
||||
errorMessage: string
|
||||
): Promise<string> {
|
||||
let content: unknown;
|
||||
try {
|
||||
content = await dir.readTextFile(name);
|
||||
} catch {
|
||||
throw new LibraryCardError(errorCode, errorMessage);
|
||||
}
|
||||
if (typeof content !== 'string') {
|
||||
throw new LibraryCardError(errorCode, errorMessage);
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
async function safeListDirHandle(
|
||||
dir: LibraryCardDirHandle,
|
||||
errorMessage: string,
|
||||
allowMissing: boolean
|
||||
): Promise<readonly LibraryCardDirEntry[]> {
|
||||
let rawEntries: unknown;
|
||||
try {
|
||||
rawEntries = await dir.listDir();
|
||||
} catch (err) {
|
||||
if (allowMissing && isEnoentError(err)) {
|
||||
return [];
|
||||
}
|
||||
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
|
||||
}
|
||||
|
||||
if (!Array.isArray(rawEntries)) {
|
||||
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
|
||||
}
|
||||
|
||||
const entries: LibraryCardDirEntry[] = [];
|
||||
for (let i = 0; i < rawEntries.length; i += 1) {
|
||||
const entry: unknown = rawEntries[i];
|
||||
if (
|
||||
typeof entry !== 'object' ||
|
||||
entry === null ||
|
||||
typeof (entry as { readonly name?: unknown }).name !== 'string' ||
|
||||
typeof (entry as { readonly isFile?: unknown }).isFile !== 'boolean' ||
|
||||
typeof (entry as { readonly isDirectory?: unknown }).isDirectory !== 'boolean'
|
||||
) {
|
||||
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
|
||||
}
|
||||
entries.push(entry as LibraryCardDirEntry);
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
interface AnchoredOpenFlags {
|
||||
readonly dirOpenFlags: number;
|
||||
readonly subdirOpenFlags: number;
|
||||
readonly fileOpenFlags: number;
|
||||
}
|
||||
|
||||
function getAnchoredOpenFlags(): AnchoredOpenFlags {
|
||||
if (
|
||||
process.platform !== 'linux' ||
|
||||
typeof fsConstants.O_NOFOLLOW !== 'number' ||
|
||||
typeof fsConstants.O_DIRECTORY !== 'number'
|
||||
) {
|
||||
throw new Error('Anchored no-follow directory operations are not supported on this platform.');
|
||||
}
|
||||
return {
|
||||
dirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY,
|
||||
subdirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,
|
||||
fileOpenFlags: fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW,
|
||||
};
|
||||
}
|
||||
|
||||
function createAnchoredNodeDirHandle(
|
||||
handle: FileHandle,
|
||||
flags: AnchoredOpenFlags
|
||||
): LibraryCardDirHandle {
|
||||
let closed = false;
|
||||
|
||||
const getFdBase = (): string => {
|
||||
if (closed) {
|
||||
throw new Error('Directory handle is closed.');
|
||||
}
|
||||
return `/proc/self/fd/${handle.fd}`;
|
||||
};
|
||||
|
||||
return {
|
||||
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
|
||||
const dirents = await readdir(getFdBase(), { withFileTypes: true });
|
||||
const entries: LibraryCardDirEntry[] = [];
|
||||
for (let i = 0; i < dirents.length; i += 1) {
|
||||
const dirent = dirents[i];
|
||||
if (dirent !== undefined) {
|
||||
entries.push({
|
||||
name: dirent.name,
|
||||
isFile: dirent.isFile(),
|
||||
isDirectory: dirent.isDirectory(),
|
||||
});
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
},
|
||||
|
||||
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
|
||||
assertSafeChildName(name);
|
||||
const childHandle = await open(`${getFdBase()}/${name}`, flags.subdirOpenFlags);
|
||||
try {
|
||||
const stats = await childHandle.stat();
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error('Target path is not a directory.');
|
||||
}
|
||||
} catch (err) {
|
||||
await childHandle.close();
|
||||
throw err;
|
||||
}
|
||||
return createAnchoredNodeDirHandle(childHandle, flags);
|
||||
},
|
||||
|
||||
async readTextFile(name: string): Promise<string> {
|
||||
assertSafeChildName(name);
|
||||
const fileHandle = await open(`${getFdBase()}/${name}`, flags.fileOpenFlags);
|
||||
try {
|
||||
const stats = await fileHandle.stat();
|
||||
if (!stats.isFile()) {
|
||||
throw new Error('Target path is not a regular file.');
|
||||
}
|
||||
return await fileHandle.readFile({ encoding: 'utf8' });
|
||||
} finally {
|
||||
await fileHandle.close();
|
||||
}
|
||||
},
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
await handle.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`.
|
||||
*
|
||||
* Anchors directory listings and file reads to opened directory file descriptors
|
||||
* via `/proc/self/fd/<fd>`, enforces `O_NOFOLLOW` on every component below the
|
||||
* configured root, verifies regular-file/directory types via `fstat`, and fails
|
||||
* closed on platforms that cannot enforce this boundary.
|
||||
*/
|
||||
export function createNodeLibraryCardFs(): LibraryCardFs {
|
||||
return {
|
||||
async readTextFile(filePath: string): Promise<string> {
|
||||
const flags = getAnchoredOpenFlags();
|
||||
const handle = await open(filePath, flags.fileOpenFlags);
|
||||
try {
|
||||
const stats = await handle.stat();
|
||||
if (!stats.isFile()) {
|
||||
throw new Error('Target path is not a regular file.');
|
||||
}
|
||||
return await handle.readFile({ encoding: 'utf8' });
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
},
|
||||
|
||||
async listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]> {
|
||||
const flags = getAnchoredOpenFlags();
|
||||
const handle = await open(dirPath, flags.subdirOpenFlags);
|
||||
try {
|
||||
const stats = await handle.stat();
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error('Target path is not a directory.');
|
||||
}
|
||||
const anchored = createAnchoredNodeDirHandle(handle, flags);
|
||||
return await anchored.listDir();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
},
|
||||
|
||||
async openDir(dirPath: string): Promise<LibraryCardDirHandle> {
|
||||
const flags = getAnchoredOpenFlags();
|
||||
const handle = await open(dirPath, flags.dirOpenFlags);
|
||||
try {
|
||||
const stats = await handle.stat();
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error('Target path is not a directory.');
|
||||
}
|
||||
const procStats = await stat(`/proc/self/fd/${handle.fd}`);
|
||||
if (!procStats.isDirectory()) {
|
||||
throw new Error('Anchored directory descriptor is not accessible.');
|
||||
}
|
||||
} catch (err) {
|
||||
await handle.close();
|
||||
throw err;
|
||||
}
|
||||
return createAnchoredNodeDirHandle(handle, flags);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only filesystem reader implementing
|
||||
* {@link KnowledgePort.listLibraryCards} over `<root>/library.yml` and
|
||||
* `<root>/cards/<sectionId>/<slug>.md`.
|
||||
*
|
||||
* Reads fresh from the injected {@link LibraryCardFs} on every call, narrows
|
||||
* only by exact case-sensitive `q.id` (leaving `q.query`, `q.tags`, ranking,
|
||||
* truncation, and `limit` to `createReadKnowledgeTool`), and returns all
|
||||
* eligible cards regardless of `verified` status.
|
||||
*/
|
||||
export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader {
|
||||
const { resolvedRoot, fs } = validateFactoryOptions(options);
|
||||
|
||||
return {
|
||||
async listLibraryCards(q: LibraryCardQuery): Promise<readonly LibraryCardRecord[]> {
|
||||
const rootDir = await safeOpenRootDir(fs, resolvedRoot);
|
||||
try {
|
||||
const manifestText = await safeReadTextFileFromDir(
|
||||
rootDir,
|
||||
'library.yml',
|
||||
'INVALID_LIBRARY',
|
||||
'Invalid library.yml: failed to read manifest.'
|
||||
);
|
||||
const manifest = parseLibraryManifest(manifestText);
|
||||
const declaredSections = new Set(manifest.sections);
|
||||
|
||||
let target: { readonly sectionId: string; readonly slug: string } | null = null;
|
||||
if (q.id !== undefined) {
|
||||
target = parseExactCardId(q.id, manifest.id, declaredSections);
|
||||
if (target === null) {
|
||||
return Object.freeze([]);
|
||||
}
|
||||
}
|
||||
|
||||
const rootEntries = await safeListDirHandle(
|
||||
rootDir,
|
||||
'Invalid library.yml: failed to list library root directory.',
|
||||
false
|
||||
);
|
||||
const hasCardsDir = rootEntries.some(
|
||||
entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile
|
||||
);
|
||||
if (!hasCardsDir) {
|
||||
return Object.freeze([]);
|
||||
}
|
||||
|
||||
const cardsDir = await safeOpenSubdir(
|
||||
rootDir,
|
||||
'cards',
|
||||
'Invalid library.yml: failed to open library cards directory.',
|
||||
true
|
||||
);
|
||||
if (cardsDir === null) {
|
||||
return Object.freeze([]);
|
||||
}
|
||||
|
||||
try {
|
||||
const cardDirEntries = await safeListDirHandle(
|
||||
cardsDir,
|
||||
'Invalid library.yml: failed to list library cards directory.',
|
||||
true
|
||||
);
|
||||
const presentSectionDirs = new Set<string>();
|
||||
for (let i = 0; i < cardDirEntries.length; i += 1) {
|
||||
const entry = cardDirEntries[i] as LibraryCardDirEntry;
|
||||
if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) {
|
||||
presentSectionDirs.add(entry.name);
|
||||
}
|
||||
}
|
||||
|
||||
const sectionsToScan = target !== null ? [target.sectionId] : manifest.sections;
|
||||
const cards: LibraryCardRecord[] = [];
|
||||
const seenIds = new Set<string>();
|
||||
|
||||
for (let s = 0; s < sectionsToScan.length; s += 1) {
|
||||
const sectionId = sectionsToScan[s] as string;
|
||||
if (!presentSectionDirs.has(sectionId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sectionDir = await safeOpenSubdir(
|
||||
cardsDir,
|
||||
sectionId,
|
||||
`Invalid library.yml: failed to open section directory "cards/${sectionId}".`,
|
||||
true
|
||||
);
|
||||
if (sectionDir === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const sectionEntries = await safeListDirHandle(
|
||||
sectionDir,
|
||||
`Invalid library.yml: failed to list section directory "cards/${sectionId}".`,
|
||||
true
|
||||
);
|
||||
|
||||
const slugs: string[] = [];
|
||||
const seenSectionSlugs = new Set<string>();
|
||||
for (let i = 0; i < sectionEntries.length; i += 1) {
|
||||
const entry = sectionEntries[i] as LibraryCardDirEntry;
|
||||
if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) {
|
||||
continue;
|
||||
}
|
||||
const slug = entry.name.slice(0, -3);
|
||||
if (!SAFE_IDENT_RE.test(slug)) {
|
||||
continue;
|
||||
}
|
||||
if (target !== null && slug !== target.slug) {
|
||||
continue;
|
||||
}
|
||||
if (seenSectionSlugs.has(slug)) {
|
||||
throw invalidCard(`cards/${sectionId}/${slug}.md`, 'duplicate card id.');
|
||||
}
|
||||
seenSectionSlugs.add(slug);
|
||||
slugs.push(slug);
|
||||
}
|
||||
|
||||
slugs.sort(compareCodeUnits);
|
||||
|
||||
for (let i = 0; i < slugs.length; i += 1) {
|
||||
const slug = slugs[i] as string;
|
||||
const relPath = `cards/${sectionId}/${slug}.md`;
|
||||
const canonicalId = `${manifest.id}:${sectionId}/${slug}`;
|
||||
if (seenIds.has(canonicalId)) {
|
||||
throw invalidCard(relPath, 'duplicate card id.');
|
||||
}
|
||||
seenIds.add(canonicalId);
|
||||
|
||||
const cardText = await safeReadTextFileFromDir(
|
||||
sectionDir,
|
||||
`${slug}.md`,
|
||||
'INVALID_CARD',
|
||||
`Invalid card "${relPath}": failed to read card file.`
|
||||
);
|
||||
cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug));
|
||||
}
|
||||
} finally {
|
||||
await sectionDir.close();
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze(cards);
|
||||
} finally {
|
||||
await cardsDir.close();
|
||||
}
|
||||
} finally {
|
||||
await rootDir.close();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -6,17 +6,20 @@
|
|||
* injected via {@link TrialRefExecutor}.
|
||||
*/
|
||||
|
||||
import { MarketDataStoreValidationError } from '../../market-data-store';
|
||||
import type { TrialRefLookupPort } from '../tools/file-finding';
|
||||
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
|
||||
|
||||
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||
const CANONICAL_TRIAL_ID_RE = /^[1-9][0-9]{0,18}$/;
|
||||
const MAX_PG_BIGINT_STR = '9223372036854775807';
|
||||
const PG_ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const FOUR_DIGIT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const CANONICAL_POSITIVE_BIGINT_RE = /^[1-9][0-9]{0,18}$/;
|
||||
const MAX_SIGNED_BIGINT_STR = '9223372036854775807';
|
||||
|
||||
/** Error codes thrown by {@link PostgresTrialRefError}. */
|
||||
export type PostgresTrialRefErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW';
|
||||
export type PostgresTrialRefErrorCode =
|
||||
| 'INVALID_EXECUTOR'
|
||||
| 'INVALID_SCHEMA'
|
||||
| 'INVALID_VAULT_CUTOFF'
|
||||
| 'INVALID_ROW';
|
||||
|
||||
/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */
|
||||
export class PostgresTrialRefError extends RangeError {
|
||||
|
|
@ -41,37 +44,40 @@ export interface TrialRefExecutor {
|
|||
): Promise<{ readonly rows: readonly Row[] }>;
|
||||
}
|
||||
|
||||
/** Factory options for {@link createPostgresTrialRefPort}. */
|
||||
export interface PostgresTrialRefPortOptions {
|
||||
/** Factory options for {@link createPostgresTrialRefLookupPort} / {@link createPostgresTrialRefPort}. */
|
||||
export interface PostgresTrialRefLookupPortOptions {
|
||||
readonly executor: TrialRefExecutor;
|
||||
/** Server-injected Vault cutoff epoch-ms timestamp; trials with `sample_end < utcDate(vaultCutoffTs)` are visible. */
|
||||
/** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */
|
||||
readonly vaultCutoffTs: number;
|
||||
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
|
||||
readonly schema?: string;
|
||||
}
|
||||
|
||||
/** Alias for {@link PostgresTrialRefLookupPortOptions}. */
|
||||
export type PostgresTrialRefPortOptions = PostgresTrialRefLookupPortOptions;
|
||||
|
||||
interface RawTrialRefVisibilityRow {
|
||||
readonly visible: unknown;
|
||||
readonly visible?: unknown;
|
||||
}
|
||||
|
||||
function isCanonicalPositiveBigInt(value: unknown): value is string {
|
||||
if (typeof value !== 'string' || !CANONICAL_TRIAL_ID_RE.test(value)) {
|
||||
if (typeof value !== 'string' || !CANONICAL_POSITIVE_BIGINT_RE.test(value)) {
|
||||
return false;
|
||||
}
|
||||
if (value.length === MAX_PG_BIGINT_STR.length && value > MAX_PG_BIGINT_STR) {
|
||||
if (value.length === MAX_SIGNED_BIGINT_STR.length && value > MAX_SIGNED_BIGINT_STR) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function buildTrialRefVisibilitySql(schemaPrefix: string): string {
|
||||
function buildTrialVisibilitySql(schemaPrefix: string): string {
|
||||
return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`;
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: PostgresTrialRefPortOptions): {
|
||||
function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): {
|
||||
readonly executor: TrialRefExecutor;
|
||||
readonly cutoffDate: string;
|
||||
readonly schemaPrefix: string;
|
||||
readonly vaultCutoffDate: string;
|
||||
} {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new PostgresTrialRefError(
|
||||
|
|
@ -99,28 +105,39 @@ function validateFactoryOptions(options: PostgresTrialRefPortOptions): {
|
|||
schemaPrefix = `"${schema}".`;
|
||||
}
|
||||
|
||||
const cutoffTs = validateVaultCutoffTs(vaultCutoffTs);
|
||||
const vaultCutoffDate = utcDateOf(cutoffTs);
|
||||
if (!PG_ISO_DATE_RE.test(vaultCutoffDate) || vaultCutoffDate.startsWith('0000-')) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid \`vaultCutoffTs\`: ${String(vaultCutoffTs)} does not produce a PostgreSQL YYYY-MM-DD date.`,
|
||||
'vaultCutoffTs'
|
||||
let validatedCutoffTs: number;
|
||||
try {
|
||||
validatedCutoffTs = validateVaultCutoffTs(vaultCutoffTs);
|
||||
} catch {
|
||||
throw new PostgresTrialRefError(
|
||||
'INVALID_VAULT_CUTOFF',
|
||||
'Invalid vaultCutoffTs: expected a finite safe-integer epoch-ms timestamp within ECMAScript Date bounds.'
|
||||
);
|
||||
}
|
||||
|
||||
return { executor, schemaPrefix, vaultCutoffDate };
|
||||
const cutoffDate = utcDateOf(validatedCutoffTs);
|
||||
if (!FOUR_DIGIT_DATE_RE.test(cutoffDate) || cutoffDate.startsWith('0000-')) {
|
||||
throw new PostgresTrialRefError(
|
||||
'INVALID_VAULT_CUTOFF',
|
||||
'Invalid vaultCutoffTs: resolved UTC date must be a four-digit PostgreSQL calendar date (0001-01-01 through 9999-12-31).'
|
||||
);
|
||||
}
|
||||
|
||||
return { executor, cutoffDate, schemaPrefix };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`
|
||||
* (`36-trial-ledger.sql`), enforcing `sample_end < vaultCutoffDate` so unknown and
|
||||
* Vault-only trial references are indistinguishable.
|
||||
* (`36-trial-ledger.sql`).
|
||||
*
|
||||
* Only trials with `sample_end < cutoffDate` (exclusive UTC Vault cutoff date) are
|
||||
* research-visible. Unknown, malformed, and Vault-only references all return `false`.
|
||||
*/
|
||||
export function createPostgresTrialRefPort(
|
||||
options: PostgresTrialRefPortOptions
|
||||
export function createPostgresTrialRefLookupPort(
|
||||
options: PostgresTrialRefLookupPortOptions
|
||||
): TrialRefLookupPort {
|
||||
const { executor, schemaPrefix, vaultCutoffDate } = validateFactoryOptions(options);
|
||||
const sql = buildTrialRefVisibilitySql(schemaPrefix);
|
||||
const { executor, cutoffDate, schemaPrefix } = validateFactoryOptions(options);
|
||||
const sql = buildTrialVisibilitySql(schemaPrefix);
|
||||
|
||||
return {
|
||||
async hasResearchVisibleTrial(trialRef: string): Promise<boolean> {
|
||||
|
|
@ -128,11 +145,7 @@ export function createPostgresTrialRefPort(
|
|||
return false;
|
||||
}
|
||||
|
||||
const result = await executor.query<RawTrialRefVisibilityRow>(sql, [
|
||||
trialRef,
|
||||
vaultCutoffDate,
|
||||
]);
|
||||
|
||||
const result = await executor.query<RawTrialRefVisibilityRow>(sql, [trialRef, cutoffDate]);
|
||||
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
|
||||
throw new PostgresTrialRefError(
|
||||
'INVALID_ROW',
|
||||
|
|
@ -163,3 +176,6 @@ export function createPostgresTrialRefPort(
|
|||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Alias for {@link createPostgresTrialRefLookupPort}. */
|
||||
export const createPostgresTrialRefPort = createPostgresTrialRefLookupPort;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
export * from './adapters/library-cards';
|
||||
export * from './adapters/postgres-findings';
|
||||
export * from './adapters/postgres-symbol-search';
|
||||
export * from './adapters/postgres-trial-ref';
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue