ir.strategy¶
Indexing strategies — the “what do we index?” seam.
An IndexingStrategy decomposes one artifact into an
IndexPlan: the filter_fields (hard-filterable metadata,
not embedded) and a list of Surface (embeddable units). This
is the central extensibility point of ir: a naive corpus uses
WholeText; a structured corpus (a package) decomposes into several
heterogeneous surfaces so a query can match the right part of an artifact,
and constrains candidates by metadata before semantic ranking.
Shipped strategies:
WholeText— one surface = the whole text. The out-of-the-box default.Chunked— split the text into overlapping chunks (one surface each).Skill— embedname + descriptiononly (the body stays on disk, per the capability-discovery research); name/parent become filter fields.Fields— a record’s named text fields (head + body, balanced windows, optional normalizer); one surface per record or per field.Package—name + descriptionplus README chunks as surfaces; name/owner/deps become filter fields (AI synopsis / problem-class surfaces are a documented extension).
Every strategy is a plain callable-ish object with a decompose method, so
custom strategies need only match the IndexingStrategy protocol.
Module Attributes
Content-token budget for token-aware chunking under the default embedder. |
|
Shipped strategies addressable by name, for persisting an |
Functions
|
Split text into the fewest windows of at most size chars, near-equal in length. |
|
Case-fold text and strip accents from Latin and Greek letters only. |
|
Whether a constructor parameter is JSON-simple (scalar, or a tuple/list of scalars). |
|
Reconstruct a shipped strategy from a |
|
The |
|
A |
|
Best-effort text extraction from a raw artifact payload. |
|
Like |
Classes
|
Split the artifact's text into overlapping chunk surfaces. |
|
Index a Claude Code session turn-pair: user prompt + assistant summary. |
|
Index a record's named text fields (a catalogue item: name, place, prose...). |
|
Decompose one artifact into filter fields + embeddable surfaces. |
|
Package strategy: |
|
Capability strategy: embed |
|
One surface = the entire text. |
- class ir.strategy.Chunked(*, chunk_size=1200, overlap=200, text_key=None, kind='chunk', max_tokens=None, token_model=None, split=None, split_id=None)[source]¶
Bases:
objectSplit the artifact’s text into overlapping chunk surfaces.
By default chunks are packed to ~``chunk_size`` characters. Set
max_tokensto chunk by tokens instead — each chunk is bounded tomax_tokenstokens oftoken_model(default: the default embedding model), so no chunk overflows the embedder’s sequence limit and is silently truncated. Token mode degrades to char mode with a warning if the tokenizer is unavailable. The charchunk_size/overlapstill set the overlap ratio used in token mode.splitswaps the character splitter for a(text, *, size, overlap) -> list[str]callable or"module:attr"reference, e.g.balanced_windows()(equal-sized windows, no short tail) orword_windows()(word-aligned cuts), withsize=chunk_size. It is exclusive withmax_tokens.split_idnames a lambda/closure for re-indexing, as forFields.
- class ir.strategy.ClaudeTurn(*, include_full=False)[source]¶
Bases:
objectIndex a Claude Code session turn-pair: user prompt + assistant summary.
Two surfaces by default —
user_prompt(what the human asked) andassistant_summary(the assistant’s final end-of-turn text, the highest-signal “here’s what I did”; the deliberation before it is mostly noise) — so a query can target either side viasurfaces={"user_prompt"}/{"assistant_summary"}. Withinclude_full=Truea thirdassistant_fullsurface (all the turn’s assistant natural-language text) trades noise for recall — off by default. Session / project / time / model / tool-use become hard-filter fields.The raw artifact is a turn-pair record (see
priv.claude_transcripts.turn_pair_records()): a mapping withuser_prompt/assistant_summary/assistant_fullplus metadata.
- ir.strategy.DFLT_CHUNK_MAX_TOKENS = 250¶
Content-token budget for token-aware chunking under the default embedder.
all-MiniLM-L6-v2caps input at 256 tokens and silently truncates beyond it. We target 250 (not 254) to leave headroom for the two special tokens ([CLS]/[SEP]) and the ±1–2 token drift when an offset-sliced substring is re-tokenized on its own — so an embedded chunk stays within budget and its tail is never silently truncated (see_chunk_text()).
- class ir.strategy.Fields(fields, *, head=(), layout='record', normalize=None, normalize_id=None, max_chars=1200, overlap=200, kind='record', split=None, split_id=None)[source]¶
Bases:
objectIndex a record’s named text fields (a catalogue item: name, place, prose…).
fieldsare the body keys, read in order;headare keys (a name, a place) that lead the record. Two layouts:layout="record"(default): one surface per window of the body, with the head text prefixed to every window, so a word in the name and a word in the place only score together because they share a surface. Measured on 12 judged requests over ~44k records: BM25 hit@1 0.92 vs 0.58 for"fields".layout="fields": one surface per field (head and body),kind= the field name, so a query can target one field withsurfaces={...}.
normalize(astr -> strcallable, or a"module:attr"reference to one, case/accent folding…) is applied to every text before indexing, andir.build()records it on the corpus so every search folds its query with the same function (seeir.index.Corpus). A reference is persisted in a registry spec and in the built corpus, and is its own identity; a callable is not persisted (a reopened corpus warns that its queries are no longer folded, unlessopen_corpus(query_normalize=...)hands it back), and is identified by its qualified name or an explicitnormalize_id(required for a lambda or closure).max_chars/overlapwindow the body withbalanced_windows()(splitswaps the splitter: a(text, *, size, overlap) -> list[str]callable or"module:attr"reference, e.g.word_windows()for word-aligned cuts;split_idnames a lambda/closure for re-indexing) (the head is prefixed to each window and not itself windowed, so keep it short).kindnames the surface in the"record"layout;"fields"uses the field names. A key listed in bothheadandfieldsis read once.readslists every key the strategy reads, so a change signal can cover them.>>> plan = Fields(fields=["about"], head=["name", "place"]).decompose( ... "r1", {"name": "Louvre", "place": "Paris", "about": "A museum."}) >>> [(s.kind, s.text) for s in plan.surfaces] [('record', 'Louvre\nParis\nA museum.')]
- class ir.strategy.IndexingStrategy(*args, **kwargs)[source]¶
Bases:
ProtocolDecompose one artifact into filter fields + embeddable surfaces.
- class ir.strategy.Package(*, chunk_size=1500, overlap=200, embed_deps=False, deps_template=None, max_tokens=None, token_model=None)[source]¶
Bases:
objectPackage strategy:
name + descriptionsurface plus README chunks.Filter fields capture ownership (ours vs third-party), name, deps. AI synopsis / problem-class surfaces are a documented extension point.
With
embed_deps=True,decomposeadditionally emits oneSurface(kind="deps", granularity="field")whose text is a prefix-form serialization of the bare dependency names (deps_template, default_default_deps_text()) — so a query for a domain matches a package by the libraries it depends on (e.g.sentence-transformers-> embeddings,networkx-> graphs), and the BM25 leg picks up exact dep-token matches. The deps bag is kept separate from prose (its own surface) so a rare library name is not diluted, and deps remain a filter field regardless.embed_depsdefaultsFalse(today’s behavior); it folds into the strategy id, so toggling it re-decomposes incrementally. The deps surface is appended last, leaving thedescription(position 0) andreadme_chunkindices unchanged.Surface indexing: the
descriptionsurface (kept whenever name or description is non-empty) occupies plan position 0, soreadme_chunkj is stored withRecord.surface_index == j + 1while its surface metadata sayschunk_index == j—surface_indexis plan-global,chunk_indexper-kind (seeir.base.Record.make_id()). Never derive sibling record ids fromchunk_index; use the ledger (ir.retrieve.records_for_artifact()).n_chunksis stamped on readme chunks at decompose time, but corpora built before the stamp keep records without it until the artifact re-indexes (content / embedder / strategy change) — read it withmetadata.get("n_chunks").- synopsis_fields = ('name', 'description', 'readme')¶
The record fields a synopsis is written from (see
ir.synopsis.with_synopsis()): prose only. The record’spath(a local absolute path) anddepsnever go to an LLM.
- ir.strategy.STRATEGY_REGISTRY: dict[str, type] = {'Chunked': <class 'ir.strategy.Chunked'>, 'ClaudeTurn': <class 'ir.strategy.ClaudeTurn'>, 'Fields': <class 'ir.strategy.Fields'>, 'Package': <class 'ir.strategy.Package'>, 'Skill': <class 'ir.strategy.Skill'>, 'WholeText': <class 'ir.strategy.WholeText'>}¶
Shipped strategies addressable by name, for persisting an
IndexingStrategyin a registry entry and reconstructing it (#58). New shipped strategies register here so a corpus can name its segmentation.
- class ir.strategy.Skill[source]¶
Bases:
objectCapability strategy: embed
name + descriptiononly.The body (SKILL.md) is loaded post-selection and is not indexed; name and parent are filter fields.
- class ir.strategy.WholeText(*, text_key=None, kind='document')[source]¶
Bases:
objectOne surface = the entire text. Sensible default for a naive corpus.
- ir.strategy.balanced_windows(text, *, size, overlap=0)[source]¶
Split text into the fewest windows of at most size chars, near-equal in length.
n = ceil((L - overlap) / (size - overlap))windows, eachceil((L + (n - 1) * overlap) / n)long, so a text just past the limit becomes two halves, not one full window plus a sliver (which length normalisation in BM25 would favour).>>> balanced_windows("a" * 10, size=10) ['aaaaaaaaaa'] >>> [len(w) for w in balanced_windows("a" * 11, size=10)] [6, 5] >>> [len(w) for w in balanced_windows("a" * 25, size=10, overlap=2)] [10, 10, 9]
- ir.strategy.fold_text(text)[source]¶
Case-fold text and strip accents from Latin and Greek letters only.
Applies NFKC first (full-width letters, ligatures and compatibility forms fold in), then
casefold, then removes accents of Latin/Greek letters, mapping strokes and ligature-letters (ø đ ł æ œ þ) to ASCII. Safe for mixed-script text: marks that carry meaning elsewhere are left alone (kana voicingが, Hangul syllables, Devanagari virama, Thai tone marks, Cyrillicй/ё). Use it as aFields(normalize=...)normalizer (by reference:"ir.strategy:fold_text") and apply it to queries, e.g.formulate=fold_text(astr -> stris a valid formulator), since folding acts on whichever side runs it. A synopsis written by an LLM (ir.with_synopsis) is not folded.>>> fold_text("Crème BRÛLÉE Straße Đà Nẵng Łódź") 'creme brulee strasse da nang lodz' >>> fold_text("Crème") 'creme' >>> fold_text("Αθήνα") 'αθηνα' >>> fold_text("がぎ 한국어 हिन्दी Йё ไก่") 'がぎ 한국어 हिन्दी йё ไก่'- Return type:
- ir.strategy.is_simple_param(value)[source]¶
Whether a constructor parameter is JSON-simple (scalar, or a tuple/list of scalars).
The shared test behind a strategy’s persisted spec (
strategy_to_spec()) and its build identity (ir.index._strategy_id), so a parameter such asFields’sfieldsboth round-trips through the registry and re-decomposes a corpus when it changes.- Return type:
- ir.strategy.strategy_from_spec(spec)[source]¶
Reconstruct a shipped strategy from a
{"name", "params"}spec.None(no persisted strategy) returnsNoneso the caller falls back to the source preset’s default strategy — the back-compatible behavior for v1 registry entries.- Return type:
- ir.strategy.strategy_normalizer(strategy)[source]¶
The
normalizean indexing strategy applies to its text, as given.That is the strategy’s
normalizeattribute (a callable or a"module:attr"reference), or, for a wrapper such asir.with_synopsis(), that of the strategy it wraps;Nonewhen the indexed text is not normalized.ir.build()records it so a search can fold its query with the same function.>>> strategy_normalizer(Fields(fields=["about"], normalize="ir.strategy:fold_text")) 'ir.strategy:fold_text' >>> strategy_normalizer(Fields(fields=["about"])) is None True
- ir.strategy.strategy_to_spec(strategy)[source]¶
A
{"name", "params"}spec for a shipped, scalar-param strategy.Captures only scalar constructor parameters (the same identity surface
ir.index._strategy_id()stamps), so it round-trips the shipped strategies. A custom strategy, or one wrapping another (e.g. their.with_synopsis()wrapper), is not captured here — those are set programmatically at build time / by the maintenance layer, not persisted as a segmentation spec.- Return type:
- ir.strategy.text_of(raw, text_key=None)[source]¶
Best-effort text extraction from a raw artifact payload.
The SSOT for turning an opaque
raw(astr, aMappingwith atextfield or atext_key, or anything else) into embeddable text — reused by the shipped strategies and byir.synopsis.make_llm_synthesizer()so an injected-free synopsis summarizes the same text a strategy would index.- Return type:
- ir.strategy.word_windows(text, *, size, overlap=0)[source]¶
Like
balanced_windows(), but each cut moves back to the nearest whitespace.A window that would end mid-word ends at the last whitespace (a space, a newline, a tab) inside it instead (when there is one), and the next window starts at the following word, so no word is split. Windows are therefore at most
sizelong but not near-equal.overlapis a character target, rounded to word starts.>>> word_windows("alpha beta gamma delta", size=12) ['alpha beta', 'gamma delta'] >>> word_windows("short", size=12) ['short']