moon_repomix

    Generate AI-ready repository context with native AST compression, Git diffs/history, HTTPS inputs and exact o200k token counts.

    repomix
    cli
    context
    native
    Download zip
    Author
    Version
    0.7.0
    License
    MIT
    Last updated
    23 days ago
    Downloads
    191

    #moon-repomix

    moon-repomix 是由 MoonBit native 实现的代码仓库上下文工具,运行时无需 Node.js。它支持读取本地目录或公开 HTTPS Git 仓库,输出 XML、Markdown、JSON 或 plain 文本;默认对完整原文先执行敏感信息启发式扫描,再做目录投影、AST 骨架压缩或按需读取,并对最终交付的完整正文执行精确 o200k_base token 计量。

    除普通目录打包外,项目围绕任务预算规划(plan_task_context)与代码按需补读(read_code_context)提供跨 SDK、CLI、MCP 和浏览器工作台(WebUI)的统一上下文工作流:

    • AST 骨架压缩(7 类语言):MoonBit(含 .mbti)、JavaScript / TypeScript(含 JSX / TSX)、Python、Go、Rust、Java。
    • 符号读取、符号目录与同文件依赖索引:支持 JavaScript / JSX / TypeScript / TSX、Python、MoonBit(.mbt / .mbti)。

    #版本边界与当前源码说明

    GitHub Release v0.7.0 与 Mooncakes 注册表 Delthin/moon_repomix@0.7.0 提供统一 ContextRequest 协议与校验 API、CLI --context-request / --context-stdio、MoonBit(.mbt / .mbti)符号与同文件依赖索引,以及 WebUI 请求配置保存/导入。普通打包、SDK pack / read_code_context / plan_task_context 和既有 MCP、工作台用法保持兼容。

    #统一任务规划与代码补读协议

    v0.7.0 中,任务预算(必选/可选文件模式与优先级)和代码补读(完整符号、不连续行范围、全文或符号目录)共享版本化 ContextRequest JSON(规范化上限 64 KiB)。以下请求可直接在本仓库使用,读取 src/version.mbt 的 version 符号及同文件依赖:

    { "schemaVersion": 1, "operation": "read_code_context", "spec": { "maxTokens": 8000, "requests": [ { "path": "src/version.mbt", "symbols": ["version"], "includeDependencies": true } ] } }

    入口如何使用同一份 ContextRequest权限、限额与会话边界
    CLImoon-repomix . --context-request request.json(或 -o response.json);多轮 JSONL 用 moon-repomix . --context-stdio规格内路径相对命令指定的授权根解释;响应 JSON 封装完整正文、计量与审计
    SDKContextRequest::from_json 校验后取出 spec_json(),转交 CodeContextSpec / TaskContextSpec 并调用对应 Root API不自动执行或授予文件权限;用 CodeContextSession 管理最多 3 轮成功累计预算
    MCP直接作为 execute_context_request 的 arguments;用 context_capabilities 查询主机能力与后缀绑定启动时固定的只读根目录;原 plan_task_context / read_code_context 继续兼容
    WebUI / HTTP工作台切到任务预算或代码补读后“导入配置”/“保存配置”;HTTP 用 {directory, request} 外层对象发送至 POST /api/context-request沿用页面当前授权目录;保存的配置不含源码、目录与会话 ID

    代码补读会话由首轮 spec.maxTokens 固定累计正文硬上限,续读在顶层传 continueFrom(不带 maxTokens),最多成功 3 轮,失败不扣额度。会话 ID 不能跨进程或跨入口迁移。代码审计嵌于正文并计入正文预算,任务审计独立计数;正文 cap 均不含外层传输封装。普通打包参数与主机输出风格仍按各入口规则收紧。

    #安装与第一次运行

    #1. 使用 v0.7.0 预编译归档

    从 GitHub Releases (v0.7.0) 下载对应平台归档并通过 SHA256SUMS 校验。解压时请保留 bin/、share/、LICENSES/ 的相对目录位置(分词词表等资源随包附带)。

    # Unix ./bin/moon-repomix /path/to/project # Windows PowerShell .\bin\moon-repomix.exe "C:\path\to\project"

    默认在当前启动目录生成 repomix-output.xml。本地目录打包无需安装 Git;仅在读取 Git diff/log 或克隆公开 HTTPS 仓库时需要系统 git。

    #2. 从当前源码构建与安装

    源码构建要求 MoonBit 0.10.20 及以上与平台 C 工具链(默认 native 后端),源码运行会自动发现仓库内 assets:

    moon update moon run src/cmd/moon-repomix --release -- examples/demo -f md -o - # 安装到用户目录(Windows 可用 "$env:LOCALAPPDATA\moon-repomix") moon run --target native scripts/install.mbtx "$HOME/.local"

    将安装前缀下的 bin 加入 PATH 后即可直接调用 moon-repomix。

    #常用 CLI 命令

    # 输出 Markdown 到文件;-o - 表示正文写 stdout、统计信息写 stderr moon-repomix ./project -f md -o context.md # 提取 AST 骨架压缩;按 glob 过滤并输出 JSON moon-repomix ./project --compress --include 'src/**,README.md' -f json -o context.json # 软预算检查(超限仍写出完整文件并以状态码 1 退出,不同于任务/代码硬预算) moon-repomix ./project --budget 12000 # 分卷输出(目标目录必须尚不存在;每卷按完整输出计量,索引文件单独计数) moon-repomix ./project --compress --split 12000 -f md -o review-parts

    更多选项可通过 --help 或 --help-all 查看。

    #浏览器工作台(WebUI)与 MCP 服务

    # 启动本地浏览器工作台(默认监听 http://127.0.0.1:8765) moon-repomix ./project --webui # 启动固定只读根目录的 stdio MCP 服务 moon-repomix /absolute/project --mcp --mcp-max-tokens 12000

    工作台提供普通打包、任务预算与代码补读三种工作方式。下图演示普通打包流程:

    WebUI 普通打包演示

    MCP 客户端配置细节参见 docs/mcp.md。

    #MoonBit SDK

    在 moon.mod 添加 Delthin/moon_repomix,并在包配置中导入 "Delthin/moon_repomix" @repomix。Runtime 会加载 o200k_base.tiktoken 与同目录的 tokenizer-unicode-16.0.0.txt 并校验 SHA-256,可在多次调用间复用;返回结果不会自动写盘:

    async fn run_pack() -> Unit {
    let runtime = @repomix.Runtime::load("/absolute/share/moon-repomix/o200k_base.tiktoken")
    let options = @repomix.options("/absolute/project", style=@repomix.Style::Json, compress=true)
    let result = @repomix.pack(options, runtime)
    println(result.tokens.to_string())
    }

    #安全扫描与精确计量说明

    • 编码与启发式安全扫描:仅处理有效 UTF-8 普通文件(去 BOM、保留原换行)。先扫描完整原文,命中的敏感文件、patch 或 commit 整项排除;若自定义模板自身命中敏感规则则直接停止。启发式扫描不能替代人工审阅,分享前请检查输出。
    • 资源边界与完整计数:token 预算只约束输出正文,不是进程内存配额(普通打包默认单文件 50 MiB、候选 20,000 个、原始总读取 200 MiB,服务端点有更严格上限)。总 token 针对含格式头部、模板与包装在内的完整正文计算,而非逐文件数字简单相加。

    #文档导航、致谢与许可

    Finding

    Locations refer to the original disk UTF-8 bytes, including a stripped BOM.

    Partition

    Total tokens include each independent volume and the independent index.

    PartitionError

    Callback errors propagate unchanged; these errors describe partition failures.

    Section

    Additional untrusted repository context, such as a diff or commit message.

    Skipped

    Path is root-relative. Reasons are documented in docs/file-selection.md.

    UnitIdentity

    Identity in the input document, independent of section titles.

    Volume

    text is exactly the rendered string passed to the counter.

    CodeContextError

    pub(all) suberror CodeContextError {
    InvalidCodeSpec
    }

    A malformed code-reading request, rejected before filesystem access.

    CodeSessionError

    pub(all) suberror CodeSessionError {
    InvalidCodeSession
    CodeRoundLimit
    CodeBudgetExhausted
    }

    A reading session cannot spend beyond its original whole-document budget or commit more than three successful reads. Transport identifiers, directories, resource lifetimes and final response publication belong to the adapter.

    ContextRequestError

    pub(all) suberror ContextRequestError {
    InvalidContextRequest
    }

    PackError

    pub(all) suberror PackError {
    ConfigurationError
    ContextTextError(String)
    ContextSecurityFinding(String)
    SelectionError
    InputLimitExceeded(kind~ : String, limit~ : Int64)
    ScanError
    ResourceError
    GitError
    RemoteError
    }

    TaskContextError

    pub(all) suberror TaskContextError {
    InvalidTaskSpec
    }

    Invalid task descriptions are rejected before filesystem access.

    BudgetStatus

    pub(all) enum BudgetStatus {
    NotSet
    Within(Int)
    Exceeded(Int)
    }

    CodeContextPlan

    pub struct CodeContextPlan {
    status : String
    text : String?
    tokens : Int
    bytes : Int
    required_tokens : Int?
    audit :
    Json

    security : SecurityStatus
    }

    A complete, exactly counted JSON payload, or a body-free failure audit. tokens includes the embedded audit; protocol envelopes are not counted.

    CodeContextSession

    pub struct CodeContextSession {
    limit : Int
    spent : Int
    rounds : Int
    }

    Immutable accounting shared by SDK, command line, MCP and HTTP adapters. Advance a candidate only when its result is ready to publish; a failed read returns the same accounting and does not consume a successful round.

    CodeContextSession::advance

    CodeContextSession::can_continue

    fn CodeContextSession::can_continue(self : CodeContextSession) -> Bool

    CodeContextSession::max_rounds

    fn CodeContextSession::max_rounds() -> Int

    CodeContextSession::new

    fn CodeContextSession::new(max_tokens : Int) -> CodeContextSession raise CodeSessionError

    CodeContextSession::remaining

    fn CodeContextSession::remaining(self : CodeContextSession) -> Int

    CodeContextSession::request

    Validate a request with the remaining allowance. value contains requests and optionally maxReadBytes; it must not replace the session's maxTokens.

    test {
    let session = @moon_repomix.CodeContextSession::new(8000)
    let spec = session.request({
    "requests": [{ "path": "src/main.mbt", "full": true }],
    })
    ignore(spec)
    }

    CodeContextSession::to_json

    CodeContextSpec

    pub struct CodeContextSpec {
    max_tokens : Int
    // private fields
    }

    Immutable validated request for read_code_context.

    CodeContextSpec::from_json

    Each path selects exactly one of symbols, inclusive ranges, full:true, or outline:true. includeDependencies is available only with symbols. Unknown fields, duplicate paths, and non-canonical relative paths fail.

    test "code context request example" {
    let spec = @moon_repomix.CodeContextSpec::from_json({
    "maxTokens": 4000,
    "requests": [{ "path": "lib/response.js", "symbols": ["res.render"] }],
    })
    assert_eq(spec.max_tokens, 4000)
    }

    ContextOperation

    pub(all) enum ContextOperation {
    Task
    Code
    } derive(Eq,
    Debug
    )

    Portable operation names, independent of host permissions and transport IDs.

    ContextOperation::equal

    ContextOperation::not_equal

    fn ContextOperation::not_equal(x : ContextOperation, y : ContextOperation) -> Bool

    ContextRequest

    pub struct ContextRequest {
    operation : ContextOperation
    continue_from : String?
    // private fields
    }

    An immutable validated portable request. JSON accessors return fresh copies.

    ContextRequest::from_json

    Validate the existing Root spec without granting filesystem access. Continuations omit maxTokens; their actual budget comes from the host session.

    ContextRequest::spec_json

    ContextRequest::to_json

    FileStats

    pub(all) struct FileStats {
    path : String
    disk_bytes : Int
    tokens : Int
    original_tokens : Int
    }

    Body counts precede presentation line prefixes and format escaping. PackResult.tokens counts the complete rendered document instead.

    PackResult

    pub struct PackResult {
    document :
    Document

    text : String
    bytes : Int
    tokens : Int
    files : Array[FileStats]
    skipped : Array[
    Skipped
    ]
    findings : Array[
    Finding
    ]
    security : SecurityStatus
    budget : BudgetStatus
    }

    Excluded files retain only metadata; their contents are absent.

    PathExplanation

    pub struct PathExplanation {
    path : String
    eligible : Bool
    status : String
    stage : String
    reason : String
    origin :
    RuleOrigin
    ?
    finding_count : Int
    finding_rules : Array[String]
    }

    One queried path: eligibility precedes source decoding and safety checks.

    Runtime

    pub struct Runtime {
    encoder :
    Encoder

    }

    Validated resources shared by sequential pack operations.

    Runtime::load

    async fn Runtime::load(tokenizer_path : String) -> Runtime

    SecurityStatus

    pub(all) enum SecurityStatus {
    Passed
    Excluded
    Disabled
    }

    SelectionReport

    pub struct SelectionReport {
    paths : Array[PathExplanation]
    security : SecurityStatus
    style :
    Style

    candidate_count : Int
    accepted_count : Int
    read_bytes : Int64
    max_files : Int
    max_total_size : Int64
    }

    A bounded query, not a promise that an entire repository fits its quotas.

    SelectionReport::to_json

    Machine-safe projection: no file bodies, rule text or absolute rule paths.

    TaskContextPlan

    pub struct TaskContextPlan {
    status : String
    text : String?
    tokens : Int
    bytes : Int
    audit :
    Json

    audit_text : String
    audit_tokens : Int
    audit_bytes : Int
    security : SecurityStatus
    }

    One shared model input plus a separately counted, body-free audit. Only complete and with_omissions contain text; failures cannot be committed.

    TaskContextSpec

    pub struct TaskContextSpec {
    max_tokens : Int
    // private fields
    }

    A validated, bounded task set. Construct with TaskContextSpec::from_json. The serialized description is retained privately to prevent mutable JSON or arrays supplied by a caller from changing a validated request.

    TaskContextSpec::from_json

    Parse a strict task description without reading any files. Required entries accept full or skeleton; optional entries also accept either and a priority from 0 to 100 (default 0). Unknown fields are rejected.

    VolumePackResult

    pub struct VolumePackResult {
    partition :
    Partition

    file_names : Map[String, String]
    files : Array[FileStats]
    skipped : Array[
    Skipped
    ]
    findings : Array[
    Finding
    ]
    security : SecurityStatus
    }

    Prepared, scanned input split into separately bounded documents and an index.

    context_capabilities

    fn context_capabilities() ->
    Json

    Transport-independent operation, selector and schema limits. An adapter can impose smaller host-authorized limits; these values do not grant access.

    explain_selection

    async fn explain_selection(options :
    Options
    , paths : Array[String]) -> SelectionReport

    Inspect only requested local paths. Uses the same selection and source safety stages as pack, without tokenizer loading, transforms, templates or Git export. Does not write files or alter any generated context.

    options

    fn options(directory : String, style? :
    Style
    , split_output? :
    SplitOutput
    , compress? : Bool, keep_full_patterns? : Array[String], header_text? : String, instruction_file_path? : String?, full_metadata? : Bool, file_summary? : Bool, directory_structure? : Bool, include_files? : Bool, git_sections? : Bool, metadata? : Bool, show_line_numbers? : Bool, output_file_path_style? :
    PathStyle
    , file_paths? : Array[String]?, include_diffs? : Bool, include_logs? : Bool, include_logs_count? : Int, remote? : String?, remote_branch? : String?, max_files? : Int, max_total_size? : Int64) ->
    Options
    raise

    Validated options for one directory, with the selected format and scanning enabled.

    Use options("/absolute/project", style=Json) to select JSON and its default filename.

    pack

    async fn pack(options :
    Options
    , runtime : Runtime) -> PackResult

    Build and count a complete document. Remote inputs are fetched and cleaned here. The caller decides where to write the result.

    pack_volumes

    async fn pack_volumes(options :
    Options
    , runtime : Runtime, max_tokens~ : Int) -> VolumePackResult

    Prepare one immutable context, then split it at file/section boundaries. max_tokens bounds every complete rendered volume; index_tokens is separate. Options.token_budget is the single-document pack budget and is not applied here. Returned strings are the exact strings counted; this function writes no files.

    plan_task_context

    async fn plan_task_context(options :
    Options
    , runtime : Runtime, spec : TaskContextSpec) -> TaskContextPlan

    Build one exact-token task context from literal paths under the host's existing selection and security rules. Optional files are read lazily in descending priority. This local-only API rejects remote/Git/split-output options and hidden file bodies; pack and pack_volumes are unchanged.

    The cap covers the returned text, not audit or the caller's model messages. Reserve those costs before choosing maxTokens. Read limits retain the existing reader's single excess-byte probe.

    read_code_context

    async fn read_code_context(options :
    Options
    , runtime : Runtime, spec : CodeContextSpec) -> CodeContextPlan

    Read explicitly scoped symbols, source ranges, outlines, or full files. Selection and security are applied before indexing or slicing. All requested entries must be available and fit the complete JSON payload cap; no source body is returned on failure. Dependency expansion is lexical and same-file, not a semantic cross-file call graph. Use another request for missing code.

    version

    fn version() -> String

    Version of the native CLI and library.