Skip to content

About

🧠 GitHub Action that embeds your repository's source code into LatticeDB and exports a browser-loadable lattice-jsonl RAG corpus

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AutoRepoRAG

CI Release GitHub Marketplace License: Apache-2.0

Turn your repository into a ready-to-query vector corpus, straight from CI. AutoRepoRAG chunks your source code, embeds it (against any OpenAI-compatible embeddings endpoint, or with deterministic mock vectors that need no secrets), loads and verifies every vector against a real, checksum-pinned LatticeDB server, and exports a byte-deterministic lattice-jsonl corpus β€” plus a gzip twin and a metadata manifest β€” that a browser, a bot, or another pipeline can consume directly. Zero npm dependencies, no Docker, no build step: a composite action running vendored Node ESM.

  repo files                                            outputs
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚ paths     │──▢│ chunk  │──▢│ embed     │──▢│ load + VERIFY        β”‚
 β”‚ globs     β”‚   β”‚ 90-lineβ”‚   β”‚ live API  β”‚   β”‚ real lattice-server  β”‚
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚ windowsβ”‚   β”‚ or mock   β”‚   β”‚ Β· points_count       β”‚
                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜   β”‚ Β· self-retrieval     β”‚
                                    β”‚         β”‚ Β· scroll fidelity    β”‚
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚  reuse by chunk_hash                   β”‚
                 β”‚  (previous-corpus-url)                 β–Ό
                 β”‚                            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 └───────────────────────────▢│ corpus.jsonl         β”‚
                                              β”‚ corpus.jsonl.gz      β”‚
                                              β”‚ corpus.meta.json     β”‚
                                              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Quick start

- uses: actions/checkout@v7

- name: Build code corpus
  id: rag
  uses: Avarok-Cybersecurity/AutoRepoRAG@v2
  with:
    paths: |
      src/**/*.rs
      src/**/*.ts
    embedding-endpoint: https://openrouter.ai/api/v1
    embedding-model: nvidia/llama-nemotron-embed-vl-1b-v2:free
    embedding-api-key: ${{ secrets.OPENROUTER_API_KEY }}
    collection: coderag
    chunk-lines: '90'
    chunk-overlap: '15'
    max-chunk-bytes: '16384'
    vector-precision: '6'
    request-interval-ms: '2500'
    lattice-version: v0.3.3
    generate-website-chat: 'false'

- run: echo "Built ${{ steps.rag.outputs.points }} points at dim ${{ steps.rag.outputs.dim }}"

Every input that shapes the corpus is required and has no default (see Inputs): a corpus records exactly what produced it, and two corpora are only comparable when the same values were stated for both.

No secrets? Use mock mode β€” same pipeline, deterministic vectors. It still states the corpus-shaping inputs, so a dry run chunks exactly like the real publish:

- uses: Avarok-Cybersecurity/AutoRepoRAG@v2
  with:
    paths: |
      src/**/*.rs
    mock-embeddings: 'true'
    embedding-endpoint: https://openrouter.ai/api/v1
    collection: coderag
    chunk-lines: '90'
    chunk-overlap: '15'
    max-chunk-bytes: '16384'
    vector-precision: '6'
    request-interval-ms: '2500'
    lattice-version: v0.3.3
    generate-website-chat: 'false'

Runs on Linux and macOS runners, x64 or arm64 (ubuntu-latest, ubuntu-24.04-arm, macos-latest, …): the lattice-server release binary for the runner is downloaded and verified against the release's checksum file, and for the versions listed in src/pins.mjs (v0.5.0 and v0.5.1 today) also against the sha256 this action pins.

Inputs

Required, no default β€” these shape the corpus. The action fails at once with input "<name>" is required when one is missing (GitHub does not enforce required for composite actions; the action does).

