agentleFS
Ontos-AIOntos-AI/knowhere/AGENTS.md

knowhere

AGENTS.md3.7k starsChanged 7 months agoApache-2.0View on GitHub

Codex agents and contributors must create branches with this format: - type should be lowercase and should normally be one of: feat, fix, refactor, chore, docs, test, perf, ci, build, or revert. - user should identify the human owner of the work, usually their GitHub username. Do not use a generic tool name such as codex. - description should be short, lowercase, and kebab-case. SDKs live in standalone repos: - Python SDK → Ontos-AI/knowhere-python-sdk - Node SDK → Ontos-AI/knowhere-node-sdk

  • Reads credentials

Trending

Quiet since September.about the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 0 mentionsMay 2026: 5 mentionsJun 2026: 2 mentionsJul 2026: 7 mentionsAug 2026: 1 mentionSep 2026: 2 mentionsOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the Ontos-AI/knowhere repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about Ontos-AI/knowhere

The biggest 5 of 17 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 17

Talked about on GitHub and Hacker News (17 times).

On GitHub · 16

11 more on GitHub
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

The file

We split this AGENTS.md into the rules it gives an agent

6 rules. About 0 are common, 1 is distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    TOC-first: If a DOCX TOC exists (structure.toc_parser.build_docx_toc_hierarchies), use it as ground truth for heading levels.

    line 160
  2. Very specific:

    LLM smart parse: When smart_title_parse=True, send candidate headings to the hierarchy model (HIERARCHY_LLM_MODEL or NORMOL_MODEL) for …

    line 163
  3. Very specific:

    After parsing and chunk conversion, results are persisted to ~/.knowhere/{corpus_name}/.

    line 231
  4. Very specific:

    Default agentic path is agent_explore: a corpus.* tool loop run by the resolved harness (AGENT_EXPLORE_HARNESS, default cursor_sdk).

    line 585
  5. Very specific:

    When total_chunks <= top_k, skips the full pipeline and returns all chunks directly (router: small_corpus_all).

    line 602
  6. Distinctive:

    When splitting tables or modifying document structure:

    line 638

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

Repository Instructions

Branch Naming

Codex agents and contributors must create branches with this format:

<type>/<user>/<description>
  • type should be lowercase and should normally be one of: feat, fix, refactor, chore, docs, test, perf, ci, build, or revert.
  • user should identify the human owner of the work, usually their GitHub username. Do not use a generic tool name such as codex.
  • description should be short, lowercase, and kebab-case.

Examples:

feat/alice/add-document-preview
fix/bob/chunk-position-range
refactor/chris/extract-chunk-converter

Project Structure

knowhereapi-main/
├── apps/
│   ├── api/          # FastAPI REST API (port 5005)
│   │   ├── app/
│   │   │   ├── api/v1/routes/   # Endpoint handlers
│   │   │   ├── services/        # Business logic (auth, ingestion, billing)
│   │   │   └── repositories/    # Data access layer
│   │   └── main.py              # Entrypoint, runs migrations on start
│   ├── worker/       # Celery worker for async document processing
│   │   ├── app/
│   │   │   ├── services/document_parser/  # All parser modules
│   │   │   └── services/workload/         # Celery task handlers
│   │   └── worker.py                      # Celery entrypoint
│   ├── web/          # Frontend (separate repo: knowhere-dashboard)
│   └── docs/         # Internal documentation
├── packages/
│   └── shared-python/shared/    # Shared library (pip: knowhere-shared)
│       ├── models/database/     # SQLAlchemy ORM models
│       ├── models/schemas/      # Pydantic request/response schemas
│       ├── services/retrieval/  # Core retrieval engine
│       ├── services/chunks/     # DataFrame → ChunkPayload conversion
│       ├── services/ai/         # LLM prompt service & AI client
│       ├── services/http/       # Public URL validation and outbound HTTP
│       ├── services/redis/      # Redis state, key language, and retry policy
│       ├── services/quota/      # Shared token-pool quota primitives
│       └── utils/               # Generic text, chunk, and API helpers
└── deploy/                      # Docker Compose & deployment scripts

SDKs live in standalone repos:


End-to-End Pipeline Overview

