Skill: dae-xiaoe/claw-code (version 1.0.0)

--- name: claw-code description: AI Agent Harness Runtime — TypeScript port of Claude Code's harness system. Use when: (1) user asks about claw-code, agent harness, or Claude Code internals; (2) user wants to run claw-code commands or query tool/command registries; (3) routing prompts to commands or tools; (4) bootstrapping agent sessions; (5) parity auditing against original TypeScript archive. Triggers on phrases like "claw-code", "harness runtime", "Claude Code port", "agent harness", "run turn loop", "route prompt". --- # claw-code — AI Agent Harness Runtime TypeScript port of Claude Code's harness system, compiled and ready to run. ## Quick Start ```bash cd C:\Users\dae\.openclaw\workspace\skills\claw-code\scripts node dist/main.js <command> [options] ``` Or build from source: ```bash cd C:\Users\dae\.openclaw\workspace\skills\claw-code\scripts npm install npm run build ``` ## Available Commands ### Info & Audit ``` node dist/main.js summary # Render workspace summary node dist/main.js manifest # Print workspace manifest node dist/main.js parity-audit # Compare against archive node dist/main.js setup-report # Startup/prefetch report node dist/main.js command-graph # Show command graph node dist/main.js tool-pool # Show tool pool node dist/main.js bootstrap-graph # Show bootstrap stages ``` ### Query Registries ``` node dist/main.js subsystems --limit 16 # List Python modules node dist/main.js commands --limit 20 # List mirrored commands node dist/main.js commands --query <keyword> # Search commands node dist/main.js tools --limit 20 # List mirrored tools node dist/main.js tools --query <keyword> # Search tools node dist/main.js tools --simple-mode # Core tools only node dist/main.js tools --no-mcp # Exclude MCP tools node dist/main.js show-command <name> # Show one command node dist/main.js show-tool <name> # Show one tool ``` ### Runtime Execution ``` node dist/main.js route "<prompt>" --limit 5 # Route prompt to commands/tools node dist/main.js bootstrap "<prompt>" --limit 5 # Bootstrap a session node dist/main.js turn-loop "<prompt>" --max-turns 3 # Run turn loop node dist/main.js flush-transcript "<prompt>" # Persist session node dist/main.js load-session <session_id> # Load saved session ``` ### Remote Modes ``` node dist/main.js remote-mode <target> node dist/main.js ssh-mode <target> node dist/main.js teleport-mode <target> node dist/main.js direct-connect-mode <target> node dist/main.js deep-link-mode <target> ``` ### Execution ``` node dist/main.js exec-command <name> "<prompt>" # Execute mirrored command node dist/main.js exec-tool <name> <payload> # Execute mirrored tool ``` ## Project Structure ``` claw-code/ ├── SKILL.md # This file └── scripts/ ├── dist/ # Compiled JavaScript (ready to run) │ └── main.js # CLI entry point ├── src/ # TypeScript source │ └── reference_data/ # Snapshot data ├── package.json └── tsconfig.json ``` ## Architecture - **Runtime Core** (`runtime.ts`) — PortRuntime class: route_prompt, bootstrap_session, run_turn_loop - **Tool/Command Registries** — loaded from `reference_data/*.json` snapshots - **Session Management** — session_store.ts, history.ts - **Query Engine** — query_engine.ts with streaming support - **Graphs** — bootstrap_graph.ts, command_graph.ts - **Remote Modes** — remote_runtime.ts, direct_modes.ts

path: scripts/dist/bootstrap_graph.d.ts
content: /**
 * A read-only ordered sequence of bootstrap stages.
 * Each stage is a human-readable label describing a phase in the startup pipeline.
 */
export declare class BootstrapGraph {
    readonly stages: readonly string[];
    constructor(stages: readonly string[]);
    /**
     * Render the bootstrap graph as a Markdown document.
     */
    asMarkdown(): string;
}
/**
 * Build the canonical bootstrap graph for claw-code.
 *
 * The stages are ordered to reflect the actual startup sequence:
 *  1. top-level prefetch side effects
 *  2. warning handler and environment guards
 *  3. CLI parser and pre-action trust gate
 *  4. setup() + commands/agents parallel load
 *  5. deferred init after trust
 *  6. mode routing: local / remote / ssh / teleport / direct-connect / deep-link
 *  7. query engine submit loop
 */
export declare function buildBootstrapGraph(): BootstrapGraph;


path: scripts/dist/bootstrap_graph.js
content: // Bootstrap Graph — models the ordered stages of the claw-code bootstrap / runtime lifecycle.
/**
 * A read-only ordered sequence of bootstrap stages.
 * Each stage is a human-readable label describing a phase in the startup pipeline.
 */
export class BootstrapGraph {
    constructor(stages) {
        this.stages = stages;
    }
    /**
     * Render the bootstrap graph as a Markdown document.
     */
    asMarkdown() {
        const lines = ['# Bootstrap Graph', ''];
        for (const stage of this.stages) {
            lines.push(`- ${stage}`);
        }
        return lines.join('\n');
    }
}
/**
 * Build the canonical bootstrap graph for claw-code.
 *
 * The stages are ordered to reflect the actual startup sequence:
 *  1. top-level prefetch side effects
 *  2. warning handler and environment guards
 *  3. CLI parser and pre-action trust gate
 *  4. setup() + commands/agents parallel load
 *  5. deferred init after trust
 *  6. mode routing: local / remote / ssh / teleport / direct-connect / deep-link
 *  7. query engine submit loop
 */