Input Description
paths Newline-separated include globs (** / * / ? and {a,b}), relative to the source root (source-dir, or the workspace).
embedding-endpoint OpenAI-compatible embeddings API base URL (POST <endpoint>/embeddings). Required in mock mode too.
collection LatticeDB collection name recorded in the corpus header.
chunk-lines Lines per chunk window.
chunk-overlap Lines of overlap between consecutive chunks (stride = chunk-lines βˆ’ chunk-overlap).
max-chunk-bytes Hard byte cap per chunk text (UTF-8).
vector-precision Significant digits vectors are rounded to (then f32-cast) before upsert and export.
request-interval-ms Minimum milliseconds between embeddings request starts (free-tier pacing).
lattice-version Pinned lattice-db release tag (e.g. v0.3.3) whose lattice-server binary is downloaded and sha256-verified.
generate-website-chat 'true' or 'false'. 'true' emits the website chat library into <output-dir>/<website-chat-dir>.

Every one of these is required in a v2 run. In a v3 site run, embedding-endpoint, vector-precision and request-interval-ms apply only when search-mode has vectors, and chunk-lines / chunk-overlap only when chunk-strategy is lines; otherwise they are refused rather than ignored. That is why action.yml declares those five optional (''); the action still fails naming each one whenever the run needs it.

Conditionally required β€” required when their condition holds, and rejected when it does not (a silently ignored input is a misconfiguration).

Input Required when Description
embedding-model mock-embeddings is false Embedding model id.
embedding-api-key mock-embeddings is false API key for the embedding endpoint. Masked immediately.
previous-corpus-meta-url previous-corpus-url is set file:// or http(s):// URL of that corpus's .meta.json. It must declare the same model, and dims must match, else the cache is discarded with a warning.
website-chat-dir generate-website-chat is 'true' Directory for the website-chat library, relative to output-dir; not absolute, not outside it, not output-dir itself.

Optional β€” plumbing with defaults declared once, in action.yml.

Input Default Description
source-dir '' Workspace-relative directory holding an external git checkout to chunk instead of the workspace β€” see External sources. '' = the workspace.
exclude '' Newline-separated exclude globs applied after paths.
output-dir autoreporag-out Directory (relative to the workspace) where corpus, gzip and metadata are written.
output-name coderag Basename for outputs (<name>.jsonl, <name>.jsonl.gz, <name>.meta.json).
gzip true Also write a gzip -9 twin of the corpus.
mock-embeddings false Use deterministic sha256-seeded L2-normalized mock vectors (CI needs no secrets).
mock-dim 256 Vector dimensionality in mock mode.
batch-size 32 Texts per embeddings request.
max-retries 3 Attempts per embeddings request (700ms Γ— 2ⁿ backoff on transient failures).
max-chunks 0 Upper bound on chunks (0 = unlimited); truncates with a warning.
previous-corpus-url '' file:// or http(s):// URL of a previously published corpus (.jsonl or .jsonl.gz) for incremental reuse by chunk_hash. Requires previous-corpus-meta-url.
lattice-port 6334 Loopback port for the throwaway lattice-server.

Outputs

Output Description
corpus-file Absolute path of the written lattice-jsonl corpus.
corpus-gz-file Absolute path of the gzip twin (empty when gzip is false).
metadata-file Absolute path of the metadata JSON.
dim Vector dimensionality of the corpus.
points Number of points in the corpus.
embedded Chunks embedded fresh this run.
reused Chunks whose vectors were reused from previous-corpus-url.
sha256 sha256 of the raw corpus file.
website-chat-dir Absolute path of the emitted website-chat bundle (empty when generate-website-chat is 'false').
snapshot-file Absolute path of the LatticeDB snapshot (<output-name>.lattice; empty unless snapshot is 'true').
edges Number of graph edges in the corpus (0 in v2).

Scenarios