flowchart TB
    subgraph INGEST["① Document Ingestion (API)"]
        Upload["POST /v1/documents"] --> Job["Create Job + S3 Upload"]
        Job --> Queue["Celery Task Queue"]
    end

    subgraph PARSE["② Document Parsing (Worker)"]
        Queue --> Router["parse_service.checkerboard_parse_output"]
        Router --> Profiler["profiling.doc_profiler.profile_document"]
        Profiler --> PDF["formats.pdf.parser → MinerU"]
        Profiler --> DOCX["formats.docx.parser.parse_docx"]
        Profiler --> PPTX["formats.pptx.parser → iLoveAPI → PDF"]
        Profiler --> XLSX["formats.excel.table_parser.parse_xlsx"]
        Profiler --> MD["formats.markdown.parser.parse_md"]
        Profiler --> IMG["formats.image.parser.parse_image"]
        PDF --> DF["pd.DataFrame (ALL_DF_COLS)"]
        DOCX --> DF
        PPTX --> DF
        XLSX --> DF
        MD --> DF
        IMG --> DF
    end

    subgraph CONVERT["③ Chunk Conversion"]
        DF --> Converter["dataframe_chunk_converter.dataframe_to_chunks"]
        Converter --> Chunks["list[ChunkPayload]"]
    end

    subgraph PUBLISH["④ Publication (shared)"]
        Chunks --> Dedup["RetrievalPublicationService._dedup_chunks_by_content"]
        Dedup --> DocState["publish_document_state → Documents/Sections/Chunks"]
        DocState --> Graph["publish_document_graph → GraphNodes/GraphEdges"]
    end

    subgraph RETRIEVE["⑤ Retrieval (shared)"]
        Query["POST /v1|/v2 retrieval/query"] --> Pipeline["run_retrieval_query"]
        Pipeline --> Classic["classic_topk / small_corpus (use_agentic=False)"]
        Pipeline --> Explore["agent_explore (use_agentic unset/true)"]
        Explore --> Cursor["AGENT_EXPLORE_HARNESS=cursor_sdk"]
        Explore --> Own["AGENT_EXPLORE_HARNESS=openai"]
        Classic --> Channels["map_unit_discovery: path+content BM25 -> RRF"]
        Channels --> Rank["rank_retrieval_candidates"]
        Cursor --> Tools["corpus.* tools + harness.run_episode"]
        Own --> Tools
        Rank --> Assemble["assemble_retrieval_results"]
        Tools --> Assemble
        Assemble --> Results["Cited Evidence Results"]
    end

Stage ②: Document Parsing Pipeline

Entry Point

apps/worker/app/services/document_parser/parse_service.py → checkerboard_parse_output()

This is the typed ParseOutput entry for all file types. The parser flow:

  1. Profiles the document via profiling.doc_profiler.profile_document(). PDF profiling uses document_agent as the single PyMuPDF feature source, then runs VLM coarse classification with two fields: open semantic category (for example, Financial Prospectus) and routing-only routing_category (atlas/scanned/slides/generic). Oversized non-atlas PDFs additionally run the structural anatomy stage once at the entry point and pass the resulting shard plan to PDF parsing.
  2. Routes to the appropriate parser based on file extension.
  3. Post-processes: cleans up unreferenced images, compresses PNG→JPG.
  4. Returns typed parse output with task-local artifact paths.

Parser Routing Table

ExtensionParser ModuleStrategy
.pdfformats.pdf.parser.parse_pdfsDOC_PROFILE category dispatch: atlas → atlas parser; oversized with entry anatomy → shard MinerU; otherwise MinerU API → Markdown parser → structure.layout_parser.pred_titles
.docxformats.docx.parser.parse_docx + convert_doc2dicsOXML iteration → heading detection → hierarchical tree
.docconversion.legacy_converter.doc_to_docx → .docx pipelineLibreOffice headless conversion first
.pptxformats.pptx.parser.parse_pptxiLoveAPI PPTX→PDF → MinerU pipeline
.xlsxformats.excel.table_parser.parse_xlsxSheet-by-sheet HTML table extraction
.xlsconversion.legacy_converter.xls_to_xlsx → .xlsx pipelineLibreOffice conversion first
.mdformats.markdown.parser.parse_mdMarkdown heading parsing + LLM summaries
.txtformats.text.parser.parse_texts → Markdown parserRead lines then route to MD parser
.png/.jpgformats.image.parser.parse_imageVLM image description + OCR
.fragmentformats.fragment.parser.parse_fragmentRaw text fragment ingestion