export function buildBootstrapGraph() {
    return new BootstrapGraph([
        'top-level prefetch side effects',
        'warning handler and environment guards',
        'CLI parser and pre-action trust gate',
        'setup() + commands/agents parallel load',
        'deferred init after trust',
        'mode routing: local / remote / ssh / teleport / direct-connect / deep-link',
        'query engine submit loop',
    ]);
}


path: scripts/dist/commands.d.ts
content: import { PortingBacklog, PortingModule } from './models.js';
export interface CommandExecution {
    readonly name: string;
    readonly source_hint: string;
    readonly prompt: string;
    readonly handled: boolean;
    readonly message: string;
}
export declare const PORTED_COMMANDS: readonly PortingModule[];
export declare function builtInCommandNames(): ReadonlySet<string>;
export declare function buildCommandBacklog(): PortingBacklog;
export declare function commandNames(): string[];
export declare function getCommand(name: string): PortingModule | undefined;
export declare function getCommands(_cwd?: string, includePluginCommands?: boolean, includeSkillCommands?: boolean): readonly PortingModule[];
export declare function findCommands(query: string, limit?: number): readonly PortingModule[];
export declare function executeCommand(name: string, prompt?: string): CommandExecution;
export declare function renderCommandIndex(limit?: number, query?: string): string;


path: scripts/dist/commands.js
content: // Commands – mirrored command entries loaded from snapshot
// Mirrored from Python src/commands.py
import { PortingBacklog, PortingModule } from './models.js';
// Module-level cached snapshot (replaces Python's @lru_cache)
const _PORTED_COMMANDS = (() => {
    const entries = [
        { name: 'help', source_hint: 'commands/help/help.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/help/help.tsx' },
        { name: 'init', source_hint: 'commands/init.ts', responsibility: 'Command module mirrored from archived TypeScript path commands/init.ts' },
        { name: 'commit', source_hint: 'commands/commit.ts', responsibility: 'Command module mirrored from archived TypeScript path commands/commit.ts' },
        { name: 'branch', source_hint: 'commands/branch/branch.ts', responsibility: 'Command module mirrored from archived TypeScript path commands/branch/branch.ts' },
        { name: 'diff', source_hint: 'commands/diff/diff.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/diff/diff.tsx' },
        { name: 'status', source_hint: 'commands/status/status.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/status/status.tsx' },
        { name: 'session', source_hint: 'commands/session/session.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/session/session.tsx' },
        { name: 'resume', source_hint: 'commands/resume/resume.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/resume/resume.tsx' },
        { name: 'model', source_hint: 'commands/model/model.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/model/model.tsx' },
        { name: 'config', source_hint: 'commands/config/config.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/config/config.tsx' },
        { name: 'plan', source_hint: 'commands/plan/plan.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/plan/plan.tsx' },
        { name: 'compact', source_hint: 'commands/compact/compact.ts', responsibility: 'Command module mirrored from archived TypeScript path commands/compact/compact.ts' },
        { name: 'cost', source_hint: 'commands/cost/cost.ts', responsibility: 'Command module mirrored from archived TypeScript path commands/cost/cost.ts' },
        { name: 'usage', source_hint: 'commands/usage/usage.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/usage/usage.tsx' },
        { name: 'skills', source_hint: 'commands/skills/skills.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/skills/skills.tsx' },
        { name: 'memory', source_hint: 'commands/memory/memory.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/memory/memory.tsx' },
        { name: 'doctor', source_hint: 'commands/doctor/doctor.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/doctor/doctor.tsx' },
        { name: 'exit', source_hint: 'commands/exit/exit.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/exit/exit.tsx' },
        { name: 'clear', source_hint: 'commands/clear/clear.ts', responsibility: 'Command module mirrored from archived TypeScript path commands/clear/clear.ts' },
        { name: 'theme', source_hint: 'commands/theme/theme.tsx', responsibility: 'Command module mirrored from archived TypeScript path commands/theme/theme.tsx' },
    ];
    return entries.map((e) => new PortingModule({
        name: e.name,
        responsibility: e.responsibility,
        source_hint: e.source_hint,
        status: 'mirrored',
    }));
})();
export const PORTED_COMMANDS = _PORTED_COMMANDS;
const _BUILTIN_NAMES = new Set(_PORTED_COMMANDS.map((m) => m.name));
export function builtInCommandNames() {
    return _BUILTIN_NAMES;
}
export function buildCommandBacklog() {
    return new PortingBacklog({ title: 'Command surface', modules: PORTED_COMMANDS });
}
export function commandNames() {
    return PORTED_COMMANDS.map((m) => m.name);
}
export function getCommand(name) {
    const needle = name.toLowerCase();
    return PORTED_COMMANDS.find((m) => m.name.toLowerCase() === needle);
}
export function getCommands(_cwd, includePluginCommands = true, includeSkillCommands = true) {
    let commands = PORTED_COMMANDS;
    if (!includePluginCommands) {
        commands = commands.filter((m) => !m.source_hint.toLowerCase().includes('plugin'));
    }
    if (!includeSkillCommands) {
        commands = commands.filter((m) => !m.source_hint.toLowerCase().includes('skills'));
    }
    return commands;
}
export function findCommands(query, limit = 20) {
    const needle = query.toLowerCase();
    const matches = PORTED_COMMANDS.filter((m) => m.name.toLowerCase().includes(needle) ||
        m.source_hint.toLowerCase().includes(needle));
    return matches.slice(0, limit);
}
export function executeCommand(name, prompt = '') {
    const module = getCommand(name);
    if (module === undefined) {
        return {
            name,
            source_hint: '',
            prompt,
            handled: false,
            message: `Unknown mirrored command: ${name}`,
        };
    }
    const message = `Mirrored command '${module.name}' from ${module.source_hint} would handle prompt ${JSON.stringify(prompt)}.`;
    return {
        name: module.name,
        source_hint: module.source_hint,
        prompt,
        handled: true,
        message,
    };
}
export function renderCommandIndex(limit = 20, query) {
    const modules = query ? findCommands(query, limit) : PORTED_COMMANDS.slice(0, limit);
    const lines = [`Command entries: ${PORTED_COMMANDS.length}`, ''];
    if (query) {
        lines.push(`Filtered by: ${query}`);
        lines.push('');
    }
    lines.push(...modules.map((m) => `- ${m.name} — ${m.source_hint}`));
    return lines.join('\n');
}