Scenario Trigger Secrets Key inputs Example
CI self-test any none mock-embeddings: 'true' this repo's ci.yml
PR dry run pull_request none mock-embeddings: 'true' β€” proves chunking/corpus still build, fork-safe examples/mock-ci.yml
Merge-to-main publish push: main embedding key embedding-model, embedding-api-key, publish step after examples/basic.yml, examples/publish-pages.yml
Incremental refresh push: main embedding key previous-corpus-url + previous-corpus-meta-url pointing at the last published corpus examples/publish-pages.yml

The action deliberately does not upload artifacts or publish anywhere β€” your workflow composes that (see Hosting the corpus), so the corpus can go to artifacts, Pages, releases, or your own bucket.

External sources (source-dir)

To build a corpus of a repository other than the one running the workflow (a dependency, a docs site, a book), check it out at a pinned commit and point source-dir at it:

- uses: actions/checkout@v7
- uses: actions/checkout@v7
  with:
    repository: rust-lang/book
    ref: <full commit sha>        # pin it: the corpus records this commit
    path: .sources/rust-book
    persist-credentials: false

- uses: Avarok-Cybersecurity/AutoRepoRAG@v2
  with:
    source-dir: .sources/rust-book
    paths: |
      src/**/*.md
    output-name: books-rust
    # ...the required inputs, with a prose chunk profile

paths are then relative to source-dir, and every chunk's repo and commit_sha come from that checkout: git rev-parse HEAD and remote.origin.url (https and ssh forms are normalised to owner/name). The workflow's own GITHUB_REPOSITORY / GITHUB_SHA are ignored, since they describe a different repository. The action refuses a source-dir that is absolute, escapes the workspace, is not the root of a git checkout (a plain subdirectory of your repo would silently inherit your repo's identity), has no commit, or has no origin remote it can parse.

Site corpora (v3)

v3 builds the corpus behind a website's search: a plain directory of files (a site's built, gitignored dist/), split at markdown headings, searchable by BM25 with no embeddings at all, and published as a LatticeDB snapshot that loads in about 2 ms in a page, a service worker or a Cloudflare Worker. GeoHarness calls it this way. v3 needs lattice-version β‰₯ v0.5.1.

v3 mode is on as soon as any v3 input is set; it then requires chunk-strategy, search-mode and snapshot. v2 runs (none of them set) behave exactly as before.