Heading Detection: structure.layout_parser.pred_titles()

The core hierarchical recognition module. Determines heading levels using:

  1. TOC-first: If a DOCX TOC exists (structure.toc_parser.build_docx_toc_hierarchies), use it as ground truth for heading levels.
  2. Regex patterns: Match numbered headings like 1.2.3, 第X章, (一).
  3. LLM smart parse: When smart_title_parse=True, send candidate headings to the hierarchy model (HIERARCHY_LLM_MODEL or NORMOL_MODEL) for level assignment.
  4. Font clustering (PDF): K-means on span heights from MinerU layout.json to group headings into 5 discrete tiers.

DOCX Parsing Deep Dive: formats/docx/parser.py

flowchart LR
    A[load_file_bytes] --> B[iter_block_items]
    B --> C{Element Type}
    C -->|CT_P| D[Paragraph + Images]
    C -->|CT_Tbl| E[Table + Cell Images]
    C -->|sdt| F[TOC Detection]
    D --> G[pred_titles → heading levels]
    G --> H[Build hierarchical tree]
    E --> I[table2html → HTML]
    H --> J[get_leaf_dics → flatten]
    J --> K[postprocess_leaf_dics → LLM summaries]
    K --> L[convert_doc2dics → DataFrame]

Key logic in parse_docx():

  • iter_block_items(): Iterates OXML body elements, yielding (ele_num, content, label, meta) tuples. Labels: PTXT, TABLE, IMAGE, TOC-AREA.
  • Heading stack: Maintains headings_stack with {heading, content[], level} dicts. New headings pop the stack to their parent level.
  • Image dedup: Uses perceptual_hash() for document-level visual dedup. Cached in _seen_images dict.
  • Table handling: table2html() converts python-docx Table to HTML with accurate rowspan/colspan via direct OXML inspection.

PDF Parsing: DOC_PROFILE + MinerU Pipeline

flowchart LR
    PDF[profiling.doc_profiler.profile_document] --> Probe[document_agent probe_page_features]
    Probe --> Coarse[VLM coarse category]
    Coarse -->|atlas| Atlas[formats.atlas.parser]
    Coarse -->|oversized generic/scanned/slides| Anatomy[document_agent structural anatomy + shard_plan]
    Coarse -->|standard| MinerU[MinerU Cloud API]
    Anatomy --> Shards[Shard MinerU pipeline]
    Shards --> MDFile[Markdown + layout.json]
    Atlas --> Chunks[Atlas page chunks]
    MinerU --> MDFile
    MDFile --> MDParser[formats.markdown.parser.parse_md]
    MDParser --> EvalHeadings[eval_md_headings + layout.json]
    EvalHeadings --> PredTitles[structure.layout_parser.pred_titles]
    PredTitles --> Chunks[Hierarchical Chunks]

LLM Models Used

TaskConfig KeyDefault Model
Text/table summarizationNORMOL_MODELdeepseek-chat
Heading hierarchy recognitionHIERARCHY_LLM_MODELFalls back to NORMOL_MODEL
Image description / OCR / classification (VLM)IMAGE_MODELdeepseek-flash
Page-memory chart/table bbox (VLM)ASSET_MODELFollows IMAGE_MODEL when empty
PDF coarse classificationIMAGE_MODELdeepseek-flash

Persisted Document Corpus Schema (On-Disk Output)

After parsing and chunk conversion, results are persisted to ~/.knowhere/{corpus_name}/. This on-disk structure is the authoritative persisted format — the intermediate DataFrame is an internal detail. Below is the complete schema.

Corpus-Level Directory Layout

~/.knowhere/{corpus_name}/
├── knowledge_graph.json           # corpus-wide graph: file metadata + cross-doc edges
├── chunk_stats.json               # Per-chunk retrieval hit analytics {chunk_id → stats}
├── {source_file_name}/            # One directory per ingested document
│   ├── chunks.json                # All parsed chunks for this document
│   ├── doc_nav.json               # Hierarchical navigation tree for agentic retrieval
│   ├── manifest.json              # Parse metadata + full heading hierarchy
│   ├── {source_file_name}.zip     # Archived original + parsed assets
│   ├── images/                    # Extracted image assets (PNG/JPG)
│   ├── tables/                    # Extracted table assets (HTML)
│   ├── preds_3_llm_base.csv       # Debug: heading predictions (base LLM pass)
│   ├── preds_4_llm_final.csv      # Debug: heading predictions (final LLM pass)
│   ├── preds_5_final_output.csv   # Debug: final parser DataFrame output
│   └── toc_hierarchies.json       # Debug: extracted TOC structure (DOCX only)

knowledge_graph.json — Corpus-Wide Graph

{
  "version": "2.0",
  "corpus_id": "test-corpus",
  "stats": { "total_files": 3, "total_chunks": 364, "total_cross_file_edges": 0 },
  "files": {
    "AI_Security_Report.docx": {
      "chunks_count": 155,
      "types": { "image": 13, "table": 1, "text": 141 },
      "top_keywords": ["model", "security", "ai", "operations", "artificial_intelligence"],
      "top_summary": "This document includes: Legal Notice, Foreword, 1. Overview, ...",
      "importance": 0.3,
      "created_at": "2026-05-09T09:14:12.422208+00:00"
    }
  },
  "edges": []
}
FieldDescription
files.{name}.top_keywordsTF-IDF top keywords across all chunks (used for cross-doc edge scoring)
files.{name}.top_summaryAuto-generated outline of top-level headings (injected by load_nav_top_summary())
files.{name}.importanceBase importance score (feeds compute_importance_score() in ranking)
edges[]Cross-document edges with {source, target, weight, shared_keywords} when keyword overlap ≥ 0.8

chunk_stats.json — Retrieval Hit Analytics

{
  "2e2beffc-90b2-5429-8ee7-3c49260a1204": {
    "hit_count": 0,
    "first_hit": null,
    "last_hit": null,
    "created_at": "2026-05-09T09:14:12.423011+00:00"
  }
}

Keyed by chunk_id. hit_count and last_hit feed into importance_norm_score for retrieval ranking boost.

chunks.json — Per-Document Chunk Records

The core persisted data. Contains {"chunks": [...]} — an ordered array of chunk objects. Three chunk types exist:

Text Chunk

{
  "chunk_id": "d88e4c47-3c48-5bdf-b849-693c00453021",
  "type": "text",
  "content": "AI Security Report\n\nThe image displays a tech theme...\n[images/image-1 ai_model.png]\n",
  "path": "test_kb/AI_Security_Report.docx/1. Overview/1.1 Key Findings",
  "metadata": {
    "length": 220,
    "summary": "",
    "page_nums": [],
    "tokens": ["model", "technology", "market", "research", "report"],
    "keywords": [],
    "connect_to": [
      {
        "target": "2e2beffc-90b2-5429-8ee7-3c49260a1204",
        "relation": "embeds",
        "ref": "[images/image-1 ai_model.png]",
        "position": { "start": 109, "end": 135 }
      }
    ]
  }
}

Image Chunk

{
  "chunk_id": "2e2beffc-90b2-5429-8ee7-3c49260a1204",
  "type": "image",
  "content": "\nThe image displays a tech theme...\n[images/image-1 ai_model.png]\n",
  "path": "images/image-1 ai_model.png",
  "metadata": {
    "length": 121,
    "summary": "image-1\nThe image displays a tech theme...",
    "page_nums": [],
    "file_path": "images/image-1 ai_model.png",
    "keywords": [],
    "tokens": []
  }
}

Table Chunk

{
  "chunk_id": "a5c3d644-479a-51f9-9a54-ff6789c1f6e8",
  "type": "table",
  "content": "<table border='1'><tr><td>Architecture Layer</td><td>AI Capabilities</td></tr>...</table>",
  "path": "tables/table-1 ai_architecture.html",
  "metadata": {
    "length": 488,
    "summary": "table-1\nThe table shows the architecture layers...",
    "page_nums": [],
    "file_path": "tables/table-1 ai_architecture.html",
    "keywords": ["AI_Capabilities", "Security_Engine", "Intelligent_Collaboration"],
    "tokens": []
  }
}

Chunk Field Reference

FieldTypeDescription
chunk_idstrDeterministic UUID5 hash from content (gen_str_codes) — enables cross-doc dedup
typestr"text" / "image" / "table"
contentstrRaw text, VLM description + asset ref, or HTML <table>
pathstrHierarchical path: {kb}/{file}/{section1}/{section2}/... for text; images/... or tables/... for assets
metadata.lengthintCharacter count of content
metadata.summarystrLLM summary (images/tables: "image-N\n{description}")
metadata.tokenslist[str]Pre-tokenized Chinese terms for BM25 retrieval
metadata.keywordslist[str]LLM-extracted keywords (semicolon-split from DataFrame)
metadata.page_numslist[int]Source page numbers (PDF only)
metadata.file_pathstrRelative asset path for images/tables
metadata.connect_tolist[ConnectionValue]Cross-chunk references (text→image/table embeddings)
metadata.connect_to[].targetstrTarget chunk_id
metadata.connect_to[].relationstr"embeds" (inline asset) or "related"
metadata.connect_to[].refstrOriginal reference string: "[images/image-1.png]"
metadata.connect_to[].position{start, end}Character offset of the reference in content

doc_nav.json — Hierarchical Navigation Tree

Used by agentic retrieval for 2-level section browsing. Structure:

{
  "version": "1.0",
  "file_name": "AI_Security_Report.docx",
  "stats": { "total_chunks": 155, "text_chunks": 141, "image_chunks": 13, "table_chunks": 1, "max_depth": 4 },
  "sections": [
    {
      "title": "1. Overview",
      "path": "test_kb/AI_Security_Report.docx/1. Overview",
      "level": 1,
      "summary": "This section covers: 1.1 Key Findings, 1.2 Recommendations",
      "chunk_count": 6,
      "children": [
        {
          "title": "1.1 Key Findings",
          "path": "test_kb/.../1. Overview/1.1 Key Findings",
          "level": 2,
          "summary": "This section covers: Supply Side Perspective, Demand Side Perspective...",
          "chunk_count": 4,
          "children": [...]
        }
      ]
    }
  ],
  "resources": {
    "images": [{ "path": "images/image-1 ai_model.png", "summary": "image-1 The image displays a tech theme..." }],
    "tables": [{ "path": "tables/table-1 ai_architecture.html", "summary": "table-1 The table shows..." }]
  }
}

manifest.json — Parse Metadata & Heading Hierarchy

{
  "version": "2.0",
  "job_id": "AI_Security_Report.docx",
  "source_file_name": "AI_Security_Report.docx",
  "processing_date": "2026-05-09T07:46:00.395048Z",
  "statistics": { "total_chunks": 155, "text_chunks": 141, "image_chunks": 13, "table_chunks": 1 },
  "HIERARCHY": {
    "Root": {},
    "1. Overview": {
      "1.1 Key Findings": { "Supply Side Perspective": {}, "Demand Side Perspective": {} },
      "1.2 Recommendations": {}
    },
    "2. History of AI in Cybersecurity": { "...": {} }
  }
}

The HIERARCHY field is a nested dict representing the full heading tree discovered by structure.layout_parser.pred_titles(). Each key is a heading title; its value is a dict of child headings (empty {} for leaf nodes).

Intermediate DataFrame (ALL_DF_COLS)

Parsers internally produce a pd.DataFrame with columns: content, path, type, length, keywords, summary, know_id, tokens, connectto, addtime, page_nums. This is converted to ChunkPayload objects via dataframe_chunk_converter.dataframe_to_chunks() before persisting to chunks.json. The DataFrame is a transient internal format; debug CSVs (preds_*.csv) are saved alongside for troubleshooting.


Stage ④: Publication — Database Schema

Core Tables

documents

ColumnTypeDescription
document_idString(36) PKdoc_{uuid_hex[:12]}
user_idText FK → user.idOwner
namespaceString(255)Isolation scope (default: "default")
statusString(32)active / archived
current_job_result_idString(36) FKPoints to active revision
source_file_nameTextOriginal filename

document_sections

ColumnTypeDescription
section_idString(36) PKsec_{uuid_hex[:12]}
document_idFK → documentsParent document
job_result_idFK → job_resultsRevision
parent_section_idFK → selfParent section (tree structure)
section_pathText UNIQUE(doc+rev+path)"file.docx / Chapter 1 / Section 1.1"
section_titleTextHeading text
section_levelIntegerDepth in hierarchy (1-based)
summaryTextSection summary
sort_orderIntegerDisplay order

document_chunks

ColumnTypeDescription
idString(36) PKdchk_{uuid_hex[:12]}
chunk_idString(64)Content hash (deterministic dedup key)
document_idFK → documentsParent document
section_idFK → document_sectionsParent section
chunk_typeString(64)text / image / table
contentTextChunk content (text/HTML)
content_search_textTextPre-tokenized for BM25 content channel
path_search_textTextPre-tokenized for BM25 path channel
term_search_textTextPre-tokenized for term/grep channel
source_chunk_pathTextOriginal parser path
file_pathTextAsset reference (images/x.jpg)
chunk_metadataJSONKeywords, tokens, connect_to, etc.
sort_orderIntegerDisplay order

graph_nodes

ColumnTypeDescription
node_idString(128) PKdoc:{document_id}
node_kindString(32)document (only doc-level nodes)
owner_document_idFK → documentsSource document
propertiesJSON{source_file_name, top_keywords, chunks_count, types, top_summary}

graph_edges

ColumnTypeDescription
edge_idString(160) PKrelated:{doc_a}<->{doc_b} (sorted pair)
edge_kindString(32)related
source_node_id / target_node_idFK → graph_nodesConnected docs
weightFloatKeyword overlap score (≥ 0.8 threshold)
propertiesJSON{shared_keywords, connection_count}
is_directedBooleanAlways False for related edges

Publication Logic

RetrievalPublicationService.publish_document_state():

  1. Dedup: Cross-document content-hash dedup via _dedup_chunks_by_content.
  2. Section tree: Builds DocumentSection tree from chunk paths, creating ancestor sections top-down.
  3. Search text: Generates 3 search text channels per chunk:
    • content_search_text: Tokenized content + summary
    • path_search_text: Tokenized file name + section path + summary
    • term_search_text: Raw content + path for substring grep
  4. Graph: DocumentGraphService.publish_document_graph() creates doc-level GraphNode with TF-IDF keywords, then keyword-overlap GraphEdges to peer documents (min 3 shared keywords, score ≥ 0.8).

Stage ⑤: Retrieval Engine

Entry Point

shared/services/retrieval/app_service.py → run_retrieval_query()

Core retrieval internals are grouped by ownership:

  • execution/: request shaping, route selection (classic / agent_explore / small_corpus), and public response projection.
  • search/: map_unit_discovery (persisted map-unit BM25 discovery; incomplete or incompatible indexes raise), scoring, section filters, candidate ranking.
  • hydration/: row/path/reference hydration, inline assets, and result assembly.
  • agent_explore/ + agent_tools/: agent retrieval when use_agentic is on. Harness is cursor_sdk (Cursor) or openai (Knowhere's own). Map-nav is archived under deprecated/mapnav/.
  • trace/: DecisionTraceStep mapping and TraceRecorder.
  • graph/: document graph publication/query support.
  • stats/: retrieval hit recording.

Retrieval Switch and Agent Modes

Per-request use_agentic only turns agent retrieval on or off: False → classic top-K (map-unit BM25); None/True → agent_explore. When agent retrieval is on, AGENT_EXPLORE_HARNESS selects Cursor (cursor_sdk) or Knowhere's own harness (openai).

Classic Mode (map-unit BM25)

Primary path is search.map_unit_discovery.map_unit_discovery: Python BM25Okapi over the persisted document_map_unit_tokens index, path and content channels only, fused by RRF. An incomplete or incompatible map-unit index raises.

flowchart LR
    Q[Query] --> P["Path channel: BM25 over document_map_unit_tokens (channel=path)"]
    Q --> C["Content channel: BM25 over document_map_unit_tokens (channel=content)"]
    P --> RRF["RRF Fusion (k=60)"]
    C --> RRF
    RRF --> Rank[rank_retrieval_candidates]
    Rank --> Assemble[hydration.result_assembly]

Channel weights (default): path=1.0, content=2.0. RRF formula: score = weight / (k + rank + 1) per channel, summed across channels, k=60.

There is no scored term channel in this primary path. Chunk term_search_text is persisted at publish time and is read by corpus.grep, not by classic discovery.

Agent-explore Mode (default)

Default agentic path is agent_explore: a corpus.* tool loop run by the resolved harness (AGENT_EXPLORE_HARNESS, default cursor_sdk). Finish refs are resolved to chunks, then assembled like classic. Map-nav is archived at deprecated/mapnav/ and is no longer a live route.

Result Assembly

hydration.result_assembly.assemble_retrieval_results():

  1. Filters by exclude_document_ids and exclude_sections
  2. Hydrates connect_to targets
  3. Filters by allowed_chunk_types while retaining body chunks connected to a requested image/table
  4. Cleans asset path references from content
  5. Public projection builds source: {document_id, source_file_name, section_path} plus page_nums for chunk_type=page when present

Small Corpus Optimization

When total_chunks <= top_k, skips the full pipeline and returns all chunks directly (router: small_corpus_all).

Caching

Results are cached per (user_id, namespace, query, top_k, filters) via cache_service. Cache version is checked before execution; cache is written after successful retrieval.


Analytics Tables

retrieval_hit_stats

Tracks per-chunk and per-document retrieval usage. hit_count and last_hit_at feed into compute_importance_score() for ranking boost.

retrieval_runs / retrieval_steps

Append-only agentic retrieval analytics. One retrieval_runs row per query, with child retrieval_steps rows recording each agent action, its input/output, latency, and token usage.


Key Implementation Patterns

Deterministic Chunk IDs

know_id = gen_str_codes(pure_text) — SHA-based hash of text content only (excludes image/table asset refs). This enables cross-document dedup: identical text in different uploads produces the same chunk_id.

Plan-then-Act DOM Mutation

When splitting tables or modifying document structure:

  1. Pass 1 (Investigate): Collect mutation targets into a static plan
  2. Pass 2 (Execute): Apply mutations in reverse order to avoid index shifting

Image Dedup: Perceptual Hash

perceptual_hash() computes a visual fingerprint. Images with identical hashes are deduplicated within a document, with cached metadata reused.

Asset Lifecycle (Deterministic UIDs)

IMAGE_[hash(content+seq)]_IMAGE — identical images at different positions receive unique IDs. Context chaining prevention scans backward past binary identifiers to find the nearest valid text.

LLM Constraints

  • DeepSeek JSON mode: Requires the word "json" in the prompt when response_format is json_object
  • Streaming robustness: Concatenate delta.content only if not None
  • Token pool rotation: Ali API keys support per-token RPM limits, cooldown, and inline retry with next available token

Development & Debugging

Local Setup

uv sync --all-packages
cp apps/api/.env.example apps/api/.env
cp apps/worker/.env.example apps/worker/.env
./deploy/local-dev/start-dev.sh        # PostgreSQL, Redis, LocalStack
cd apps/api && uv run main.py          # API on :5005
cd apps/worker && uv run worker.py     # Celery worker

Debug Scripts (Worker)

PDF/PPT debug is track-split (not a single all-format one-shot):

ScriptPurpose
debug_text_track.pyTEXT-TRACK (chunk) staged debug: --stop-at profile/mineru/hierarchy/full, --clean
page_memory/debug_pm_stage0..5.pyPAGE-TRACK (page_memory) staged debug (bootstrap → finalize); shared --clean wipes output dir
debug_retrieval.pyRetrieval debug
_debug_publish.pyOptional --run-db publish helper for the scripts above

Quality Checks

make lint          # Ruff lint
make lint-fix      # Auto-fix safe issues
make typecheck     # Pyright across api, worker, shared
make check         # Both lint + typecheck

Local Endpoints

ServiceURL
APIhttp://localhost:5005
OpenAPI docshttp://localhost:5005/docs
PostgreSQLlocalhost:5432
Redislocalhost:6379
LocalStack (S3)http://localhost:4566

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.