path: scripts/dist/command_graph.d.ts
content: import type { PortingModule } from './models.js';
/**
 * Read-only command graph.
 * Commands are bucketed by their `sourceHint` category.
 */
export declare class CommandGraph {
    readonly builtins: readonly PortingModule[];
    readonly pluginLike: readonly PortingModule[];
    readonly skillLike: readonly PortingModule[];
    constructor(builtins: readonly PortingModule[], pluginLike: readonly PortingModule[], skillLike: readonly PortingModule[]);
    /**
     * All commands in a single flat tuple, in the order:
     * builtins → pluginLike → skillLike.
     */
    flattened(): readonly PortingModule[];
    /**
     * Render the command graph as a Markdown summary.
     */
    asMarkdown(): string;
}
/**
 * Build the canonical command graph by partitioning all registered commands
 * according to their `sourceHint` field.
 */
export declare function buildCommandGraph(): CommandGraph;


path: scripts/dist/command_graph.js
content: // Command Graph — organises mirrored commands into three buckets:
//   • builtins   – core commands shipped in the main package
//   • plugin-like – commands that originate from plugins
//   • skill-like  – commands that originate from skills
import { getCommands } from './commands.js';
/**
 * Read-only command graph.
 * Commands are bucketed by their `sourceHint` category.
 */
export class CommandGraph {
    constructor(builtins, pluginLike, skillLike) {
        this.builtins = builtins;
        this.pluginLike = pluginLike;
        this.skillLike = skillLike;
    }
    /**
     * All commands in a single flat tuple, in the order:
     * builtins → pluginLike → skillLike.
     */
    flattened() {
        return [...this.builtins, ...this.pluginLike, ...this.skillLike];
    }
    /**
     * Render the command graph as a Markdown summary.
     */
    asMarkdown() {
        const lines = [
            '# Command Graph',
            '',
            `Builtins: ${this.builtins.length}`,
            `Plugin-like commands: ${this.pluginLike.length}`,
            `Skill-like commands: ${this.skillLike.length}`,
        ];
        return lines.join('\n');
    }
}
/**
 * Build the canonical command graph by partitioning all registered commands
 * according to their `sourceHint` field.
 */
export function buildCommandGraph() {
    const commands = getCommands();
    const builtins = [];
    const pluginLike = [];
    const skillLike = [];
    for (const module of commands) {
        const hint = module.source_hint.toLowerCase();
        if (hint.includes('plugin')) {
            pluginLike.push(module);
        }
        else if (hint.includes('skills')) {
            skillLike.push(module);
        }
        else {
            builtins.push(module);
        }
    }
    return new CommandGraph(builtins, pluginLike, skillLike);
}


path: scripts/dist/context.d.ts
content: export interface PortContext {
    readonly source_root: string;
    readonly tests_root: string;
    readonly assets_root: string;
    readonly archive_root: string;
    readonly python_file_count: number;
    readonly test_file_count: number;
    readonly asset_file_count: number;
    readonly archive_available: boolean;
}
export declare function buildPortContext(_base?: string): PortContext;
export declare function renderContext(context: PortContext): string;


path: scripts/dist/context.js
content: // Context – workspace context mirrored from Python src/context.ts
// Note: Path resolution uses string-based paths since Node.js path module
// is used instead of Python's pathlib.
export function buildPortContext(_base) {
    // In the TypeScript port, we keep paths as logical strings.
    // The actual path resolution would use Node.js `path` module in a real implementation.
    return {
        source_root: '<src_root>',
        tests_root: '<tests_root>',
        assets_root: '<assets_root>',
        archive_root: '<archive_root>',
        python_file_count: 0,
        test_file_count: 0,
        asset_file_count: 0,
        archive_available: false,
    };
}
export function renderContext(context) {
    const lines = [
        `Source root: ${context.source_root}`,
        `Test root: ${context.tests_root}`,
        `Assets root: ${context.assets_root}`,
        `Archive root: ${context.archive_root}`,
        `Python files: ${context.python_file_count}`,
        `Test files: ${context.test_file_count}`,
        `Assets: ${context.asset_file_count}`,
        `Archive available: ${context.archive_available}`,
    ];
    return lines.join('\n');
}


path: scripts/dist/deferred_init.d.ts
content: export interface DeferredInitResult {
    readonly ok: boolean;
    readonly detail: string;
}
export declare function runDeferredInit(_trusted: boolean): DeferredInitResult;


path: scripts/dist/deferred_init.js
content: // Deferred Init – deferred initialization result (stub)
// Mirrored from Python src/deferred_init.py
export function runDeferredInit(_trusted) {
    return { ok: true, detail: 'deferred init stub – no-op in TypeScript port' };
}


path: scripts/dist/direct_modes.d.ts
content: /**
 * Direct Modes Module
 * Supports: direct-connect / deep-link modes
 */
export interface DirectModeReport {
    readonly mode: string;
    readonly target: string;
    readonly active: boolean;
}
export declare function asText(report: DirectModeReport): string;
export declare function runDirectConnect(target: string): DirectModeReport;
export declare function runDeepLink(target: string): DirectModeReport;


path: scripts/dist/direct_modes.js
content: /**
 * Direct Modes Module
 * Supports: direct-connect / deep-link modes
 */
export function asText(report) {
    return `mode=${report.mode}\ntarget=${report.target}\nactive=${report.active}`;
}
export function runDirectConnect(target) {
    return Object.freeze({
        mode: 'direct-connect',
        target,
        active: true,
    });
}
export function runDeepLink(target) {
    return Object.freeze({
        mode: 'deep-link',
        target,
        active: true,
    });
}


path: scripts/dist/execution_registry.d.ts
content: export declare class MirroredCommand {
    readonly name: string;
    readonly source_hint: string;
    constructor(name: string, source_hint: string);
    execute(prompt: string): string;
}
export declare class MirroredTool {
    readonly name: string;
    readonly source_hint: string;
    constructor(name: string, source_hint: string);
    execute(payload: string): string;
}
export declare class ExecutionRegistry {
    readonly commands: readonly MirroredCommand[];
    readonly tools: readonly MirroredTool[];
    constructor(commands: readonly MirroredCommand[], tools: readonly MirroredTool[]);
    command(name: string): MirroredCommand | undefined;
    tool(name: string): MirroredTool | undefined;
}
export declare function buildExecutionRegistry(): ExecutionRegistry;


path: scripts/dist/execution_registry.js
content: // Execution Registry – mirrors commands and tools for execution
// Mirrored from Python src/execution_registry.py
import { PORTED_COMMANDS } from './commands.js';
import { PORTED_TOOLS } from './tools.js';
export class MirroredCommand {
    constructor(name, source_hint) {
        this.name = name;
        this.source_hint = source_hint;
    }
    execute(prompt) {
        // deferred import to avoid circular dependency at module level
        const { executeCommand } = require('./commands.js');
        return executeCommand(this.name, prompt).message;
    }
}
export class MirroredTool {
    constructor(name, source_hint) {
        this.name = name;
        this.source_hint = source_hint;
    }
    execute(payload) {
        const { executeTool } = require('./tools.js');
        return executeTool(this.name, payload).message;
    }
}
export class ExecutionRegistry {
    constructor(commands, tools) {
        this.commands = commands;
        this.tools = tools;
    }
    command(name) {
        const lowered = name.toLowerCase();
        return this.commands.find((c) => c.name.toLowerCase() === lowered) ?? undefined;
    }
    tool(name) {
        const lowered = name.toLowerCase();
        return this.tools.find((t) => t.name.toLowerCase() === lowered) ?? undefined;
    }
}
export function buildExecutionRegistry() {
    const commands = PORTED_COMMANDS.map((m) => new MirroredCommand(m.name, m.source_hint));
    const tools = PORTED_TOOLS.map((m) => new MirroredTool(m.name, m.source_hint));
    return new ExecutionRegistry(commands, tools);
}


path: scripts/dist/history.d.ts
content: export interface HistoryEvent {
    readonly title: string;
    readonly detail: string;
}
export declare class HistoryLog {
    private readonly _events;
    add(title: string, detail: string): void;
    get events(): readonly HistoryEvent[];
    asMarkdown(): string;
}


path: scripts/dist/history.js
content: // History – session history log mirrored from Python src/history.py
export class HistoryLog {
    constructor() {
        this._events = [];
    }
    add(title, detail) {
        this._events.push({ title, detail });
    }
    get events() {
        return this._events;
    }
    asMarkdown() {
        const lines = ['# Session History', ''];
        for (const event of this._events) {
            lines.push(`- ${event.title}: ${event.detail}`);
        }
        return lines.join('\n');
    }
}


path: scripts/dist/main.d.ts
content: /**
 * CLI entry point – TypeScript port of main.py
 *
 * All commands output via console.log; process.argv is parsed with simple if/else.
 * Strict mode: enabled (tsconfig.json strict:true)
 */
export declare function main(argv?: readonly string[]): number;


path: scripts/dist/models.d.ts
content: /**
 * Data models for claw-code-ts
 * Mirrored from Python src/models.py
 * Strict mode enabled.
 */
export declare class Subsystem {
    readonly name: string;
    readonly path: string;
    readonly file_count: number;
    readonly notes: string;
    constructor(args: {
        name: string;
        path: string;
        file_count: number;
        notes: string;
    });
}
export declare class PortingModule {
    readonly name: string;
    readonly responsibility: string;
    readonly source_hint: string;
    readonly status: string;
    constructor(args: {
        name: string;
        responsibility: string;
        source_hint: string;
        status?: string;
    });
}
export declare class PermissionDenial {
    readonly tool_name: string;
    readonly reason: string;
    constructor(args: {
        tool_name: string;
        reason: string;
    });
}
export declare class UsageSummary {
    readonly input_tokens: number;
    readonly output_tokens: number;
    constructor(args?: {
        input_tokens?: number;
        output_tokens?: number;
    });
    addTurn(prompt: string, output: string): UsageSummary;
}
export declare class PortingBacklog {
    readonly title: string;
    readonly modules: readonly PortingModule[];
    constructor(args?: {
        title?: string;
        modules?: readonly PortingModule[];
    });
    summaryLines(): string[];
}


path: scripts/dist/models.js
content: /**
 * Data models for claw-code-ts
 * Mirrored from Python src/models.py
 * Strict mode enabled.
 */
// ---------------------------------------------------------------------------
// Subsystem
// ---------------------------------------------------------------------------
export class Subsystem {
    constructor(args) {
        this.name = args.name;
        this.path = args.path;
        this.file_count = args.file_count;
        this.notes = args.notes;
    }
}
// ---------------------------------------------------------------------------
// PortingModule
// ---------------------------------------------------------------------------
export class PortingModule {
    constructor(args) {
        this.name = args.name;
        this.responsibility = args.responsibility;
        this.source_hint = args.source_hint;
        this.status = args.status ?? 'planned';
    }
}
// ---------------------------------------------------------------------------
// PermissionDenial
// ---------------------------------------------------------------------------
export class PermissionDenial {
    constructor(args) {
        this.tool_name = args.tool_name;
        this.reason = args.reason;
    }
}
// ---------------------------------------------------------------------------
// UsageSummary
// ---------------------------------------------------------------------------
export class UsageSummary {
    constructor(args) {
        this.input_tokens = args?.input_tokens ?? 0;
        this.output_tokens = args?.output_tokens ?? 0;
    }
    addTurn(prompt, output) {
        return new UsageSummary({
            input_tokens: this.input_tokens + prompt.split(/\s+/).filter(Boolean).length,
            output_tokens: this.output_tokens + output.split(/\s+/).filter(Boolean).length,
        });
    }
}
// ---------------------------------------------------------------------------
// PortingBacklog
// ---------------------------------------------------------------------------
export class PortingBacklog {
    constructor(args) {
        this.title = args?.title ?? '';
        this.modules = args?.modules ?? [];
    }
    summaryLines() {
        return this.modules.map((module) => `- ${module.name} [${module.status}] — ${module.responsibility} (from ${module.source_hint})`);
    }
}


path: scripts/dist/parity_audit.d.ts
content: /**
 * Parity Audit – compare TypeScript port against the archived snapshot.
 * Mirrored from Python src/parity_audit.py
 *
 * Strict mode: enabled (tsconfig.json strict:true)
 */
export interface ParityAuditResult {
    readonly archive_present: boolean;
    readonly root_file_coverage: readonly [number, number];
    readonly directory_coverage: readonly [number, number];
    readonly total_file_ratio: readonly [number, number];
    readonly command_entry_ratio: readonly [number, number];
    readonly tool_entry_ratio: readonly [number, number];
    readonly missing_root_targets: readonly string[];
    readonly missing_directory_targets: readonly string[];
}
/**
 * Render the parity audit result as a Markdown string.
 */
export declare function parityAuditAsMarkdown(result: ParityAuditResult): string;
/**
 * Stub parity audit – returns a placeholder result.
 * A full implementation would read the archive snapshot and compare file coverage.
 */
export declare function runParityAudit(): ParityAuditResult;


path: scripts/dist/parity_audit.js
content: /**
 * Parity Audit – compare TypeScript port against the archived snapshot.
 * Mirrored from Python src/parity_audit.py
 *
 * Strict mode: enabled (tsconfig.json strict:true)
 */
/**
 * Render the parity audit result as a Markdown string.
 */
export function parityAuditAsMarkdown(result) {
    const lines = ['# Parity Audit'];
    if (!result.archive_present) {
        lines.push('Local archive unavailable; parity audit cannot compare against the original snapshot.');
        return lines.join('\n');
    }
    lines.push('');
    lines.push(`Root file coverage: **${result.root_file_coverage[0]}/${result.root_file_coverage[1]}**`);
    lines.push(`Directory coverage: **${result.directory_coverage[0]}/${result.directory_coverage[1]}**`);
    lines.push(`Total Python files vs archived TS-like files: **${result.total_file_ratio[0]}/${result.total_file_ratio[1]}**`);
    lines.push(`Command entry coverage: **${result.command_entry_ratio[0]}/${result.command_entry_ratio[1]}**`);
    lines.push(`Tool entry coverage: **${result.tool_entry_ratio[0]}/${result.tool_entry_ratio[1]}**`);
    lines.push('');
    lines.push('Missing root targets:');
    if (result.missing_root_targets.length > 0) {
        for (const item of result.missing_root_targets) {
            lines.push(`- ${item}`);
        }
    }
    else {
        lines.push('- none');
    }
    lines.push('');
    lines.push('Missing directory targets:');
    if (result.missing_directory_targets.length > 0) {
        for (const item of result.missing_directory_targets) {
            lines.push(`- ${item}`);
        }
    }
    else {
        lines.push('- none');
    }
    return lines.join('\n');
}
/**
 * Stub parity audit – returns a placeholder result.
 * A full implementation would read the archive snapshot and compare file coverage.
 */
export function runParityAudit() {
    return {
        archive_present: false,
        root_file_coverage: [0, 0],
        directory_coverage: [0, 0],
        total_file_ratio: [0, 0],
        command_entry_ratio: [0, 0],
        tool_entry_ratio: [0, 0],
        missing_root_targets: [],
        missing_directory_targets: [],
    };
}


path: scripts/dist/permissions.d.ts
content: /**
 * Permission context for blocking tool access.
 * TypeScript port of permissions.py with strict mode.
 */
/**
 * Encapsulates deny-lists for tool names and name prefixes.
 * Use ToolPermissionContext.fromIterables() to construct from optional arrays.
 *
 * Mirrors the Python @dataclass(frozen=True) ToolPermissionContext.
 */
export declare class ToolPermissionContext {
    readonly denyNames: ReadonlySet<string>;
    readonly denyPrefixes: readonly string[];
    constructor(args?: {
        denyNames?: ReadonlySet<string>;
        denyPrefixes?: readonly string[];
    });
    /**
     * Factory: build a ToolPermissionContext from optional arrays of
     * deny-names and deny-prefixes. All values are lower-cased.
     *
     * Mirrors the Python classmethod `from_iterables`.
     */
    static fromIterables(denyNames?: readonly string[] | null, denyPrefixes?: readonly string[] | null): ToolPermissionContext;
    /**
     * Returns true when the given tool name is blocked by either the exact-name
     * deny-list or any of the prefix deny-list entries.
     *
     * Mirrors the Python method `blocks`.
     */
    blocks(toolName: string): boolean;
}


path: scripts/dist/permissions.js
content: /**
 * Permission context for blocking tool access.
 * TypeScript port of permissions.py with strict mode.
 */
/**
 * Encapsulates deny-lists for tool names and name prefixes.
 * Use ToolPermissionContext.fromIterables() to construct from optional arrays.
 *
 * Mirrors the Python @dataclass(frozen=True) ToolPermissionContext.
 */
export class ToolPermissionContext {
    constructor(args) {
        this.denyNames = args?.denyNames ?? new Set();
        this.denyPrefixes = args?.denyPrefixes ?? [];
    }
    /**
     * Factory: build a ToolPermissionContext from optional arrays of
     * deny-names and deny-prefixes. All values are lower-cased.
     *
     * Mirrors the Python classmethod `from_iterables`.
     */
    static fromIterables(denyNames, denyPrefixes) {
        const names = denyNames ?? [];
        const prefixes = denyPrefixes ?? [];
        return new ToolPermissionContext({
            denyNames: new Set(names.map((n) => n.toLowerCase())),
            denyPrefixes: prefixes.map((p) => p.toLowerCase()),
        });
    }
    /**
     * Returns true when the given tool name is blocked by either the exact-name
     * deny-list or any of the prefix deny-list entries.
     *
     * Mirrors the Python method `blocks`.
     */
    blocks(toolName) {
        const lowered = toolName.toLowerCase();
        if (this.denyNames.has(lowered)) {
            return true;
        }
        return this.denyPrefixes.some((prefix) => lowered.startsWith(prefix));
    }
}


path: scripts/dist/port_manifest.d.ts
content: import { Subsystem } from './models.js';
export interface PortManifest {
    readonly src_root: string;
    readonly total_python_files: number;
    readonly top_level_modules: readonly Subsystem[];
}
export declare function buildPortManifest(_srcRoot?: string): PortManifest;


path: scripts/dist/port_manifest.js
content: // Port Manifest – workspace manifest mirrored from Python src/port_manifest.py
export function buildPortManifest(_srcRoot) {
    // Stub: returns an empty manifest. Real implementation would scan the filesystem.
    return {
        src_root: _srcRoot ?? '<port_root>',
        total_python_files: 0,
        top_level_modules: [],
    };
}


path: scripts/dist/prefetch.d.ts
content: export interface PrefetchResult {
    readonly name: string;
    readonly detail: string;
}
export declare function startMdmRawRead(): PrefetchResult;
export declare function startKeychainPrefetch(): PrefetchResult;
export declare function startProjectScan(_root: string): PrefetchResult;


path: scripts/dist/prefetch.js
content: // Prefetch – side-effect prefetch results (stub)
// Mirrored from Python src/prefetch.py
export function startMdmRawRead() {
    return { name: 'mdm_raw_read', detail: 'stub prefetch – no-op' };
}
export function startKeychainPrefetch() {
    return { name: 'keychain_prefetch', detail: 'stub prefetch – no-op' };
}
export function startProjectScan(_root) {
    return { name: 'project_scan', detail: `stub prefetch for root=${_root}` };
}


path: scripts/dist/query_engine.d.ts
content: /**
 * Query Engine — TypeScript port of query_engine.py
 *
 * Porting notes:
 * - Python `uuid4().hex`  →  `crypto.randomUUID()` (Node 14.17+)
 * - Python `@dataclass(frozen=True)`  →  `Readonly<T>` / immutable class
 * - Python `tuple[T, ...]`  →  `readonly T[]`
 * - Python generator `yield`  →  `Generator<T, void, unknown>`
 * - Token estimation: `prompt.split(/\s+/).filter(Boolean).length`
 *
 * Strict mode: enabled (tsconfig.json strict:true)
 */
import type { PermissionDenial } from './models.js';
/** Mirrors models.py Subsystem */
interface Subsystem {
    readonly name: string;
    readonly path: string;
    readonly fileCount: number;
    readonly notes: string;
}
/** Mirrors models.py UsageSummary */
interface UsageSummary {
    readonly inputTokens: number;
    readonly outputTokens: number;
    addTurn(prompt: string, output: string): UsageSummary;
}
/** Minimal PortingBacklog duck-type (summaryLines method only) */
interface PortingBacklog {
    readonly modules: readonly {
        name: string;
        sourceHint: string;
    }[];
    summaryLines(): string[];
}
declare class TranscriptStore {
    private _entries;
    private _flushed;
    get entries(): readonly string[];
    get flushed(): boolean;
    append(entry: string): void;
    compact(keepLast?: number): void;
    replay(): readonly string[];
    flush(): void;
}
interface PortManifest {
    readonly srcRoot: string;
    readonly totalPythonFiles: number;
    readonly topLevelModules: readonly Subsystem[];
}
declare function buildPortManifest(_srcRoot?: string): PortManifest;
declare function buildCommandBacklog(): PortingBacklog;
declare function buildToolBacklog(): PortingBacklog;
interface QueryEngineConfig {
    readonly maxTurns: number;
    readonly maxBudgetTokens: number;
    readonly compactAfterTurns: number;
    readonly structuredOutput: boolean;
    readonly structuredRetryLimit: number;
}
declare const DEFAULT_QUERY_ENGINE_CONFIG: QueryEngineConfig;
interface TurnResult {
    readonly prompt: string;
    readonly output: string;
    readonly matchedCommands: readonly string[];
    readonly matchedTools: readonly string[];
    readonly permissionDenials: readonly PermissionDenial[];
    readonly usage: UsageSummary;
    readonly stopReason: string;
}
type StreamEvent = {
    readonly type: 'message_start';
    readonly sessionId: string;
    readonly prompt: string;
} | {
    readonly type: 'command_match';
    readonly commands: readonly string[];
} | {
    readonly type: 'tool_match';
    readonly tools: readonly string[];
} | {
    readonly type: 'permission_denial';
    readonly denials: readonly string[];
} | {
    readonly type: 'message_delta';
    readonly text: string;
} | {
    readonly type: 'message_stop';
    readonly usage: {
        readonly inputTokens: number;
        readonly outputTokens: number;
    };
    readonly stopReason: string;
    readonly transcriptSize: number;
};
declare class QueryEnginePort {
    private readonly _manifest;
    private _config;
    private readonly _sessionId;
    private _mutableMessages;
    private _permissionDenials;
    private _totalUsage;
    private _transcriptStore;
    constructor(manifest: PortManifest, config?: QueryEngineConfig, sessionId?: string);
    get sessionId(): string;
    get manifest(): PortManifest;
    get config(): QueryEngineConfig;
    set config(value: QueryEngineConfig);
    static fromWorkspace(): QueryEnginePort;
    static fromSavedSession(sessionId: string): QueryEnginePort;
    submitMessage(prompt: string, matchedCommands?: readonly string[], matchedTools?: readonly string[], deniedTools?: readonly PermissionDenial[]): TurnResult;
    streamSubmitMessage(prompt: string, matchedCommands?: readonly string[], matchedTools?: readonly string[], deniedTools?: readonly PermissionDenial[]): Generator<StreamEvent, void, unknown>;
    persistSession(): string;
    private _compactMessagesIfNeeded;
    replayUserMessages(): readonly string[];
    flushTranscript(): void;
    private _formatOutput;
    private _renderStructuredOutput;
    renderSummary(): string;
    private _manifestToMarkdown;
}
export { QueryEnginePort, type QueryEngineConfig, DEFAULT_QUERY_ENGINE_CONFIG, type TurnResult, type StreamEvent, TranscriptStore, buildPortManifest, type PortManifest, buildCommandBacklog, buildToolBacklog, type Subsystem, type UsageSummary, type PortingBacklog, };


path: scripts/dist/remote_runtime.d.ts
content: /**
 * Remote Runtime Module
 * Supports: remote / ssh / teleport modes
 */
export interface RuntimeModeReport {
    readonly mode: string;
    readonly connected: boolean;
    readonly detail: string;
}
export declare function asText(report: RuntimeModeReport): string;
export declare function runRemoteMode(target: string): RuntimeModeReport;
export declare function runSshMode(target: string): RuntimeModeReport;
export declare function runTeleportMode(target: string): RuntimeModeReport;


path: scripts/dist/remote_runtime.js
content: /**
 * Remote Runtime Module
 * Supports: remote / ssh / teleport modes
 */