Input Required Meaning
files-dir no Workspace-relative directory of plain files to chunk instead of a git checkout. Git is never asked (it would hide a gitignored build output); paths / exclude apply relative to it. Exclusive with source-dir.
corpus-repo with files-dir owner/name stamped on every chunk (there is no checkout to derive it from).
corpus-commit with files-dir Full 40- or 64-hex commit id stamped on every chunk.
chunk-strategy in v3 lines (v2 windows; needs chunk-lines / chunk-overlap) or markdown: split at ATX headings, heading_path per chunk (["About","Contact"]), long sections split between paragraphs, never inside fenced code, tables or front matter (one of those larger than max-chunk-bytes fails naming file, line and size), and a next edge between consecutive chunks of a file. Setext headings are not recognised.
search-mode in v3 lexical (BM25 text_index, no vectors, no embedding call), vector (dense only) or hybrid (both). The collection records embedding.model whenever it has vectors.
vector-index with vectors hnsw or flat (exact scan; no graph to load).
vector-storage with vectors f32, f16 or int8. The server rounds on write; the corpus carries the stored values, checked against the local ones within that rounding.
snapshot in v3 'true' exports <output-name>.lattice (snapshot format 2: graph + BM25 postings + encoded vectors). Its embedded config must equal the jsonl header's, or the run fails.
max-snapshot-bytes with snapshot: 'true' Fail when the snapshot is larger, naming both sizes (26214400 = Cloudflare's 25 MiB per static asset).
payload-sidecar no JSON object {"<path>": {extra payload}}, path relative to files-dir (or the source root). Merged into every chunk of that file. A path not in the corpus, or a field the action writes (text, path, heading_path, …), is an error.
edges-file no JSON array of {"from": {"path", "chunk"?}, "to": {"path", "chunk"?}, "relation", "weight"}; chunk is the 0-based chunk index within the file (default 0). Resolved to point ids and written as lattice-jsonl edge lines; unknown paths, out-of-range chunks, self-loops and duplicates fail naming the entry.

payload-sidecar and edges-file paths may be absolute or workspace-relative.

Example: a website's search corpus

- run: npm run build            # writes dist/**/index.html + a dist/**/index.md twin per page,
                                # plus $RUNNER_TEMP/pages.json ({"about/index.md": {"url", "title", "lastmod"}})
- name: Build site search corpus
  id: corpus
  uses: Avarok-Cybersecurity/AutoRepoRAG@v3
  with:
    files-dir: dist
    corpus-repo: ${{ github.repository }}
    corpus-commit: ${{ github.sha }}
    paths: |
      **/*.md
    chunk-strategy: markdown
    max-chunk-bytes: '2000'          # bge-base reads 512 tokens
    search-mode: lexical
    snapshot: 'true'
    max-snapshot-bytes: '26214400'
    payload-sidecar: ${{ runner.temp }}/pages.json
    collection: site
    output-dir: dist/_search
    output-name: site
    lattice-version: v0.5.1
    generate-website-chat: 'false'

For hybrid, add vector-index, vector-storage, vector-precision, request-interval-ms and an embedding provider (below).

Embedding with Cloudflare Workers AI

Workers AI serves an OpenAI-compatible API, so it is just another embedding-endpoint (docs):

    embedding-endpoint: https://api.cloudflare.com/client/v4/accounts/${{ vars.CF_ACCOUNT_ID }}/ai/v1
    embedding-model: '@cf/baai/bge-base-en-v1.5'   # 768 dims, 512 input tokens
    embedding-api-key: ${{ secrets.CLOUDFLARE_API_TOKEN }}   # sent as Authorization: Bearer

The action POSTs {"model", "input": [...]} to <endpoint>/embeddings and reads data[].embedding (ordered by index when the items carry one, in response order when none do). Cloudflare errors arrive as {"success": false, "errors": [{"code", "message"}]}; code 3040 (out of capacity, HTTP 429) is retried, code 3036 (daily free allocation used up, also HTTP 429) fails at once, and 408 timeouts are retried (error codes). Model facts are from the bge-base-en-v1.5 page. OpenRouter and any other OpenAI-compatible endpoint work as before. The Cloudflare path is tested against a loopback server speaking the documented shapes, not a live account.

What a v3 run writes

<name>.jsonl (+ .gz), <name>.lattice when snapshot is 'true', and <name>.meta.json, which adds to the v2 fields: chunk_strategy, search_mode, text_field ("text", or null without a text index), vector_index, vector_storage (null when lexical), edges, and snapshot_bytes, snapshot_sha256, snapshot_format (2; all three null when snapshot is 'false'). A lexical corpus has dim 0 and model / endpoint null. Every chunk's payload also has heading_path (markdown) and the sidecar fields.

The jsonl and the snapshot are both byte-deterministic: two runs on the same input write the same sha256 and snapshot_sha256. Relation ids in the jsonl header are numbered in relation-name order, as lattice-db writes them in a snapshot. Before the snapshot is written it is round-tripped through the server: the collection is dropped, the snapshot imported in its place (POST /collections/<c>/import?mode=create), and its points_count, a probe query's hits and scores, and a second export's bytes must equal the first.

Query the snapshot with LatticeDB β‰₯ v0.5.0 (npm [email protected]) (LatticeHost.importSnapshot, then route('POST', '/collections/<c>/points/query', …)), with {"query": {"text": "free plan limits", "model": "bm25"}, "limit": 10, "with_payload": true}; see lattice-db's docs/edge-search.md for service workers and Workers.

Testing v3 locally

node --test test/integration/site.test.mjs runs the whole action on fixtures/site with the v0.5.1 release (downloaded and sha256-verified, on Linux or macOS), loads the snapshot into the v0.5.1 wasm build and checks BM25 ranking, the native round-trip (lexical, hybrid and vector mode) and that a second run writes the same jsonl and snapshot bytes. It needs network access to the GitHub release.

Output format

The corpus is lattice-jsonl v1 β€” LatticeDB's line-oriented interchange format. One JSON object per line, every object's keys sorted lexicographically at every nesting level, header first, points ascending by id. The output is byte-deterministic: identical inputs (in mock mode) produce an identical file, byte for byte.

Line 1 β€” header:

{"config":{"durability":"ephemeral","hnsw":{"ef":100,"ef_construction":200,"m":16,"m0":32,"ml":0.36067376022224085},"name":"coderag","relations":{},"vectors":{"distance":"cosine","size":256}},"dim":256,"edges":0,"format":"lattice-jsonl","points":412,"t":"header","version":1,"vectors":"inline"}

Every following line β€” one point per chunk:

{"id":1,"payload":{"chunk_hash":"b1946ac92492d2347c6235b4d2611184e2c8f861…","commit_sha":"da56736dc8e0f2c9b3a41c26f6b0a9f4c8f0e2ab","end_line":90,"language":"rust","path":"src/scheduler/mod.rs","repo":"your-org/your-repo","start_line":1,"text":"//! Scheduler entry points.\nuse crate::…"},"t":"point","vector":[0.0123456,-0.0987654,0.0456789]}
  • id β€” ordinal in (path asc, start_line asc) order, starting at 1.
  • chunk_hash β€” sha256(path \0 start_line \0 text); the identity used for incremental reuse.
  • text β€” the chunk content itself, so consumers can build LLM context without re-fetching files; path/start_line/end_line give you exact source links (blob/<commit_sha>/<path>#L<start>-L<end>).
  • Vectors are rounded to vector-precision significant digits and f32-cast before both server upsert and export, so the file and a live DB agree exactly.

The .meta.json manifest carries format, version, dim, points, files, embedded, reused, model, endpoint, repo, commit_sha, generated_at, bytes, gz_bytes, sha256, action_version, lattice_version β€” fetch this tiny file first as a preflight (cache key, download size, dim check) before pulling the corpus.

Consuming from a browser

The corpus round-trips into LatticeDB's WASM build. Note the WASM API has no import binding, so parse the lines and upsert in batches yourself:

import { LatticeDB } from 'https://avarok-cybersecurity.github.io/lattice-db/js/lattice-db.esm.js';

const db = await LatticeDB.init('https://avarok-cybersecurity.github.io/lattice-db/wasm/lattice_server_bg.wasm');

const res = await fetch('https://your-org.github.io/your-repo/coderag/coderag.jsonl.gz');
const text = await new Response(
  res.body.pipeThrough(new DecompressionStream('gzip')),
).text();

const lines = text.split('\n').filter(Boolean);
const header = JSON.parse(lines[0]);
await db.createCollection('coderag', header.dim);

let batch = [];
for (const line of lines.slice(1)) {
  const obj = JSON.parse(line);
  if (obj.t !== 'point') continue;
  batch.push({ id: obj.id, vector: obj.vector, payload: obj.payload });
  if (batch.length === 256) { await db.upsert('coderag', batch); batch = []; }
}
if (batch.length) await db.upsert('coderag', batch);

const hits = await db.search('coderag', queryVector, 5);
// ⚠ `score` is a cosine DISTANCE, not a similarity: 0.0 = identical,
// lower = closer. Do not expect "score β‰ˆ 1.0" for good matches.

Website chat library

generate-website-chat: 'true' writes a ready-to-host "Talk to the Repo" chat into <output-dir>/<website-chat-dir>/, next to your corpus:

File What it is
repo-chat.js The library: one ES module, Svelte runtime bundled, no dependencies.
repo-chat.css Its stylesheet. Every colour and font is a --arr-* property set from your theme.
lattice_server.js, lattice_server_bg.wasm The LatticeDB wasm build of lattice-version, downloaded from that release and verified against its lattice-db-wasm.sha256.
repo-chat.manifest.json library_version, lattice_version and the sha256 of every file above. No timestamp: the same inputs give the same bytes.

Retrieval runs in the visitor's browser (LatticeDB in wasm, one collection per corpus, cached in OPFS per commit); the question embedding, the rerank and the answer come from OpenRouter with the visitor's own key, kept in their browser. Each release also attaches the same bundle as repo-chat-<tag>.tar.gz (one repo-chat-<tag>/ directory) with a .sha256, for sites that vendor it instead of building a corpus.

Host the bundle on your own origin (it is CSP-friendly: no inline styles or scripts, theme values are applied through CSSOM) and open it with one call. Import it lazily so nothing loads until the visitor asks:

const BASE = '/repo-chat/2.2.1/';
let lib;
const load = () => (lib ??= import(`${BASE}repo-chat.js`));

// Every key is required; openRepoChat({}) throws one error listing them all.
const config = (COPY_EN) => ({
  mount: document.body,
  assets: { cssHref: `${BASE}repo-chat.css` },
  wasm: { jsUrl: `${BASE}lattice_server.js`, binUrl: `${BASE}lattice_server_bg.wasm` },
  corpora: [
    { id: 'code', gzUrl: 'https://your-org.github.io/your-repo/coderag/code.jsonl.gz', metaUrl: 'https://your-org.github.io/your-repo/coderag/code.meta.json' },
    { id: 'docs', gzUrl: 'https://your-org.github.io/your-repo/coderag/docs.jsonl.gz', metaUrl: 'https://your-org.github.io/your-repo/coderag/docs.meta.json' },
  ],
  provider: {
    apiUrl: 'https://openrouter.ai/api/v1',
    rerankModel: 'nvidia/llama-nemotron-rerank-vl-1b-v2:free',
    chatModel: 'nvidia/nemotron-3-ultra-550b-a55b:free',
    appTitle: 'Your Project: Ask the Codebase',
    referer: 'https://your.site',
    maxAttempts: 3,
    retryBaseMs: 700,
  },
  retrieval: { topK: 3, rerankMultiplier: 4, upsertBatch: 256 },
  storage: { keyPrefix: 'your-site-' },
  copy: { ...COPY_EN, starters: ['Where does a request enter the server?'] },
  brand: { productName: 'Your Project', motifSvg: null },
  theme: {
    bg: 'var(--bg)', bg2: 'var(--bg2)', card: 'var(--card)', border: 'var(--border)',
    borderStrong: 'var(--border-strong)', text: 'var(--text)', text2: 'var(--text-2)', text3: 'var(--text-3)',
    accent: 'var(--accent)', accentSoft: 'var(--accent-soft)', onAccent: 'var(--on-accent)',
    green: 'var(--green)', amber: 'var(--amber)', fontMono: 'ui-monospace, monospace',
    fontSans: 'system-ui, sans-serif', shadowLg: '0 18px 50px rgba(0, 0, 0, 0.5)',
  },
});

button.addEventListener('pointerenter', async () => {
  const { warmRepoChat, COPY_EN } = await load();
  warmRepoChat(config(COPY_EN)); // stylesheet + idle wasm prefetch, never a corpus
});
button.addEventListener('click', async () => {
  const { openRepoChat, COPY_EN } = await load();
  const chat = openRepoChat(config(COPY_EN)); // { close(), ready }
});
  • The embedding model is not configuration: it is read from each corpus's meta.json, and corpora built with different models or dimensions refuse to load with a message naming both.
  • Several corpora are searched with one question embedding (each returns topK Γ— rerankMultiplier candidates), merged by cosine distance, cut back to that many, and reranked once; each source receipt names its corpus.
  • The corpora must be served with CORS (GitHub Pages is). See website-chat/README.md for the full config reference, the theme keys and how to build and test the library.

Search mode (no API key, library 3.0)

mode: 'search' turns the chat into site search over v3 snapshots: BM25 in the visitor's browser, no key and no model call, results listed with their title, url and heading_path. With search.embedder set (a site-owned function whose model and dim match the corpus), vector and hybrid corpora are queried too (BM25 + dense, RRF). It needs the wasm of lattice-db β‰₯ v0.5.0, so emit the bundle with lattice-version: v0.5.0 or later. Every corpus must have been built with snapshot: 'true'. Full config: website-chat/README.md.

openRepoChat({ mode: 'search', mount: document.body,
  assets: { cssHref: '/repo-chat/repo-chat.css' },
  wasm: { jsUrl: '/repo-chat/lattice_server.js', binUrl: '/repo-chat/lattice_server_bg.wasm' }, // lattice-db >= v0.5.0
  corpora: [{ id: 'site', snapshotUrl: '/rag/site.lattice', metaUrl: '/rag/site.meta.json' }],
  search: { topK: 8, snippetChars: 160, embedder: null },
  storage: { keyPrefix: 'mysite-' }, copy: COPY_EN, brand: { motifSvg: null }, theme });

Library 3.0 makes mode a required key: existing answer-mode configs add mode: 'answer'.

Rate limits & incremental refresh

A first full run on a mid-sized repo is a few hundred embedding requests (ceil(chunks / batch-size)), paced by request-interval-ms (2500 ms between request starts suits free-tier endpoints; ~9,000 chunks β‰ˆ 300 requests β‰ˆ 15–20 minutes). Transient failures (HTTP 429/5xx and 200-with-error bodies, common on saturated free tiers) retry up to max-retries times with 700ms Γ— 2ⁿ backoff.

After the first publish, pass previous-corpus-url pointing at the published corpus and previous-corpus-meta-url pointing at its .meta.json. Vectors are reused by chunk_hash, so steady-state runs embed only chunks whose content changed β€” typically a handful of requests per merge. Guardrails, all fail-safe to a full re-embed with a warning:

  • the .meta.json at previous-corpus-meta-url must declare the same model;
  • dimensionality must match (also re-checked against the first live response);
  • an unreachable/corrupt previous corpus is simply discarded.

Budget levers: chunk-lines (bigger chunks β†’ fewer requests), vector-precision (smaller corpus file), max-chunks (hard cap), request-interval-ms (pacing).

Multi-corpus hosting (100 MB cap)

GitHub rejects any single pushed file over 100 MB, and a Pages site may be at most 1 GB in total. Treat the per-file cap as the binding one and build one corpus per source rather than one ever-growing file:

Corpus source-dir output-name Chunk profile
your code '' code code windows (e.g. 90 / 15 lines)
your docs '' (with paths: docs/**) docs prose windows
a book or dependency .sources/<name> books-<name> prose windows
  • Give each corpus its own output-name and its own previous-corpus-url / previous-corpus-meta-url pair, so each reuses only its own vectors.

  • Fail the publish before the cap, not at it. Leave headroom for growth:

    max=$((95 * 1024 * 1024))
    size=$(stat -c %s "$CORPUS_GZ")
    [ "$size" -le "$max" ] || { echo "::error::$CORPUS_GZ is $size B (> 95 MiB)"; exit 1; }
  • Lower vector-precision (e.g. 4) to shrink a large code corpus; vectors dominate the file size.

  • Publish every corpus in the same job when you force-push an orphan gh-pages branch: that push replaces the whole site, so a corpus built in another job would be deleted. Corpora built on different schedules (a book rebuilt only when its pin moves) should instead check out the current gh-pages tree and replace only their own files.

  • A browser client loads each corpus into its own collection (or one collection with distinct ids per corpus) and merges results by distance.

Hosting the corpus

Where you publish determines who can fetch it β€” a browser app needs CORS:

Host Browser CORS Lifetime Notes
GitHub Pages (orphan gh-pages) βœ… Access-Control-Allow-Origin: * no TTL Best for web apps: stable URL, free, served gzip-friendly.
Release assets ❌ no CORS headers permanent Great for CLI/server consumers via releases/latest/download/…; not fetchable from browser JS.
Actions artifacts ❌ auth required ≀ 90 days CI-internal handoff only (API token needed to download).

The Pages pattern β€” merge to main β†’ build incrementally β†’ force-push a single-commit orphan gh-pages branch β€” is exactly examples/publish-pages.yml. One-time setup: repo Settings β†’ Pages β†’ Deploy from a branch β†’ gh-pages / root. Your corpus then lives at a stable, CORS-open URL:

https://<owner>.github.io/<repo>/coderag/coderag.jsonl.gz
https://<owner>.github.io/<repo>/coderag/coderag.meta.json

Versioning

  • @v2 is a moving major tag: every v2.x.y release re-points it, as long as it is the newest v2 release (semver-compatible changes only). Pin the full commit SHA if you want absolute immutability: uses: Avarok-Cybersecurity/AutoRepoRAG@<sha> # v2.x.y.
  • @v1 is frozen at v1.0.0 and receives no further changes.
  • lattice-version is yours to pin (v0.3.3 is the version this action's CI uses) and the downloaded server binary is sha256-verified β€” a new lattice-db release can never silently change your corpus. A weekly canary in this repo's CI runs against the newest lattice-db release to catch drift early.
  • Format guarantee: the corpus stays lattice-jsonl format version 1 with the documented payload keys (unchanged from v1). A corpus format break means a new action major version.

Migrating from v1 to v2

v2 changes the inputs only; the corpus format and the outputs are unchanged.

  1. Change @v1 to @v2.

  2. State every input that used to have a default and now does not. These are the v1 defaults; stating them keeps v1's chunking, precision, pacing and server version:

    embedding-endpoint: https://openrouter.ai/api/v1
    collection: coderag
    chunk-lines: '90'
    chunk-overlap: '15'
    max-chunk-bytes: '16384'
    vector-precision: '6'
    request-interval-ms: '2500'
    lattice-version: v0.3.3
    generate-website-chat: 'false'
  3. If you use previous-corpus-url, add previous-corpus-meta-url. v1 derived it from the corpus URL (<name>.jsonl.gz β†’ <name>.meta.json); v2 reads only the URL you give it.

  4. Nothing else changes for a workflow that chunks its own repository. The new source-dir input is opt-in.

Security

See SECURITY.md. In short: the embedding key crosses only via env, is masked immediately, and is never persisted to any output; the lattice-server binary is release-pinned + checksum-verified and listens on loopback only; the action has zero npm dependencies; report vulnerabilities to [email protected].

License

Apache-2.0 Β© 2026 Avarok Cybersecurity.

Contributing

Issues and PRs welcome. Before opening a PR:

  1. node --check src/*.mjs and node --test test/unit/*.test.mjs must pass (CI lints every .mjs and workflow and runs the unit tests).
  2. Run the mock e2e locally (scripts/local-dry-run.sh): the action is plain Node β€” no build step.
  3. Keep the zero-dependency rule for the action: no root package.json, no runtime node_modules. The website chat under website-chat/ has build-time devDependencies only (Svelte, Vite, Playwright) and ships as the committed website-chat/dist/; CI rebuilds it and fails on any difference, so run npm ci && npm run build there after changing it.
  4. CHANGELOG.md follows Keep a Changelog β€” add your entry under [Unreleased].

About

🧠 GitHub Action that embeds your repository's source code into LatticeDB and exports a browser-loadable lattice-jsonl RAG corpus

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages