GitNexus/docs/wiki-generation.md
Justin Lee 071286affb
fix(wiki): budget wiki prompts to the model context window (#4200)
* fix(wiki): budget wiki prompts to the model context window

`gitnexus wiki` could send prompts larger than the model's context window
(#1290: 370k tokens against a 131k window). Grouping used a fixed 100k
estimate with chars/4 counting, and parent and overview pages concatenated
every child summary and every inter-module edge without a limit.

- Add a context-window setting: --context-window, GITNEXUS_CONTEXT_WINDOW,
  or "contextWindow" in ~/.gitnexus/config.json (default 128000), resolved
  and validated like the completion-token limit.
- Budget each prompt to the window minus the completion limit, the system
  prompt and a safety margin, using a 3 chars/token estimate. Grouping falls
  back to batches, module source is clipped, child and module summaries share
  the remaining budget, and overview edges are capped at the 200 strongest.
- On a context-length 400, explain how to set the window.

Fixes #1290

* fix(wiki): reject context windows that cannot fit a prompt

Address review feedback on the prompt budget:
- promptTokenBudget throws instead of returning a 4k floor that overflows
  the configured window; resolveLLMConfig rejects a configured window
  smaller than the completion limit + 6000 up front.
- When only the completion limit is raised, the default window grows by
  the same amount, so existing --max-completion-tokens setups keep working.
- clipToTokens stays within budgets smaller than the truncation notice.
- Restore the --lang JSDoc above buildSystemPrompt.
- Tests pin the minimum budget and the small-share case.

* fix(wiki): bound graph references in module prompts

Carry the distinct coverage from #1494 into #4200.

Co-authored-by: ChasLui <10083758+ChasLui@users.noreply.github.com>

* fix(wiki): keep joined section lists within the prompt budget

fitSectionsToBudget returns one string per section, so with more sections
than tokens the callers' separators alone could overflow the budget.
Parent and overview prompts now use joinSectionsToBudget, which keeps the
first sections and ends with an "N more omitted" line when there is not
room for every separator.

* fix(wiki): localize context help and isolate test

* fix(wiki): budget every prompt block together and count CJK per character

The overview reserved room for up to 200 full edge lines, the project
info and the process list before clipping module summaries, so with 200
edges and an 8,000-token window the request reached 9,369 estimated
tokens against a 4,699-token budget. fillTemplateWithinBudget now
measures the template's own text and shares the rest among every
variable; parent and overview pages use it, budgeted against the system
prompt they actually send (with the --lang instruction).

estimateTokensSafe counted three characters per token, which undercounts
CJK text about threefold. Non-ASCII code units now cost a whole token,
and clipping cuts by that cost without splitting surrogate pairs.

A raised completion limit no longer grows the default context window;
the window is the model's capacity. minContextWindow also reserves room
for a system prompt, so the smallest accepted window can generate.

* refactor(wiki): replace nested ternaries in the prompt budget

Address SonarCloud findings on #4200: read code units with codePointAt,
detect a split surrogate pair from the code point that starts before the
cut, and turn the nested ternaries in partTokens and
fillTemplateWithinBudget into if statements.

* fix(wiki): keep dropping a lone high surrogate before the clip point

d2442e0c switched the split-pair check to codePointAt and only caught a
cut pair, so a lone high surrogate right before the cut was kept instead
of dropped as before. Check both cases again and pin the lone surrogate
in a test.

* fix(wiki): measure grouping with the Unicode-aware estimator and fill template fields once

Grouping batches were sized with chars/4, so CJK paths and symbols could
overflow the window. They now use estimateTokensSafe, capped at the
400,000 ASCII characters the old budget allowed.

fillTemplate now replaces each of the template's own placeholders once,
with the value inserted literally. A README that mentions a placeholder
is no longer expanded a second time, and $-patterns in repository text
are no longer read as replacement patterns.

* fix(wiki): drop the unbudgeted separator from joinSectionsToBudget

The join reserve is one token per section, which only holds for the fixed
'\n\n' separator. No caller passed another one, so the parameter is removed
and a type-level test keeps it from coming back. The capLines JSDoc now
describes the omission line it appends.

* fix(wiki): budget non-ASCII text at a token per UTF-8 byte

A token per CJK character let clipped text overflow the window: a spread
of CJK ideographs clipped to 4,697 estimated tokens measured 11,045 with
cl100k_base. Byte-level tokenizers never spend more than a token per UTF-8
byte, so non-ASCII text is now budgeted at that bound; ASCII keeps its
three-characters-per-token heuristic.

The assembly tests now measure captured requests independently of the
estimator, the parent-page case sends an edge block that alone exceeds
the budget, and the docs give the real 6,500-token minimum and say the
default window no longer grows with the completion limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Abhigyan Patwari <126312502+abhigyanpatwari@users.noreply.github.com>
Co-authored-by: ChasLui <10083758+ChasLui@users.noreply.github.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Abhinav Pandey <abhinavpandey1230@gmail.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 06:27:03 +00:00

122 lines
7.2 KiB
Markdown

# Wiki generation
[Back to GitNexus](../README.md)
Generate LLM-powered documentation from your knowledge graph:
```bash
# Requires an LLM API key (MINIMAX_API_KEY, ANTHROPIC_API_KEY, GITNEXUS_API_KEY or OPENAI_API_KEY)
gitnexus wiki
gitnexus wiki src/features # a file uses its folder; a folder without an index of its own uses the repository's index
gitnexus wiki --api-key <key> # or pass the key on the command line
# Use a custom model or provider (default model: MiniMax-M3)
gitnexus wiki --model gpt-4o
gitnexus wiki --base-url https://api.anthropic.com/v1
gitnexus wiki --provider anthropic # Anthropic Messages API (default model: claude-opus-5-5)
gitnexus wiki --provider grok # local Grok Build CLI (uses `grok login`, no API key)
# Providers: minimax, anthropic, openai, openrouter, azure, custom,
# and the local agent CLIs cursor, claude, codex, opencode and grok
# Azure OpenAI with a legacy deployment URL also needs an api-version
gitnexus wiki --provider azure --api-version 2024-10-21 \
--base-url https://<resource>.openai.azure.com/openai/deployments/<deployment>
# Turn reasoning mode on or off. MiniMax-M3 uses adaptive thinking unless
# --no-reasoning-model is set; o1, o3 and their -mini or -preview models are detected.
gitnexus wiki --reasoning-model
gitnexus wiki --no-reasoning-model
# Force full regeneration
gitnexus wiki --force
# Run more LLM calls in parallel (default: 3)
gitnexus wiki --concurrency 6
# Increase the timeout or retries for large codebases or slow LLM providers
gitnexus wiki --timeout <seconds> # LLM request timeout in seconds (default: disabled)
gitnexus wiki --retries <n> # Max LLM retry attempts per request (default: 3)
# Raise the completion-token limit (default: 16384)
gitnexus wiki --max-completion-tokens 131072
GITNEXUS_MAX_COMPLETION_TOKENS=131072 gitnexus wiki
# Or set "maxCompletionTokens": 131072 in ~/.gitnexus/config.json
# Precedence: flag, then the environment variable, then the config file.
# Tell GitNexus the model's context window so prompts are trimmed to fit (default: 128000)
gitnexus wiki --context-window 32768
GITNEXUS_CONTEXT_WINDOW=32768 gitnexus wiki
# Or set "contextWindow": 32768 in ~/.gitnexus/config.json (same precedence as above).
# The window must be at least the completion limit + 6500 tokens; smaller values are rejected.
# Raising only the completion limit keeps the default 128000 window and leaves less room for
# the prompt; a limit that leaves no room fails before the first request, so set the window too.
# Allow a specific LAN/self-hosted HTTP LLM host (HTTPS is preferred for remote endpoints)
gitnexus wiki --base-url http://llama-box.local:8080/v1 --allow-insecure-connection llama-box.local
# Or set a comma-separated host allowlist:
GITNEXUS_ALLOW_INSECURE_CONNECTION=llama-box.local,192.168.1.23
# Change the output language
gitnexus wiki --lang <lang> # e.g. english, chinese, spanish, japanese
# Review the module structure before any page is generated
gitnexus wiki --review
# Print the commands and responses of a local agent CLI provider
gitnexus wiki --provider claude --verbose
# Publish the wiki as a public GitHub Gist after generation (needs the GitHub CLI, `gh`)
gitnexus wiki --gist
```
`--provider`, `--model`, `--base-url`, `--api-key`, `--api-version` and `--reasoning-model`
are saved to `~/.gitnexus/config.json`, so later runs reuse them without the flags. The API
key is stored there as plain text. Switching to another `--provider` clears the saved key,
base URL, model, api-version and reasoning setting. `--api-version` is appended to requests
only for Azure: `--provider azure` or an Azure OpenAI base URL.
`--review` stops after modules are grouped. It prints the module tree, saves it as
`module_tree.json` in the wiki output folder, and asks whether to continue. Answer `edit` to
open the file in `$EDITOR` (or `$VISUAL`, else `vi`) and generate pages from the edited tree,
or `n` to stop. In a non-interactive shell, generation continues without asking.
Wiki generation uses a system Git installation to compare revisions. If Git is installed
elsewhere, set `GITNEXUS_WIKI_GIT_PATH` to the absolute path of your trusted Git executable.
`--force` groups the files into modules again before regenerating every page, unless
`module_tree.json` was edited since the last generation; an edit is used for the next
generation only. A run that finds more than five new source files since the last generation
(files the knowledge graph indexes, at paths that did not exist then) also groups the files
again, or uses an edited tree the same way. It then rewrites only the pages of modules whose
files changed and deletes the pages of modules that are gone; other `.md` files in the wiki
folder are left alone. If such a run stops before the end, the next run at the same commit
completes it, and a run at another commit writes again the pages it changed.
The completion limit must be a positive integer supported by your model. It applies to
OpenAI-compatible HTTP providers; local agent CLI providers manage their own limits.
For reasoning models, the limit includes reasoning tokens as well as the visible answer.
When a provider reports `finish_reason: "length"`, GitNexus rejects the incomplete response
instead of saving it as a finished page. Failed modules are listed, the command exits with
status 1, and a normal rerun retries them even if the repository commit has not changed.
Increase `--max-completion-tokens` within your model's supported limit before retrying.
Truncated grouping or overview responses also fail the run; batched grouping retains its
directory-based fallback. Incomplete runs are not published with `--gist`.
Use `--force` to replace incomplete pages already saved by an older version.
The context window must be a positive integer. GitNexus keeps each prompt within the window
minus the completion limit, the system prompt and a safety margin: grouping falls back to
batches, and module sources, child summaries and overview edges are trimmed. Sizes are estimated
without the model's tokenizer: non-ASCII text at a token per UTF-8 byte, ASCII at three characters
per token. If the provider still answers `400` with a context-length error, lower
`--context-window` to the model's real limit.
For safety, `http://` LLM base URLs are allowed by default only for loopback hosts (`localhost`, `127.0.0.1`, `::1`). `--allow-insecure-connection` and `GITNEXUS_ALLOW_INSECURE_CONNECTION` accept exact hostnames or IP addresses only; do not include schemes, ports, paths, credentials, or wildcards.
The wiki generator reads the indexed graph structure, groups files into modules via LLM, generates per-module documentation pages, and creates an overview page — all with cross-references to the knowledge graph.
A module whose source does not fit one page (30,000 tokens) is split by directory, below the
directory its files share, so a Gradle or Maven module is split at its packages
(`src — main/entity`). Small neighbouring directories share a page up to the same size, and so
do the files sitting directly in a directory (`top-level files (1 of 2)`), so only a single file
larger than a page is cut. A module of three files or fewer stays on one page. IntelliJ project
files (`.iml`, `.ipr`, `.iws`) and Gradle lockfiles are not indexed, so they get no page.