export function asText(report) {
    return `mode=${report.mode}\nconnected=${report.connected}\ndetail=${report.detail}`;
}
export function runRemoteMode(target) {
    return Object.freeze({
        mode: 'remote',
        connected: true,
        detail: `Remote control placeholder prepared for ${target}`,
    });
}
export function runSshMode(target) {
    return Object.freeze({
        mode: 'ssh',
        connected: true,
        detail: `SSH proxy placeholder prepared for ${target}`,
    });
}
export function runTeleportMode(target) {
    return Object.freeze({
        mode: 'teleport',
        connected: true,
        detail: `Teleport resume/create placeholder prepared for ${target}`,
    });
}


path: scripts/dist/runtime.d.ts
content: import { PermissionDenial, PortingModule } from './models.js';
import { PortContext } from './context.js';
import { HistoryLog } from './history.js';
import { TurnResult as EngineTurnResult } from './query_engine.js';
import { SetupReport, WorkspaceSetup } from './setup.js';
/**
 * RoutedMatch – produced by the prompt routing step.
 * Mirrors Python's @dataclass(frozen=True) RoutedMatch.
 */
export interface RoutedMatch {
    readonly kind: 'command' | 'tool';
    readonly name: string;
    readonly source_hint: string;
    readonly score: number;
}
/**
 * Runtime session – aggregates all state produced by a single bootstrap.
 * Mirrors Python's @dataclass RuntimeSession.
 */
export declare class RuntimeSession {
    readonly prompt: string;
    readonly context: PortContext;
    readonly setup: WorkspaceSetup;
    readonly setup_report: SetupReport;
    readonly system_init_message: string;
    readonly history: HistoryLog;
    readonly routed_matches: readonly RoutedMatch[];
    readonly turn_result: EngineTurnResult;
    readonly command_execution_messages: readonly string[];
    readonly tool_execution_messages: readonly string[];
    readonly stream_events: readonly Record<string, unknown>[];
    readonly persisted_session_path: string;
    constructor(params: {
        prompt: string;
        context: PortContext;
        setup: WorkspaceSetup;
        setup_report: SetupReport;
        system_init_message: string;
        history: HistoryLog;
        routed_matches: readonly RoutedMatch[];
        turn_result: EngineTurnResult;
        command_execution_messages: readonly string[];
        tool_execution_messages: readonly string[];
        stream_events: readonly Record<string, unknown>[];
        persisted_session_path: string;
    });
    asMarkdown(): string;
}
/**
 * Core runtime – routes prompts, manages sessions and turn loops.
 * Mirrors Python class PortRuntime.
 */
export declare class PortRuntime {
    /**
     * Route a prompt to the best-matching commands and tools.
     * Returns up to `limit` matches sorted by score, with one command
     * and one tool promoted to the front if present.
     */
    route_prompt(prompt: string, limit?: number): RoutedMatch[];
    /** Bootstrap a new runtime session from a prompt. */
    bootstrap_session(prompt: string, limit?: number): RuntimeSession;
    /**
     * Run a multi-turn conversation loop.
     * Returns all TurnResult instances produced across the turns.
     */
    run_turn_loop(prompt: string, limit?: number, max_turns?: number, structured_output?: boolean): EngineTurnResult[];
    /** Infer permission denials for dangerous tools. */
    _inferPermissionDenials(matches: readonly RoutedMatch[]): PermissionDenial[];
    /** Collect matching modules for a given token set and kind. */
    _collectMatches(tokens: ReadonlySet<string>, modules: readonly PortingModule[], kind: string): RoutedMatch[];
    /**
     * Score a module against a token set – returns number of matching tokens.
     * Static method mirrors Python's @staticmethod _score.
     */
    static _score(tokens: ReadonlySet<string>, module: PortingModule): number;
}


path: scripts/dist/session_store.d.ts
content: export interface StoredSession {
    readonly session_id: string;
    readonly messages: readonly string[];
    readonly input_tokens: number;
    readonly output_tokens: number;
}
export declare function loadSession(_sessionId: string): StoredSession;
export declare function saveSession(_session: StoredSession): string;


path: scripts/dist/session_store.js
content: // Session Store – persisted session storage (stub)
// Mirrored from Python src/session_store.py
export function loadSession(_sessionId) {
    return {
        session_id: _sessionId,
        messages: [],
        input_tokens: 0,
        output_tokens: 0,
    };
}
export function saveSession(_session) {
    return `<session_store_path>/${_session.session_id}.json`;
}


path: scripts/dist/setup.d.ts
content: import { DeferredInitResult } from './deferred_init.js';
import { PrefetchResult } from './prefetch.js';
export declare class WorkspaceSetup {
    readonly python_version: string;
    readonly implementation: string;
    readonly platform_name: string;
    readonly test_command: string;
    constructor(args?: {
        python_version?: string;
        implementation?: string;
        platform_name?: string;
        test_command?: string;
    });
    startup_steps(): readonly string[];
}
export interface SetupReport {
    readonly setup: WorkspaceSetup;
    readonly prefetches: readonly PrefetchResult[];
    readonly deferred_init: DeferredInitResult;
    readonly trusted: boolean;
    readonly cwd: string;
}
export declare function runSetup(_cwd?: string, trusted?: boolean): SetupReport;


path: scripts/dist/system_init.d.ts
content: export declare function buildSystemInitMessage(trusted?: boolean): string;


path: scripts/src/__init__.py
content: """Tracked snapshot metadata extracted from the local TypeScript archive."""


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)