Skip to content

Indexing modules

The pipeline that turns a folder of source files into indexed chunks: discover → hash-diff → chunk → embed → upsert.

noesis.core.chunker

cAST split-then-merge chunking: AST nodes -> size-bounded chunks (Overview §4.4).

tree-sitter parses each file; adjacent sibling nodes are greedily merged into chunks within a token budget, any node over the max budget is split by recursing into its children, and over-budget leaves are split by lines. Missing language or grammar degrades to a line-based fallback — never an error. Canonical language names (core/languages.py) are passed straight to tree-sitter-language-pack; they resolve 1:1 today, and M5's LANGUAGE_MAP is the seam if that ever changes.

Hard invariant: concatenating chunk.text over a file's chunks, in order, reproduces the file text exactly — byte-for-byte, no overlap. Whitespace and comments between siblings attach to the following chunk, and every chunk boundary is snapped to a line start, so start_line/end_line slice the file's lines exactly.

Never split a function below its signature: a definition either fits whole in a chunk, or — only when it alone exceeds the max budget — is split via its own children behind a hard chunk boundary forced at the definition's start.

MIN_CHUNK_TOKENS = 300 module-attribute

Soft floor: greedy merging aims to fill chunks at least this far.

MAX_CHUNK_TOKENS = 800 module-attribute

Hard ceiling: only an indivisible single line may estimate above this.

Chunk(text, file_path, start_line, end_line, language, node_type, symbol_name, file_hash) dataclass

One retrieval unit of a file, with 1-based inclusive line bounds.

text instance-attribute

file_path instance-attribute

start_line instance-attribute

end_line instance-attribute

language instance-attribute

node_type instance-attribute

symbol_name instance-attribute

file_hash instance-attribute

chunk_file(text, *, language, file_path, file_hash)

Chunk one file's content; empty text yields an empty list.

Source code in src/noesis/core/chunker.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def chunk_file(
    text: str, *, language: str | None, file_path: str, file_hash: str
) -> list[Chunk]:
    """Chunk one file's content; empty text yields an empty list."""
    if not text:
        return []
    data = text.encode("utf-8")
    prefix = _nws_prefix(data)
    pieces = _ast_pieces(text, data, prefix, language)
    if pieces is None:  # no language / grammar / parse — degrade, never fail
        pieces = _line_pieces(data, 0, len(data), "text", named=True)
    pieces = _snap_to_lines(pieces, data, prefix)
    chunks: list[Chunk] = []
    for window in _merge(pieces, prefix):
        start, end = window[0].start, window[-1].end
        source = next(
            (p for p in window if p.symbol is not None),
            next((p for p in window if p.named and p.kind != "comment"), window[0]),
        )
        chunks.append(
            Chunk(
                text=data[start:end].decode("utf-8"),
                file_path=file_path,
                start_line=data.count(b"\n", 0, start) + 1,
                end_line=data.count(b"\n", 0, end - 1) + 1,
                language=language,
                node_type=source.kind,
                symbol_name=source.symbol,
                file_hash=file_hash,
            )
        )
    return chunks

noesis.core.languages

Canonical language names, keyed by file extension.

This module is the single source for the project's canonical language identifiers (stored in files.language). LANGUAGE_MAP (M5, §3.5) is the explicit seam mapping each canonical name to (a) its tree-sitter-language-pack grammar name and (b) its ast-grep language string — the two engines do not share identifiers by contract, even where they coincide today. Keep this a plain dict module.

EXT_TO_LANGUAGE = {'.py': 'python', '.pyi': 'python', '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.ts': 'typescript', '.tsx': 'tsx', '.go': 'go', '.rs': 'rust', '.java': 'java', '.c': 'c', '.h': 'c', '.cpp': 'cpp', '.cc': 'cpp', '.cxx': 'cpp', '.hpp': 'cpp', '.hh': 'cpp', '.cs': 'csharp', '.rb': 'ruby', '.php': 'php', '.swift': 'swift', '.kt': 'kotlin', '.kts': 'kotlin', '.scala': 'scala', '.sh': 'bash', '.bash': 'bash', '.html': 'html', '.htm': 'html', '.css': 'css', '.json': 'json', '.yaml': 'yaml', '.yml': 'yaml', '.toml': 'toml', '.md': 'markdown', '.sql': 'sql'} module-attribute

LANGUAGE_MAP = {'python': LanguageMapping('python', 'python'), 'javascript': LanguageMapping('javascript', 'javascript'), 'typescript': LanguageMapping('typescript', 'typescript'), 'tsx': LanguageMapping('tsx', 'tsx'), 'go': LanguageMapping('go', 'go'), 'rust': LanguageMapping('rust', 'rust'), 'java': LanguageMapping('java', 'java'), 'c': LanguageMapping('c', 'c'), 'cpp': LanguageMapping('cpp', 'cpp'), 'csharp': LanguageMapping('csharp', 'csharp'), 'ruby': LanguageMapping('ruby', 'ruby'), 'php': LanguageMapping('php', 'php'), 'swift': LanguageMapping('swift', 'swift'), 'kotlin': LanguageMapping('kotlin', 'kotlin'), 'scala': LanguageMapping('scala', 'scala'), 'bash': LanguageMapping('bash', 'bash'), 'html': LanguageMapping('html', 'html'), 'css': LanguageMapping('css', 'css'), 'json': LanguageMapping('json', 'json'), 'yaml': LanguageMapping('yaml', 'yaml'), 'markdown': LanguageMapping('markdown', 'markdown')} module-attribute

LanguageMapping(grammar, ast_grep) dataclass

grammar instance-attribute

ast_grep instance-attribute

detect_language(path)

Return the canonical language for path's extension, or None.

Source code in src/noesis/core/languages.py
56
57
58
def detect_language(path: str | Path) -> str | None:
    """Return the canonical language for *path*'s extension, or None."""
    return EXT_TO_LANGUAGE.get(Path(path).suffix.lower())

noesis.core.discovery

File discovery: walk a project tree and yield indexable files.

Filters, in order: excluded directories, .gitignore (git semantics, nested files, negation), the secret skip-list, the generated-lockfile skip-list, symlinks, size cap, binary sniff. The secret skip-list is defense-in-depth on top of .gitignore — a secret file is skipped even when no .gitignore mentions it, so it can never enter the index (a retrievable surface) or M5 structural-search results.

logger = logging.getLogger(__name__) module-attribute

EXCLUDED_DIRS = frozenset({'.git', '.hg', '.svn', 'node_modules', 'dist', 'build', 'target', '.venv', 'venv', '__pycache__', '.mypy_cache', '.pytest_cache', '.ruff_cache', '.tox', '.eggs', '.idea', '.vscode'}) module-attribute

SECRET_SKIP_PATTERNS = ('.env', '.env.*', '*.pem', '*.key', '*.p12', '*.pfx', '*.jks', '*.keystore', 'id_rsa*', 'id_ed25519*', 'id_ecdsa*', 'id_dsa*', '*.ppk', 'credentials*', '.netrc', '.npmrc', '.pypirc', '*.tfvars', 'secrets.*', '*.secret', '**/.aws/**', '**/.ssh/**') module-attribute

GENERATED_SKIP_PATTERNS = ('uv.lock', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb', 'Cargo.lock', 'poetry.lock', 'Pipfile.lock', 'go.sum', 'composer.lock', 'Gemfile.lock', 'packages.lock.json', 'flake.lock') module-attribute

DiscoveryConfig(max_file_bytes=1048576, follow_symlinks=False, include_languages=None, extra_ignore_patterns=()) dataclass

max_file_bytes = 1048576 class-attribute instance-attribute

include_languages = None class-attribute instance-attribute

extra_ignore_patterns = () class-attribute instance-attribute

DiscoveryErrors(files=list(), dirs=list(), entries_seen=0, unscreened=list(), unidentified=list()) dataclass

Non-fatal discovery failures, (root-relative path, message) pairs.

files: a file that exists but could not be screened (stat/read error) — it is excluded from the results, but "absent from discovery" must not be read as "deleted from disk" (same discrimination as H7). dirs: a directory whose scandir failed mid-walk — its whole subtree went unseen, so deletion evidence from this walk is untrustworthy.

The two lists above are about a path's EXISTENCE. The two below are not: the walk reached the directory and enumerated it fine, and every file in it is accounted for — what failed is an input to screening, so the result may be the wrong SHAPE rather than incomplete (ADR-58).

unscreened: a directory whose .gitignore could not be tested for or read, so its ignore rules were never applied. Unlike every other failure in this module this one runs in BOTH directions. The obvious half is under-ignoring — excluded files reach the index, a retrievable surface. The half that is easy to miss, and the reason this is not merely cosmetic: git's last-match-wins semantics mean a deeper .gitignore can NEGATE a shallower exclusion (*.log at the root, !important.log in logs/). Lose the deeper spec and the outer exclusion stands unopposed, the file drops out of the results, and "absent from discovery" is read downstream as deletion. So this list DOES suppress deletion — under its own directory prefix only, via the ADR-54 machinery — even though nothing about the walk was incomplete.

unidentified: a directory whose identity could not be established — the follow_symlinks cycle-guard stat, or the per-child is_symlink test. This one can only make the walk OVER-inclusive (a subtree walked twice under two rel paths, or a symlink descended into that would normally be skipped); it can never remove a path from the results, so it is never deletion evidence and suppresses nothing. Recorded anyway, so that no filesystem fault in this module is invisible.

entries_seen counts every file entry the walk enumerated, before any filter runs. It is not an error, but it lives here because only the caller that cares about the errors cares about it: an empty result with entries_seen == 0 means the walk found nothing at all (an unmounted or emptied root), while an empty result with entries_seen > 0 means the tree is readable and populated and the filters — an ADR-42 scope narrowing, .gitignore, the skip-lists — removed everything. Those two are indistinguishable from the returned list alone, and change detection must not treat the first as deletion.

files = field(default_factory=list) class-attribute instance-attribute

dirs = field(default_factory=list) class-attribute instance-attribute

entries_seen = 0 class-attribute instance-attribute

unscreened = field(default_factory=list) class-attribute instance-attribute

unidentified = field(default_factory=list) class-attribute instance-attribute

is_secret_path(rel_posix)

True if a project-relative POSIX path matches the secret skip-list.

Source code in src/noesis/core/discovery.py
170
171
172
def is_secret_path(rel_posix: str) -> bool:
    """True if a project-relative POSIX path matches the secret skip-list."""
    return bool(_SECRET_SPEC.match_file(rel_posix))

discover_files(root, config=None, *, errors=None)

Return sorted, POSIX-style relative paths of indexable files under root.

When errors is given, transient stat/read/scandir failures are recorded there instead of vanishing silently — callers doing change detection need them to tell "file errored" from "file deleted"; errors.entries_seen additionally reports how many file entries the walk enumerated before filtering, which is the only way to tell an unreadable root from a fully filtered one. errors=None keeps the historical silent-skip behavior.

Source code in src/noesis/core/discovery.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
def discover_files(
    root: str | Path,
    config: DiscoveryConfig | None = None,
    *,
    errors: DiscoveryErrors | None = None,
) -> list[str]:
    """Return sorted, POSIX-style relative paths of indexable files under *root*.

    When *errors* is given, transient stat/read/scandir failures are recorded
    there instead of vanishing silently — callers doing change detection need
    them to tell "file errored" from "file deleted"; ``errors.entries_seen``
    additionally reports how many file entries the walk enumerated before
    filtering, which is the only way to tell an unreadable root from a fully
    filtered one. ``errors=None`` keeps the historical silent-skip
    behavior."""
    cfg = config or DiscoveryConfig()
    root_path = Path(root).resolve()

    def _walk_error(exc: OSError) -> None:
        # A *subdirectory* deleted mid-walk is a genuine deletion (same
        # discrimination as H7's file case); any other scandir failure means
        # part of the tree went unseen and must be surfaced when asked.
        #
        # The root is the exception. os.walk routes the walk root's own
        # scandir failure through this hook too, and an unmounted or renamed
        # root arrives as FileNotFoundError — so treating it as "genuine
        # absence" would report an empty tree with no error recorded, which
        # every caller reads as "every tracked file was deleted". A missing
        # root is never evidence that files were deleted; it is evidence the
        # scan could not run. An unattributable failure (no filename) is
        # treated the same way, since it cannot be proven to be a subtree.
        failed = Path(exc.filename) if exc.filename else None
        at_root = failed is None or failed == root_path
        if isinstance(exc, (FileNotFoundError, NotADirectoryError)) and not at_root:
            return
        if errors is None:
            return
        rel = "<root>"
        if exc.filename:
            try:
                rel = PurePosixPath(
                    Path(exc.filename).relative_to(root_path)
                ).as_posix()
            except ValueError:
                rel = str(exc.filename)
            if rel == ".":
                rel = "<root>"
        # Message only — never the key. `_walk_error`'s unattributable branch
        # above deliberately keeps `rel = str(exc.filename)` as an absolute
        # path when it IS the key (`indexer.is_attributable_prefix` reads it),
        # which `_error_detail` does not touch (issue #32, ADR-73).
        errors.dirs.append((rel, _error_detail(exc)))

    # `errors=None` keeps the historical silent-skip contract for the callers
    # that do no change detection (structural search, the ADR-42 registration
    # preview). `_record_degraded` still logs in that case — these are the
    # buckets, not the reporting switch.
    unscreened = None if errors is None else errors.unscreened
    unidentified = None if errors is None else errors.unidentified
    # O(1)-dedupe companions for the two buckets above, scoped to this single
    # walk — see `_record_degraded` (issue #33). Built unconditionally, even
    # when the corresponding bucket is None, so every call site can pass one
    # without a branch.
    unscreened_seen: set[str] = set()
    unidentified_seen: set[str] = set()

    ignores = _IgnoreStack()
    extra_spec = (
        GitIgnoreSpec.from_lines(cfg.extra_ignore_patterns)
        if cfg.extra_ignore_patterns
        else None
    )
    results: list[str] = []
    # When following symlinks, os.walk has no cycle/duplicate guard. Track
    # directory identity (st_dev, st_ino) and prune any dir already walked so
    # a self-referencing link cannot loop forever and a link into an
    # already-walked subtree cannot index files twice.
    visited: set[tuple[int, int]] = set()

    for dirpath, dirnames, filenames in os.walk(
        root_path, topdown=True, followlinks=cfg.follow_symlinks, onerror=_walk_error
    ):
        dir_rel = PurePosixPath(Path(dirpath).relative_to(root_path)).as_posix()
        if dir_rel == ".":
            dir_rel = ""
        # Computed before the cycle guard purely so the guard has a key to
        # report against; it reads nothing from the filesystem.
        dir_key = _dir_key(dir_rel)

        if cfg.follow_symlinks:
            ident = _cycle_guard_identity(
                dirpath, bucket=unidentified, key=dir_key, seen=unidentified_seen
            )
            if ident is not None:
                visited.add(ident)

        # Both .gitignore faults land in `unscreened` and both are non-fatal.
        # Before issue #26 the first one RAISED — CPython's `_ignore_error`
        # covers only (ENOENT, ENOTDIR, EBADF, ELOOP), so `is_file()` re-raises
        # EACCES and ESTALE — and it ran unconditionally once per walked
        # directory, so a single unstattable path took down the whole run, and
        # with it `structural_search` (an unhandled 500) and the registration
        # preview. The second was swallowed with a bare `return`.
        #
        # Continuing is not the same as ignoring: the directory prefix is
        # recorded, and the indexer suppresses deletion under it (ADR-58),
        # because a lost .gitignore can drop a file OUT of the results as well
        # as let one in — a deeper spec's negation of a shallower exclusion
        # stops applying, and downstream "absent from the walk" means deleted.
        gitignore = Path(dirpath) / ".gitignore"
        try:
            has_gitignore = gitignore.is_file()
        except OSError as exc:
            has_gitignore = False
            _record_degraded(
                unscreened,
                dir_key,
                gitignore,
                exc,
                "could not test whether this directory holds a .gitignore, so "
                "any rules it holds were not applied",
                seen=unscreened_seen,
            )
        if has_gitignore:
            try:
                ignores.push(dir_rel, gitignore)
            except OSError as exc:
                _record_degraded(
                    unscreened,
                    dir_key,
                    gitignore,
                    exc,
                    "this directory's .gitignore exists but could not be read, "
                    "so its rules were not applied",
                    seen=unscreened_seen,
                )

        kept_dirs = []
        for d in sorted(dirnames):
            if d in EXCLUDED_DIRS:
                continue
            child_rel = f"{dir_rel}/{d}" if dir_rel else d
            if ignores.ignored(child_rel, is_dir=True):
                continue
            if not cfg.follow_symlinks:
                try:
                    is_link = (Path(dirpath) / d).is_symlink()
                except OSError as exc:
                    # Same re-raise mechanism as the .gitignore test above, and
                    # before issue #26 this also killed the run. Treated as
                    # "not a symlink" so the directory is still walked: pruning
                    # it would hide whatever it holds from the deletion path,
                    # handing downstream a set of "absent" files nobody looked
                    # for — purge on doubt, which ADR-51 refuses. That is the
                    # same call the `follow_symlinks=True` branch below already
                    # makes for an unstattable child.
                    #
                    # Recorded in `unidentified`, which suppresses nothing,
                    # because the cost runs only one way: `os.walk` may now
                    # descend into a link it would normally skip, so the result
                    # can gain paths. It cannot lose any.
                    is_link = False
                    _record_degraded(
                        unidentified,
                        child_rel,
                        Path(dirpath) / d,
                        exc,
                        "could not determine whether this child directory is a "
                        "symlink, so it is walked unguarded",
                        seen=unidentified_seen,
                    )
                if is_link:
                    continue
            if cfg.follow_symlinks:
                child_ident = _cycle_guard_identity(
                    Path(dirpath) / d,
                    bucket=unidentified,
                    key=child_rel,
                    seen=unidentified_seen,
                )
                if child_ident is None:
                    # Keep walking it. Skipping an unstattable directory would
                    # hide whatever it holds and hand the deletion path a set
                    # of "absent" files that were never actually looked for —
                    # purge on doubt, which ADR-51 refuses. It simply walks
                    # unguarded.
                    kept_dirs.append(d)
                    continue
                if child_ident in visited:
                    continue
                visited.add(child_ident)
            kept_dirs.append(d)
        dirnames[:] = kept_dirs

        for name in filenames:
            # Counted before every filter: the question this answers is "did
            # the walk see anything?", not "did anything survive screening".
            if errors is not None:
                errors.entries_seen += 1
            rel = f"{dir_rel}/{name}" if dir_rel else name
            full = Path(dirpath) / name
            try:
                if not cfg.follow_symlinks and full.is_symlink():
                    continue
                if ignores.ignored(rel):
                    continue
                if is_secret_path(rel):
                    continue
                if _GENERATED_SPEC.match_file(rel):
                    continue
                if extra_spec is not None and extra_spec.match_file(rel):
                    continue
                if (
                    cfg.include_languages is not None
                    and detect_language(rel) not in cfg.include_languages
                ):
                    continue
                st = full.stat()
                # Non-regular files are skipped before anything opens them.
                # A FIFO passes the size gate (st_size is 0) and then
                # `_is_binary`'s open() blocks until some process opens the
                # write end — forever, in practice. That hangs discovery
                # inside its worker thread, so the run never finishes and
                # nothing raises for the OSError handler below to catch.
                # Device and socket nodes are skipped here too, explicitly
                # rather than by accident.
                if not stat.S_ISREG(st.st_mode):
                    continue
                if st.st_size > cfg.max_file_bytes:
                    continue
                if _is_binary(full):
                    continue
            except (FileNotFoundError, NotADirectoryError):
                continue  # genuinely vanished mid-walk — a real deletion (H7)
            except OSError as exc:
                # Still present but unscreened (EACCES, EIO, ESTALE): never
                # index it on unverified data, but record the failure so
                # callers don't mistake its absence for a deletion. The
                # message is rebuilt without `filename` — see `_error_detail`
                # (issue #32, ADR-73).
                if errors is not None:
                    errors.files.append((rel, _error_detail(exc)))
                continue
            results.append(rel)

    return sorted(results)

noesis.core.gitfast

Git candidate-set fast path (§3.2) — subprocess git CLI (ADR-23).

The fast path may only shrink the set of files that get hashed; it never decides changed/unchanged on its own authority (§3.2 rule 1) — that stays with the SHA-256 comparison in :mod:noesis.core.hashdiff. Any uncertainty — no repo, git binary absent, in-progress merge/rebase, detached HEAD, missing or unreachable anchor commit, non-zero git exit, timeout — returns None and the caller falls back to the full hash-walk, silently for the API caller and logged for the operator (rule 3).

Subprocess against the system git CLI is deliberate (rule 5 / ADR-23): zero Python deps, license-clean, and the ~10ms spawn cost is noise next to embedding. pygit2 remains the documented upgrade if profiling ever says otherwise.

logger = logging.getLogger(__name__) module-attribute

CandidatePathSet(paths)

Bases: AbstractSet[str]

Candidate paths where an entry may denote a whole directory.

Git collapses some changes to a single directory entry: an untracked nested repository is one dir/ line even under -uall, and a submodule change is one gitlink path with no slash. Discovery does descend into those directories, so a plain path-equality test would carry their changed files forward as unchanged. Membership here also matches any ancestor directory of the queried path — this only widens the candidate set (more files hashed, never fewer), so rule 1 holds.

Source code in src/noesis/core/gitfast.py
57
58
def __init__(self, paths: Iterable[str]) -> None:
    self._entries = frozenset(p.rstrip("/") for p in paths if p.rstrip("/"))

__slots__ = ('_entries',) class-attribute instance-attribute

__contains__(rel)

Source code in src/noesis/core/gitfast.py
60
61
62
63
64
65
66
67
68
69
70
def __contains__(self, rel: object) -> bool:
    if not isinstance(rel, str):
        return False
    if rel in self._entries:
        return True
    i = rel.rfind("/")
    while i > 0:
        if rel[:i] in self._entries:
            return True
        i = rel.rfind("/", 0, i)
    return False

__iter__()

Source code in src/noesis/core/gitfast.py
72
73
def __iter__(self) -> Iterator[str]:
    return iter(self._entries)

__len__()

Source code in src/noesis/core/gitfast.py
75
76
def __len__(self) -> int:
    return len(self._entries)

__repr__()

Source code in src/noesis/core/gitfast.py
78
79
def __repr__(self) -> str:
    return f"CandidatePathSet({sorted(self._entries)!r})"

GitCandidates(candidates, head_commit, dirty_paths=frozenset()) dataclass

Candidate changed set for one run.

candidates holds project-root-relative POSIX paths (same shape as discovery output); head_commit is the HEAD sha the diff was taken against — the anchor to store once the run completes (rule 4). dirty_paths is the working-tree-dirty subset (staged + unstaged + untracked, project-relative) — persisted with the anchor so a file dirty at run N stays a candidate at run N+1 even after being reverted to HEAD (H1).

candidates instance-attribute

head_commit instance-attribute

dirty_paths = frozenset() class-attribute instance-attribute

resolve_head(root)

HEAD commit sha, or None (not a repo, no commits yet, git absent).

Called even on full-walk runs of a git worktree so the next run has an anchor to fast-path from.

Source code in src/noesis/core/gitfast.py
113
114
115
116
117
118
119
120
121
122
def resolve_head(root: str | Path) -> str | None:
    """HEAD commit sha, or None (not a repo, no commits yet, git absent).

    Called even on full-walk runs of a git worktree so the *next* run has
    an anchor to fast-path from.
    """
    proc = _git(root, "rev-parse", "HEAD")
    if proc is None or proc.returncode != 0:
        return None
    return proc.stdout.decode("ascii", "replace").strip() or None

compute_candidates(root, anchor)

Candidate changed set since anchor, or None → full hash-walk.

The set is git diff --name-status anchor..HEAD ∪ git status --porcelain (staged + unstaged + untracked), per §3.2 rule 2. Deleted paths are included; they are not on disk, so discovery never yields them and the partition marks them deleted exactly as the full walk would.

Source code in src/noesis/core/gitfast.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def compute_candidates(root: str | Path, anchor: str) -> GitCandidates | None:
    """Candidate changed set since *anchor*, or None → full hash-walk.

    The set is ``git diff --name-status anchor..HEAD`` ∪
    ``git status --porcelain`` (staged + unstaged + untracked), per §3.2
    rule 2. Deleted paths are included; they are not on disk, so discovery
    never yields them and the partition marks them deleted exactly as the
    full walk would.
    """
    proc = _git(root, "rev-parse", "--absolute-git-dir", "--show-prefix")
    if proc is None or proc.returncode != 0:
        return _fallback("not a git repository")
    lines = os.fsdecode(proc.stdout).splitlines()
    if not lines:
        return _fallback("unparseable rev-parse output")
    git_dir = Path(lines[0])
    # --show-prefix is empty at the repo toplevel; rev-parse still emits the
    # (empty) line, but be tolerant of it being absent.
    prefix = lines[1] if len(lines) > 1 else ""

    for marker in _IN_PROGRESS_MARKERS:
        if (git_dir / marker).exists():
            return _fallback(f"in-progress git operation ({marker} present)")

    proc = _git(root, "symbolic-ref", "-q", "HEAD")
    if proc is None or proc.returncode != 0:
        return _fallback("detached HEAD")

    head = resolve_head(root)
    if head is None:
        return _fallback("cannot resolve HEAD")

    # Anchor must be an ancestor of HEAD — merely existing in the object
    # store is not enough (a rebased/force-pushed-away commit lingers until
    # gc; diffing against it would miss the rewritten history — Risk 12).
    # Exit 1 = not an ancestor, 128 = unknown object; both → fallback.
    proc = _git(root, "merge-base", "--is-ancestor", anchor, "HEAD")
    if proc is None or proc.returncode != 0:
        return _fallback("anchor commit missing or unreachable")

    # --no-renames: renames surface as D old + A new, so both paths become
    # candidates with a trivial parser, independent of user diff.renames
    # config. -z: NUL-separated raw paths — immune to quoting/escaping.
    diff = _git(root, "diff", "--name-status", "-z", "--no-renames", anchor, "HEAD")
    if diff is None or diff.returncode != 0:
        return _fallback("git diff failed")

    # --untracked-files=all lists files inside untracked directories
    # individually (default collapses to "dir/", which is not a file path).
    status = _git(
        root, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"
    )
    if status is None or status.returncode != 0:
        return _fallback("git status failed")

    diff_paths = _parse_diff_z(diff.stdout)
    status_paths = _parse_status_z(status.stdout)
    return GitCandidates(
        candidates=CandidatePathSet(_strip_prefix(diff_paths | status_paths, prefix)),
        head_commit=head,
        dirty_paths=frozenset(_strip_prefix(status_paths, prefix)),
    )

status_dirty_paths(root)

Working-tree-dirty paths (staged + unstaged + untracked), project-root relative. Persisted alongside the anchor on a full-walk run so the H1 revert case is covered even when no git diff was computed. Returns None when root is not a usable git worktree (caller stores no dirty set).

Source code in src/noesis/core/gitfast.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def status_dirty_paths(root: str | Path) -> frozenset[str] | None:
    """Working-tree-dirty paths (staged + unstaged + untracked), project-root
    relative. Persisted alongside the anchor on a full-walk run so the H1
    revert case is covered even when no git diff was computed. Returns None
    when *root* is not a usable git worktree (caller stores no dirty set)."""
    proc = _git(root, "rev-parse", "--show-prefix")
    if proc is None or proc.returncode != 0:
        return None
    lines = os.fsdecode(proc.stdout).splitlines()
    prefix = lines[0] if lines else ""
    status = _git(
        root, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"
    )
    if status is None or status.returncode != 0:
        return None
    return frozenset(_strip_prefix(_parse_status_z(status.stdout), prefix))

noesis.core.hashdiff

SHA-256 change detection: hash files, partition against stored state.

Hash is the source of truth for change detection (Overview §4.9). The M7 git fast-path may later shrink the candidate set fed to partition, but never replaces the hash comparison itself (expanded doc §3.2 rule 1).

DiffResult(new=(), changed=(), unchanged=(), deleted=(), hashes=dict(), errored=(), verified=0, skipped=0) dataclass

Partition of discovered files vs stored state (relative POSIX paths).

new = field(default=()) class-attribute instance-attribute

changed = field(default=()) class-attribute instance-attribute

unchanged = field(default=()) class-attribute instance-attribute

deleted = field(default=()) class-attribute instance-attribute

hashes = field(default_factory=dict) class-attribute instance-attribute

Current content hash for every discovered file (new/changed/unchanged).

errored = field(default=()) class-attribute instance-attribute

(path, error) for files whose hash attempt failed non-fatally (the H7 carry-forward). The file's true state is UNKNOWN this run — callers must treat these like per-file failures: never advance the git anchor past them and re-queue them for retry, or a committed-then-errored file is carried forward as unchanged on every future fast-path run (stale forever).

verified = 0 class-attribute instance-attribute

Count of files where hash_file actually succeeded this run (whether the result landed in new/changed/unchanged). NOT the same as len(unchanged): an errored file with a prior hash is also carried into unchanged (H7), so unchanged alone cannot tell a real outage (every hash attempt failing) from ordinary steady state (nothing changed).

skipped = 0 class-attribute instance-attribute

Count of files carried forward as unchanged purely because the git fast path excluded them (not a candidate) — a deliberate, healthy skip, never hashed and never in doubt. Distinct from verified because a caller judging "did this run make zero real progress" must not count a narrow candidate set (fast path correctly skipping most of the tree) as equivalent to a whole-tree hashing outage: verified + skipped == 0 together with errored is a real "nothing in the whole discovered set is in a known-good state" signal; verified == 0 alone is not, since it is the fast path's steady-state norm.

hash_file(path)

SHA-256 hex digest of a file's content, read in chunks.

Source code in src/noesis/core/hashdiff.py
18
19
20
21
22
23
24
def hash_file(path: str | Path) -> str:
    """SHA-256 hex digest of a file's content, read in chunks."""
    digest = hashlib.sha256()
    with open(path, "rb") as fh:
        while chunk := fh.read(_READ_CHUNK):
            digest.update(chunk)
    return digest.hexdigest()

partition(root, discovered, stored, *, candidates=None, discovery_errored=())

Partition discovered (relative POSIX paths under root) against stored (path -> content_hash from the files table).

Files that vanish between discovery and hashing (FileNotFoundError / NotADirectoryError) are treated as deleted — the filesystem is ground truth at the moment it is read. A file that still exists but fails to open for another reason (permissions, transient network-fs error) is NOT treated as deleted: its stored hash is carried forward so its chunks are never purged (H7).

When candidates is given (git fast-path, §3.2), only discovered files that are candidates — or unknown to stored — get hashed; the rest carry their stored hash forward as unchanged. Candidacy only shrinks the hashing work, never decides changed/unchanged by itself (rule 1): every hashed file is still compared against stored, and deletions fall out of discovery exactly as in the full walk.

discovery_errored lists (path, error) pairs for files discovery could not screen (transient stat/read failure) and therefore excluded from discovered — they get the same treatment as a hash-time OSError (H7): surfaced in errored, stored hash carried forward, never deleted.

Source code in src/noesis/core/hashdiff.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def partition(
    root: str | Path,
    discovered: Iterable[str],
    stored: Mapping[str, str],
    *,
    candidates: AbstractSet[str] | None = None,
    discovery_errored: Sequence[tuple[str, str]] = (),
) -> DiffResult:
    """Partition `discovered` (relative POSIX paths under `root`) against
    `stored` (path -> content_hash from the files table).

    Files that vanish between discovery and hashing (FileNotFoundError /
    NotADirectoryError) are treated as deleted — the filesystem is ground
    truth at the moment it is read. A file that still exists but fails to
    open for another reason (permissions, transient network-fs error) is
    NOT treated as deleted: its stored hash is carried forward so its chunks
    are never purged (H7).

    When `candidates` is given (git fast-path, §3.2), only discovered files
    that are candidates — or unknown to `stored` — get hashed; the rest
    carry their stored hash forward as unchanged. Candidacy only shrinks
    the hashing work, never decides changed/unchanged by itself (rule 1):
    every hashed file is still compared against `stored`, and deletions
    fall out of discovery exactly as in the full walk.

    *discovery_errored* lists (path, error) pairs for files discovery could
    not screen (transient stat/read failure) and therefore excluded from
    `discovered` — they get the same treatment as a hash-time OSError (H7):
    surfaced in `errored`, stored hash carried forward, never `deleted`.
    """
    root = Path(root)
    new: list[str] = []
    changed: list[str] = []
    unchanged: list[str] = []
    hashes: dict[str, str] = {}
    errored: list[tuple[str, str]] = []
    seen: set[str] = set()
    verified = 0
    skipped = 0

    for rel in discovered:
        prior_hash = stored.get(rel)
        if candidates is not None and prior_hash is not None and rel not in candidates:
            seen.add(rel)
            hashes[rel] = prior_hash
            unchanged.append(rel)
            skipped += 1
            continue
        try:
            current = hash_file(root / rel)
        except (FileNotFoundError, NotADirectoryError):
            continue  # genuinely vanished mid-run; falls through to deleted
        except OSError as exc:
            # Transient/permission failure (EACCES after a chmod, EIO/ESTALE
            # on a network fs) on a file that still exists — NOT a deletion
            # (H7). Conflating the two would purge a live file's chunks. Carry
            # the stored hash forward as unchanged so its chunks keep serving;
            # a file unknown to `stored` we simply skip this run (nothing to
            # preserve, and it is not "deleted"). Either way the path is
            # surfaced in `errored`: "the next run retries" holds only if the
            # caller keeps the git anchor back / re-queues it — under the fast
            # path a committed file that errored here would otherwise never be
            # a candidate again and its stale hash would be carried forward on
            # every future run.
            errored.append((rel, str(exc) or type(exc).__name__))
            if prior_hash is not None:
                seen.add(rel)
                hashes[rel] = prior_hash
                unchanged.append(rel)
            continue
        seen.add(rel)
        hashes[rel] = current
        verified += 1
        prior = stored.get(rel)
        if prior is None:
            new.append(rel)
        elif prior != current:
            changed.append(rel)
        else:
            unchanged.append(rel)

    for rel, msg in discovery_errored:
        # Discovery-stage failure on a still-present file: exactly the H7
        # branch above — report it, carry the stored hash forward so its
        # chunks keep serving, and keep it out of `deleted`.
        errored.append((rel, msg))
        prior_hash = stored.get(rel)
        if prior_hash is not None:
            seen.add(rel)
            hashes[rel] = prior_hash
            unchanged.append(rel)

    deleted = sorted(p for p in stored if p not in seen)
    return DiffResult(
        new=tuple(sorted(new)),
        changed=tuple(sorted(changed)),
        unchanged=tuple(sorted(unchanged)),
        deleted=tuple(deleted),
        hashes=hashes,
        errored=tuple(errored),
        verified=verified,
        skipped=skipped,
    )

noesis.core.indexer

Indexing pipeline: discover → hash-diff → chunk → embed → upsert (§3.2).

Orchestrates the M1 spine (discovery, hashdiff, state) with the M2 pieces (chunker, Embedder, VectorStore). Dense channel only in M2 — the sparse/BM25 channel and RRF fusion land in M3; the git fast-path narrows the candidate set in M7. Embedding batches go through the Embedder Protocol at LOW priority so live queries preempt indexing (§3.8).

logger = logging.getLogger(__name__) module-attribute

ProgressFn = Callable[[int, int, int], None] module-attribute

IndexResult(project_id, run_id, files_total, files_indexed, files_deleted, chunks_written, fast_path_used=False, candidate_count=None, files_failed=0, failed_paths=(), unverified_suppressed=0, discovery_degraded=0) dataclass

project_id instance-attribute

run_id instance-attribute

files_total instance-attribute

files_indexed instance-attribute

files_deleted instance-attribute

chunks_written instance-attribute

fast_path_used = False class-attribute instance-attribute

candidate_count = None class-attribute instance-attribute

files_failed = 0 class-attribute instance-attribute

failed_paths = () class-attribute instance-attribute

unverified_suppressed = 0 class-attribute instance-attribute

discovery_degraded = 0 class-attribute instance-attribute

is_attributable_prefix(dir_rel)

True when dir_rel is a root-relative prefix _under can test.

False for the three shapes that describe no subtree of this project: the empty string, the <root> sentinel, and a path outside the root (an absolute name, or one reached by ../) — which discovery records when relative_to fails. Public because the promotion policy in jobs asks the same question of a stored ledger row: an unattributable failure leaves the whole index unverified, which no scoped run can make progress on.

Source code in src/noesis/core/indexer.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def is_attributable_prefix(dir_rel: str) -> bool:
    """True when *dir_rel* is a root-relative prefix ``_under`` can test.

    False for the three shapes that describe no subtree of this project: the
    empty string, the ``<root>`` sentinel, and a path outside the root (an
    absolute name, or one reached by ``../``) — which discovery records when
    ``relative_to`` fails. Public because the promotion policy in ``jobs`` asks
    the same question of a stored ledger row: an unattributable failure leaves
    the *whole* index unverified, which no scoped run can make progress on.
    """
    return bool(
        dir_rel
        and dir_rel != "<root>"
        and not os.path.isabs(dir_rel)
        and not dir_rel.startswith("../")
    )

discovery_config_for_project(conn, project_id)

Build a project's persisted index scope (ADR-42) into a DiscoveryConfig. Returns None for an unknown project (caller falls back to the default walk). NULL columns map to DiscoveryConfig defaults, so an unconfigured project walks exactly as before.

Source code in src/noesis/core/indexer.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def discovery_config_for_project(
    conn: sqlite3.Connection, project_id: str
) -> DiscoveryConfig | None:
    """Build a project's persisted index scope (ADR-42) into a
    DiscoveryConfig. Returns None for an unknown project (caller falls
    back to the default walk). NULL columns map to DiscoveryConfig
    defaults, so an unconfigured project walks exactly as before."""
    row = state.get_project(conn, project_id)
    if row is None:
        return None
    kwargs: dict = {"follow_symlinks": bool(row["follow_symlinks"])}
    if row["max_file_bytes"] is not None:
        kwargs["max_file_bytes"] = row["max_file_bytes"]
    if row["index_languages"]:
        kwargs["include_languages"] = frozenset(json.loads(row["index_languages"]))
    if row["extra_ignores"]:
        kwargs["extra_ignore_patterns"] = tuple(json.loads(row["extra_ignores"]))
    return DiscoveryConfig(**kwargs)

prepare_run(conn, embedder, root_path)

Register (or re-open) the project and open a run row.

Split from :func:execute_run so the API can hand back 202 Accepted + run_id before indexing starts (§3.2).

Goes through :func:state.try_start_run — the same guard as jobs.launch_index_run — and raises RuntimeError when a live run already holds the project: returning that run's id would make this caller execute it concurrently with its owner, the exact race the guard exists to prevent.

Source code in src/noesis/core/indexer.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def prepare_run(
    conn: sqlite3.Connection, embedder: Embedder, root_path: str
) -> tuple[str, str]:
    """Register (or re-open) the project and open a run row.

    Split from :func:`execute_run` so the API can hand back
    ``202 Accepted + run_id`` before indexing starts (§3.2).

    Goes through :func:`state.try_start_run` — the same guard as
    jobs.launch_index_run — and raises RuntimeError when a live run
    already holds the project: returning that run's id would make this
    caller execute it concurrently with its owner, the exact race the
    guard exists to prevent.
    """
    project_id = state.register_project(conn, root_path, embedder.model_id)
    run_id, created = state.try_start_run(conn, project_id)
    if not created:
        raise RuntimeError(
            f"index run {run_id} already running for project {project_id}"
        )
    return project_id, run_id

index_project(conn, store, embedder, root_path, *, batch_size=32, discovery_config=None, git_fast_path=True) async

Register, open a run, and index in one call (tests / CLI use).

Source code in src/noesis/core/indexer.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
async def index_project(
    conn: sqlite3.Connection,
    store: VectorStore,
    embedder: Embedder,
    root_path: str,
    *,
    batch_size: int = 32,
    discovery_config: DiscoveryConfig | None = None,
    git_fast_path: bool = True,
) -> IndexResult:
    """Register, open a run, and index in one call (tests / CLI use)."""
    project_id, run_id = prepare_run(conn, embedder, root_path)
    return await execute_run(
        conn,
        store,
        embedder,
        root_path,
        project_id,
        run_id,
        batch_size=batch_size,
        discovery_config=discovery_config,
        git_fast_path=git_fast_path,
    )

execute_run(conn, store, embedder, root_path, project_id, run_id, *, batch_size=32, discovery_config=None, git_fast_path=True, paths=None, force=False, unwalkable_quarantine_runs=5, on_progress=None) async

Index changes for an already-registered project under an open run.

Idempotent: chunk ids are content-derived and file state is only written after that file's chunks are safely in Qdrant, so an interrupted run re-processes only what is still out of date (Overview §5).

paths scopes the run to an explicit candidate set (the watcher's pending files, ADR-40): only those files (plus anything unknown to stored state) are hashed; deletions are still detected discovery-wide. A scoped run disables the git fast path and NEVER advances last_indexed_commit — the anchor may only move when the candidate set was derived from a git diff against it, otherwise the next fast path would silently skip files the watcher never saw (§3.2 rule 1).

force accepts a discovery result of zero files as real deletion evidence even when state still tracks files. Off by default: nothing observable distinguishes an emptied root from an unmounted one, so the assertion has to come from an operator (ADR-55). It relaxes nothing else — a directory that failed to scan still suppresses deletions under it.

unwalkable_quarantine_runs is how many consecutive runs a directory must fail to be walked before the stored paths it hides stop being re-queued for retry (ADR-56). 0 disables quarantine. It relaxes nothing about deletion either: a quarantined subtree's files are still never purged, and the run that finds the directory readable again re-hashes every one of them. All it bounds is the pending_changes backlog, which under a permanently unreadable directory could otherwise never drain (issue #25).

Source code in src/noesis/core/indexer.py
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
async def execute_run(
    conn: sqlite3.Connection,
    store: VectorStore,
    embedder: Embedder,
    root_path: str,
    project_id: str,
    run_id: str,
    *,
    batch_size: int = 32,
    discovery_config: DiscoveryConfig | None = None,
    git_fast_path: bool = True,
    paths: Sequence[str] | None = None,
    force: bool = False,
    unwalkable_quarantine_runs: int = 5,
    on_progress: ProgressFn | None = None,
) -> IndexResult:
    """Index changes for an already-registered project under an open run.

    Idempotent: chunk ids are content-derived and file state is only written
    after that file's chunks are safely in Qdrant, so an interrupted run
    re-processes only what is still out of date (Overview §5).

    *paths* scopes the run to an explicit candidate set (the watcher's
    pending files, ADR-40): only those files (plus anything unknown to
    stored state) are hashed; deletions are still detected discovery-wide.
    A scoped run disables the git fast path and NEVER advances
    ``last_indexed_commit`` — the anchor may only move when the candidate
    set was derived from a git diff against it, otherwise the next fast
    path would silently skip files the watcher never saw (§3.2 rule 1).

    *force* accepts a discovery result of zero files as real deletion evidence
    even when state still tracks files. Off by default: nothing observable
    distinguishes an emptied root from an unmounted one, so the assertion
    has to come from an operator (ADR-55). It relaxes nothing else — a
    directory that failed to scan still suppresses deletions under it.

    *unwalkable_quarantine_runs* is how many consecutive runs a directory must
    fail to be walked before the stored paths it hides stop being re-queued for
    retry (ADR-56). ``0`` disables quarantine. It relaxes nothing about
    deletion either: a quarantined subtree's files are still never purged, and
    the run that finds the directory readable again re-hashes every one of
    them. All it bounds is the ``pending_changes`` backlog, which under a
    permanently unreadable directory could otherwise never drain (issue #25).
    """
    if paths is not None:
        git_fast_path = False
    try:
        run_started = time.perf_counter()
        # Git fast-path (§3.2): capture HEAD and the candidate set BEFORE
        # discovery/hashing — anything committed after this point is simply
        # re-examined next run (the safe direction). Every fallback is
        # silent here and logged in gitfast; hash stays the truth.
        head: str | None = None
        git_info: "gitfast.GitCandidates | None" = None
        candidates: "gitfast.CandidatePathSet | frozenset[str] | None" = None
        if paths is not None:
            candidates = frozenset(paths)
        if git_fast_path:
            anchor = None
            project = state.get_project(conn, project_id)
            if project is not None:
                anchor = project["last_indexed_commit"]
            # Heavy sync spans (git subprocesses, tree walk, hashing, file
            # IO, Qdrant round-trips) run via to_thread throughout this
            # function: the run shares the event loop with live queries and
            # must never starve them (§3.8). Quick state.* calls stay on the
            # loop — the shared sqlite conn is serialized either way.
            git_info = (
                await asyncio.to_thread(gitfast.compute_candidates, root_path, anchor)
                if anchor
                else None
            )
            if git_info is not None:
                head = git_info.head_commit
                candidates = git_info.candidates
            else:
                # Full walk this run, but still record HEAD (on success) so
                # the next run has an anchor to fast-path from (rule 4).
                head = await asyncio.to_thread(gitfast.resolve_head, root_path)

        # H1: re-admit files that were working-tree-dirty at the last anchor
        # advance. If such a file was reverted to HEAD since, neither the diff
        # nor `git status` surfaces it now, yet its stored hash is the stale
        # dirty content — carrying it forward forever. Unioning the persisted
        # dirty set only widens the candidate set (rule 1 safe) and forces a
        # re-hash that detects the revert.
        if candidates is not None:
            prior_dirty = state.get_dirty_paths(conn, project_id)
            if prior_dirty:
                candidates = gitfast.CandidatePathSet(
                    set(candidates) | set(prior_dirty)
                )

        fast_path_active = git_fast_path and candidates is not None

        # No explicit config → honor the project's persisted index scope
        # (ADR-42), so manual/watcher/reindex runs all apply the same filter.
        if discovery_config is None:
            discovery_config = discovery_config_for_project(conn, project_id)
        # Discovery walks the whole tree and binary-sniffs each file; on large
        # or network-mounted trees this alone is slow and, until now, silent.
        disc_started = time.perf_counter()
        # Collect discovery failures instead of letting them vanish: a file
        # (or whole subtree) that errored transiently is absent from
        # `discovered`, and without the collector hashdiff would read that
        # absence as deletion and purge live chunks.
        disc_errors = DiscoveryErrors()
        discovered = await asyncio.to_thread(
            discover_files, root_path, discovery_config, errors=disc_errors
        )
        logger.info(
            "index run %s: discovery took=%.1fs discovered=%d",
            run_id,
            time.perf_counter() - disc_started,
            len(discovered),
        )
        stored = state.get_file_states(conn, project_id)
        # A scan that returned NOTHING while state tracks files is not
        # evidence of mass deletion — it is evidence the scan did not run: an
        # unmounted or renamed root, or a mountpoint not populated yet. The
        # walk-root discrimination in discovery catches the errno cases, but a
        # root that exists and is simply empty raises nothing at all, so this
        # cannot be expressed as an error check — the emptiness itself is the
        # signal. Recorded as a directory-level error so it takes the same
        # path as an unwalked subtree: deletions and orphan pruning are
        # skipped, the anchor cannot advance, and the run is marked failed.
        #
        # Two escapes, because a guard that can never be satisfied is a guard
        # that strands the project (PR #24 review):
        #
        # * ``entries_seen`` — the walk enumerated files and the filters
        #   removed all of them. The root is demonstrably readable and
        #   populated, so the emptiness is a scope decision (an ADR-42
        #   narrowing, a new .gitignore), not a missing mount, and the
        #   now-out-of-scope files SHOULD leave the index.
        # * ``force`` — an operator asserting the empty root is real. Nothing
        #   the process can observe distinguishes "every file deleted" from
        #   "root not mounted", so that call is the operator's to make.
        #
        # ``force`` deliberately does NOT relax the directory-error
        # suppression below: an unwalked subtree is a different, still-open
        # proof problem, not something the operator asserted anything about.
        #
        # Both branches stand down when discovery already reported a directory
        # failure (PR #24 review). This guard exists for the emptiness that
        # raises nothing; when something DID raise, that error is the diagnosis
        # and it is already recorded. Synthesizing a second ``<root>`` row on
        # top of it would overwrite the real errno — ``record_file_errors`` is
        # INSERT OR REPLACE keyed on (run_id, path) — costing the operator the
        # EACCES/ESTALE they need to fix the mount, and double-counting one
        # failure in ``files_failed``. Under ``force`` the same condition
        # otherwise logs a purge that the deletion block then refuses to
        # perform. Deletion safety is unchanged either way: the recorded
        # directory error drives `unwalked` on its own.
        if (
            stored
            and not discovered
            and not force
            and not disc_errors.entries_seen
            and not disc_errors.dirs
        ):
            disc_errors.dirs.append(
                (
                    "<root>",
                    f"discovery returned no files while state tracks "
                    f"{len(stored)} file(s) — treating as an unreadable root, "
                    f"not as deletion",
                )
            )
            logger.warning(
                "index run %s: discovery returned 0 files but state tracks %d "
                "— refusing to treat that as deletion (root unreadable or "
                "not mounted?)",
                run_id,
                len(stored),
            )
        elif stored and not discovered and not disc_errors.dirs:
            # The purge the guard exists to prevent, now deliberate. Loud
            # either way: an operator reading the log after the fact must be
            # able to see which escape emptied the project — so it may only
            # fire where a purge can actually follow, and it may only claim
            # what the walk actually did. With no directory error recorded,
            # `_unwalked_prefixes` below returns `()` and nothing is
            # suppressed; with one, it returns a subtree or None and this line
            # would name an escape that emptied nothing.
            #
            # `entries_seen` counts every enumerated entry, including ones that
            # then failed to be screened — and a file that ERRORED was not
            # "filtered out": hashdiff carries it forward, so it is never
            # deleted. Report the two populations separately rather than
            # crediting the filters with a permission error.
            logger.warning(
                "index run %s: discovery returned 0 files while state tracks "
                "%d — accepting the empty scan as real (%s); what that deletes "
                "is still decided per file, so an unreadable path is carried "
                "forward, not purged",
                run_id,
                len(stored),
                "forced by caller"
                if force
                else f"walk enumerated {disc_errors.entries_seen} file entry/"
                f"entries ({disc_errors.entries_seen - len(disc_errors.files)} "
                f"filtered out, {len(disc_errors.files)} unreadable) — root is "
                f"readable",
            )

        # Which stored paths this walk could not see. Computed once, after
        # the empty-scan guard has had its chance to add `<root>`, and used
        # by both purge paths below (orphan pruning and deletion).
        # `discovery_config` may still be None here (no persisted scope row);
        # discover_files defaults it the same way, so read the flag from the
        # same default rather than assuming what it is.
        follow_symlinks = (discovery_config or DiscoveryConfig()).follow_symlinks
        unwalked = _unwalked_prefixes(disc_errors, follow_symlinks=follow_symlinks)
        # Prefixes where the walk saw everything but could not apply the ignore
        # rules (ADR-58). These block deletion for a reason that is the reverse
        # of `unwalked`'s: nothing went unseen, but a lost .gitignore can push a
        # file OUT of the results — git is last-match-wins, so a deeper spec's
        # negation of a shallower exclusion stops applying — and downstream
        # every absence reads as a deletion.
        #
        # Kept in its own value rather than merged into `unwalked`, because
        # `unwalked` also feeds the ADR-56 ledger, the quarantine test and the
        # recovery reset. A directory that walked fine must not accumulate
        # consecutive-failure counts toward quarantine, and a ledger row must
        # not be denied its reset because an unrelated .gitignore was degraded.
        unscreened = _error_prefixes(
            disc_errors.unscreened, follow_symlinks=follow_symlinks
        )

        # Directory-failure ledger (ADR-56). READ here, WRITTEN after the file
        # loop — the order is load-bearing. Reconciling early would delete a
        # recovered directory's row before the re-admission below had run, and
        # a crash in between would lose the only record that its files were
        # ever unverified: the ledger would say healthy, the files would carry
        # stale hashes, and nothing would re-hash them.
        ledger = state.list_unwalkable_dirs(conn, project_id)
        reported_now = {dir_rel for dir_rel, _ in disc_errors.dirs}
        prior_counts = {row["dir_path"]: row["consecutive_runs"] for row in ledger}
        # Quarantine is judged on the count this run WILL have, not the stored
        # one, so `unwalkable_quarantine_runs = N` means "suppressed on the Nth
        # consecutive failure" rather than the N+1'th. The reconcile below
        # applies the same >= test to the same post-increment number, so the
        # decision here and the `quarantined_at` an operator reads agree.
        quarantined: frozenset[str] = (
            frozenset()
            if unwalkable_quarantine_runs <= 0
            else frozenset(
                key
                for key in set(prior_counts) | reported_now
                if prior_counts.get(key, 0) + (1 if key in reported_now else 0)
                >= unwalkable_quarantine_runs
            )
        )
        # Recorded directories this walk proved walkable again. Requires
        # `unwalked is not None`: when the failure cannot be attributed to a
        # subtree the walk proved nothing about anything, so nothing clears.
        # A recorded path that is not under what went unseen this run was
        # reached — whether it is readable again, was deleted, or has been
        # filtered out of scope. All three are correct resets, and none of them
        # is a fault.
        recovered = (
            ()
            if unwalked is None
            else tuple(key for key in prior_counts if not _under(key, unwalked))
        )
        # Re-admit what the recovered subtrees hold, in the very run that
        # observes the recovery. This is what makes it safe to stop re-pending
        # a quarantined subtree: a file edited while its directory was
        # unreadable lost its watcher event, so without this nothing would ever
        # retry it. Widening-only, exactly like the H1 and drift unions
        # (§3.2 rule 1). Unattributable rows are deliberately excluded — no
        # prefix describes them, and unioning "everything" would silently turn
        # a scoped run into a whole-index hash; those force a full walk through
        # the promotion policy in `jobs` instead.
        recovered_prefixes = tuple(k for k in recovered if is_attributable_prefix(k))
        if recovered_prefixes and candidates is not None:
            readmit = {p for p in discovered if _under(p, recovered_prefixes)}
            if readmit:
                logger.info(
                    "index run %s: %d director(ies) walkable again — re-hashing "
                    "%d file(s) under them to catch edits made while they were "
                    "unreadable",
                    run_id,
                    len(recovered_prefixes),
                    len(readmit),
                )
                candidates = gitfast.CandidatePathSet(set(candidates) | readmit)

        # Drift self-heal (ADR-49): the state DB can claim files are indexed
        # while Qdrant holds none of their points — an externally dropped or
        # recreated collection. Hash comparison then sees no content change,
        # the run writes nothing, and search stays empty for those files
        # permanently. Gate cheaply: one exact project-scoped point count vs
        # the stored chunk total. Only a mismatch pays for the per-file
        # scroll. The total gate can miss *balanced* drift (one file over by
        # N points, another under by N) — accepted to keep the steady state
        # at a single count query.
        drifted: set[str] = set()
        orphan_paths: list[str] = []
        stored_chunk_counts = state.get_file_chunk_counts(conn, project_id)
        expected_points = sum(stored_chunk_counts.values())
        actual_points = await asyncio.to_thread(store.count_project_points, project_id)
        if actual_points != expected_points:
            if paths is not None:
                # Scoped (watcher) run: keep its narrow candidate set and its
                # never-advance-anchor rule — surface the drift only. A full
                # reindex is what heals it.
                logger.warning(
                    "index run %s: drift detected project=%s expected=%d "
                    "actual=%d — scoped run, warning only; run a full reindex "
                    "to self-heal",
                    run_id,
                    project_id,
                    expected_points,
                    actual_points,
                )
            else:
                per_file = await asyncio.to_thread(
                    store.per_file_point_counts, project_id
                )
                discovered_set = set(discovered)
                drifted = {
                    rel
                    for rel, cc in stored_chunk_counts.items()
                    if per_file.get(rel, 0) != cc
                }
                # Points for a file_path neither tracked in state nor present
                # on disk: no other prune path covers them and they keep the
                # drift gate firing every run.
                #
                # Discovery failures make "absent from disk" unprovable, so
                # they must not feed this either — same purge-on-doubt rule as
                # the deletion guard below. A path missing from `discovered_set`
                # because its stat or its parent's scandir failed says nothing
                # about whether the file exists, and a file live on disk whose
                # state row is missing (a crash between `upsert_chunks` and
                # `upsert_file`) is exactly the shape that lands here: pruning
                # it deletes searchable points for a live file. A dir-level
                # failure hides its whole subtree and cannot enumerate what it
                # hid, so every path under it is spared; file-level failures
                # name their paths, so only those are. Paths elsewhere were
                # walked normally and stay provable. Cost of skipping is one
                # more drift-gate firing next run; cost of pruning wrongly is
                # content gone from search.
                #
                # `unscreened` is spared on the same rule (ADR-58): under a
                # directory whose ignore rules never loaded, "not in
                # discovered_set" can mean "wrongly excluded", not "gone".
                errored_files = {p for p, _ in disc_errors.files}
                orphan_paths = (
                    []
                    if unwalked is None or unscreened is None
                    else [
                        p
                        for p in per_file
                        if p not in stored_chunk_counts
                        and p not in discovered_set
                        and p not in errored_files
                        and not _under(p, unwalked)
                        and not _under(p, unscreened)
                    ]
                )
                if disc_errors.dirs:
                    logger.warning(
                        "index run %s: %d directory discovery error(s) — orphan "
                        "point pruning %s (absence is not evidence); a clean "
                        "run prunes them",
                        run_id,
                        len(disc_errors.dirs),
                        "skipped for the whole run"
                        if unwalked is None
                        else "skipped under the failed director(ies)",
                    )
                if disc_errors.unscreened:
                    # Reported separately, and not folded into the line above,
                    # because a screening fault can skip pruning with NO
                    # directory error to explain it — that line would never
                    # fire and the skip was the one thing about this run an
                    # operator could not see anywhere (PR #31 review). The
                    # screening warning further down talks about deletions held
                    # back, which is a different decision on a different set.
                    logger.warning(
                        "index run %s: %d director(ies) had unloadable ignore "
                        "rules — orphan point pruning %s, because a file that "
                        "the missing rules wrongly excluded is absent from the "
                        "walk without being absent from disk; a run that loads "
                        "them prunes normally",
                        run_id,
                        len(disc_errors.unscreened),
                        "skipped for the whole run"
                        if unscreened is None
                        else "skipped under those director(ies)",
                    )
                logger.warning(
                    "index run %s: drift detected project=%s expected=%d "
                    "actual=%d — re-embedding %d drifted file(s), pruning %d "
                    "orphan path(s)",
                    run_id,
                    project_id,
                    expected_points,
                    actual_points,
                    len(drifted),
                    len(orphan_paths),
                )
                if candidates is not None and drifted:
                    # Widening-only, exactly like the H1 dirty-paths union
                    # above: forces partition to re-hash drifted files so the
                    # re-embed uses their true current hash (rule 1 safe).
                    # When candidates is None, partition already hashes the
                    # whole tree, so no union is needed.
                    candidates = gitfast.CandidatePathSet(set(candidates) | drifted)

        diff = await asyncio.to_thread(
            hashdiff.partition,
            root_path,
            discovered,
            stored,
            candidates=candidates,
            discovery_errored=disc_errors.files,
        )

        chunks_written = 0
        file_errors: list[tuple[str, str]] = []
        to_index = [*diff.new, *diff.changed]
        if drifted:
            # Drifted-but-unchanged files: content hash still matches state,
            # yet their points are missing/mismatched in Qdrant — exactly what
            # incremental indexing skips. Re-embed is idempotent (deterministic
            # point ids), so this restores the missing points. Files deleted
            # from disk are excluded: they never enter diff.hashes.
            present = set(to_index)
            to_index.extend(
                rel
                for rel in sorted(drifted)
                if rel in diff.hashes and rel not in present
            )
        # Start milestone: counts only, no paths or content (ADR-25).
        logger.info(
            "index run %s: project=%s to_index=%d (new=%d changed=%d deleted=%d "
            "drifted=%d) discovered=%d",
            run_id,
            project_id,
            len(to_index),
            len(diff.new),
            len(diff.changed),
            len(diff.deleted),
            len(drifted),
            len(discovered),
        )
        # Throttle progress lines: the larger of every-50-files and every-10%,
        # so a big repo logs ~10 lines, not thousands. Empty to_index skips the
        # loop entirely, so the /0 case never arises.
        progress_step = max(50, (len(to_index) + 9) // 10)
        for done, rel in enumerate(to_index, start=1):
            # Per-file failure containment (ADR-41): a bad file is recorded
            # and skipped — its old chunks keep serving, its state row stays
            # out of date so the next run retries it. Exception, not
            # BaseException: cancellation must still abort the run.
            try:
                text = await asyncio.to_thread(_read_text, root_path, rel)
                language = detect_language(rel)
                file_hash = diff.hashes[rel]
                chunks = await asyncio.to_thread(
                    chunk_file,
                    text,
                    language=language,
                    file_path=rel,
                    file_hash=file_hash,
                )
                if chunks:
                    vectors: list[list[float]] = []
                    for i in range(0, len(chunks), batch_size):
                        batch = chunks[i : i + batch_size]
                        vectors.extend(
                            await embedder.embed_documents([c.text for c in batch])
                        )
                    # Shielded, then awaited on cancel: asyncio delivers
                    # CancelledError at the await while the worker thread runs
                    # on, so a plain `await asyncio.to_thread(...)` lets an
                    # abandoned write land after a concurrent delete_project
                    # wipe — orphaning those points under a dead project_id
                    # (nothing prunes them; every prune path is scoped to a
                    # live project). Cancellation still aborts the run; it
                    # just waits out the one write already in flight.
                    upsert = asyncio.ensure_future(
                        asyncio.to_thread(
                            store.upsert_chunks,
                            project_id,
                            chunks,
                            vectors,
                            embedding_model=embedder.model_id,
                        )
                    )
                    try:
                        await asyncio.shield(upsert)
                    except asyncio.CancelledError:
                        await asyncio.gather(upsert, return_exceptions=True)
                        raise
                # New points first, stale points after: chunk ids embed the file
                # hash, so old content lives at different ids and must be pruned —
                # but only once the replacement is searchable. A failure above
                # leaves the old chunks serving; a failure below leaves brief
                # duplicates that the next (self-healing) run prunes.
                await asyncio.to_thread(
                    store.delete_file_chunks,
                    project_id,
                    [rel],
                    exclude_file_hash=file_hash,
                )
                state.upsert_file(
                    conn,
                    project_id,
                    rel,
                    file_hash,
                    language=language,
                    chunk_count=len(chunks),
                )
                chunks_written += len(chunks)
            except Exception as exc:  # noqa: BLE001 — contained per ADR-41
                file_errors.append((rel, str(exc) or type(exc).__name__))
                # Path at DEBUG only: it can reveal repo structure if logs are
                # pasted into a bug report (telemetry.py precedent). Never the
                # file contents.
                logger.debug("index run %s: file %s failed: %s", run_id, rel, exc)
            if on_progress is not None:
                on_progress(done, len(to_index), chunks_written)
            if done % progress_step == 0 or done == len(to_index):
                logger.info(
                    "index run %s: %d/%d files chunks=%d",
                    run_id,
                    done,
                    len(to_index),
                    chunks_written,
                )

        # A directory-level discovery error means part of the tree was never
        # walked, so "absent from discovery" is not deletion evidence *there*.
        # Stale chunks beat purged live files; a clean next run detects real
        # deletions again. Scoped to the unwalked subtrees rather than the
        # whole project: a directory that is permanently unreadable (root-owned,
        # dead mount) would otherwise freeze deletion processing for every
        # other path forever, and deletions outside it were provable all along
        # — os.walk loses only the failing directory's subtree. When the
        # failures cannot be attributed to a subtree (`unwalked is None`) the
        # old project-wide suppression is exactly right and still applies
        # (ADR-54).
        files_deleted = 0
        # Suppressed deletions are unverified files, not deleted ones: their
        # stored hash may be stale and this run never read them. They must be
        # re-queued individually (the caller re-pends `failed_paths`) — a
        # scoped retry matches its candidate set EXACTLY, with no prefix
        # expansion, so re-pending only the errored directory would make the
        # retry carry every stored child forward as unchanged and clear the
        # pending row, stranding the edit until a manual full run. Any path in
        # here that really was deleted is simply re-detected and deleted by the
        # next run, which then clears its pending row.
        unverified: tuple[str, ...] = ()
        # Deletions held back because the ignore rules that decide membership
        # could not be loaded (ADR-58). Kept OUT of `unverified` on purpose:
        # that name feeds the re-pend and the ADR-56 quarantine, and these
        # paths need neither. Discovery walks the entire tree on every run, and
        # deletion is recomputed from that walk — so the first run that reads
        # the .gitignore again reaches the right answer on its own, with no
        # retry queued and no backlog to drain. What it does drive is the
        # anchor: a stored file wrongly excluded this run is a file whose hash
        # may now be stale, which is exactly what the anchor must not skip past.
        screening_held: tuple[str, ...] = ()
        if diff.deleted:
            if unwalked is None:
                provable: tuple[str, ...] = ()
                unverified = tuple(diff.deleted)
            elif unwalked:
                provable = tuple(p for p in diff.deleted if not _under(p, unwalked))
                unverified = tuple(p for p in diff.deleted if _under(p, unwalked))
            else:
                provable = tuple(diff.deleted)
            # Second filter, applied only to what the first one already cleared
            # — so a path blocked by both is counted once, as unverified.
            if unscreened is None:
                screening_held = provable
                provable = ()
            elif unscreened:
                screening_held = tuple(p for p in provable if _under(p, unscreened))
                provable = tuple(p for p in provable if not _under(p, unscreened))
            if provable:
                await asyncio.to_thread(store.delete_file_chunks, project_id, provable)
                state.delete_files(conn, project_id, provable)
                files_deleted = len(provable)

        # Which unverified paths the caller should re-pend (ADR-56). Note what
        # this block does NOT touch: `provable`, `files_deleted`, and the
        # deletion above already happened on ADR-51/54's terms alone. Quarantine
        # decides only whether a path is queued for RETRY — never whether it is
        # deleted — so a quarantined subtree's chunks keep serving search
        # forever, exactly as they did before this change.
        repend = unverified
        if unverified and quarantined:
            if unwalked is None:
                # No prefix describes what went unseen, so every stored path is
                # unverified and the choice is all-or-nothing. Stand down only
                # when EVERY directory reported this run is quarantined: one
                # fresh failure means this run's doubt is new, and new doubt is
                # exactly what the retry exists for.
                if disc_errors.dirs and reported_now <= quarantined:
                    repend = ()
            else:
                blocked = tuple(p for p in unwalked if p in quarantined)
                if blocked:
                    repend = tuple(p for p in unverified if not _under(p, blocked))
        suppressed = len(unverified) - len(repend)
        if suppressed:
            logger.warning(
                "index run %s: %d path(s) under %d quarantined director(ies) are "
                "no longer being re-queued for retry — their indexed content is "
                "KEPT and still searchable, not deleted, but it is no longer "
                "being re-verified either. Fix the director(ies) (or narrow the "
                "project's index scope) and the next run re-hashes them "
                "automatically",
                run_id,
                suppressed,
                len(reported_now & quarantined),
            )

        if orphan_paths:
            # Drift cleanup: points whose file_path is neither tracked in
            # state nor on disk. No state rows correspond to them, so this
            # only prunes Qdrant; without it the drift gate keeps firing.
            await asyncio.to_thread(store.delete_file_chunks, project_id, orphan_paths)

        # Hash-time failures (H7 carry-forward) are per-file failures too:
        # the file's true state is unknown this run, its stored hash may be
        # stale, and — unlike chunk/embed failures — it never entered
        # to_index, so without this it would be invisible to every guard
        # below and silently stranded by the next fast path.
        #
        # `diff.errored` carries both stages: hashdiff's own read failures and
        # the file-level discovery failures handed to it as
        # `discovery_errored`. They are disjoint (a file discovery could not
        # screen never reaches `discovered`, so it is never hashed), and the
        # stage belongs in the message — an operator chasing a permission
        # error should not be pointed at hashing when the stat failed.
        discovery_failed = {path for path, _ in disc_errors.files}
        hash_errors = [
            (
                path,
                f"{'discovery' if path in discovery_failed else 'hash'} failed: {msg}",
            )
            for path, msg in diff.errored
        ]
        # Dir-level discovery errors are run failures too: an unseen subtree
        # leaves its files' true state unknown, so they count toward
        # `files_failed` and `clean_run` exactly like hash failures. They no
        # longer block the anchor, though — ADR-60 carries the stored paths
        # they hid (`unverified`) forward in the dirty set instead, which meets
        # the same guarantee without freezing the project. (File-level
        # discovery errors already arrive here via diff.errored /
        # discovery_errored.)
        #
        # Kept in their OWN list rather than folded into hash_errors, because
        # they are the only entries here that are not file paths — a directory
        # rel, or the `<root>` sentinel. They belong in run_file_errors (an
        # operator needs to see which subtree failed) but must never reach
        # `failed_paths`, which the caller re-pends as file rows: a scoped
        # retry matches its candidate set exactly, so a directory candidate
        # matches nothing, indexes nothing, and then clears its own pending
        # row. The stored files under that subtree are already re-queued the
        # right way, as themselves, via `unverified`.
        #
        # A quarantined directory says so here, so the run row explains its own
        # backlog: an operator looking at "why is this failing every run and
        # why did the awaiting-reindex list empty out?" gets both halves in one
        # place, rather than having to correlate a log line with a table.
        dir_errors = [
            (
                dir_rel,
                f"discovery failed: {msg}"
                + (
                    " — quarantined after "
                    f"{prior_counts.get(dir_rel, 0) + 1} consecutive failure(s):"
                    " stored paths under it are no longer re-queued for retry."
                    " They are NOT deleted; a run that walks this directory"
                    " again re-hashes them"
                    if dir_rel in quarantined
                    else ""
                ),
            )
            for dir_rel, msg in disc_errors.dirs
        ]
        # Screening faults (ADR-58). Recorded so an operator can see them, and
        # kept out of `total_failed` / `all_failed` / `run_error`, because
        # nothing failed to be indexed — the run's results may just be the
        # wrong shape.
        #
        # The synthetic key prefixes are load-bearing, not decoration.
        # `record_file_errors` is INSERT OR REPLACE on (run_id, path), and the
        # r-without-x case that motivates this whole change produces a REAL
        # `errors.files` row for `<dir>/.gitignore` at the same time as the
        # screening row for `<dir>` — different questions, and on a root
        # .gitignore the keys would otherwise be one character apart. Round 6
        # of PR #24 already lost an operator's errno to exactly this collision,
        # with a generic sentinel overwriting the real one. A real rel path can
        # never begin with `<`, so these cannot collide with anything.
        screening_errors = [
            (f"<screening>:{dir_rel}", f"screening degraded: {msg}")
            for dir_rel, msg in disc_errors.unscreened
        ] + [
            (f"<identity>:{dir_rel}", f"screening degraded: {msg}")
            for dir_rel, msg in disc_errors.unidentified
        ]
        if file_errors or hash_errors or dir_errors or screening_errors:
            state.record_file_errors(
                conn,
                run_id,
                [*file_errors, *hash_errors, *dir_errors, *screening_errors],
            )
        if screening_errors:
            logger.warning(
                "index run %s: %d discovery screening fault(s) — this run's "
                "results may be over- or under-inclusive under %s. %d deletion(s) "
                "held back as a result; indexed content is untouched and a run "
                "that loads the rules again reaches the right answer on its own",
                run_id,
                len(screening_errors),
                ", ".join(
                    sorted(
                        {
                            dir_rel or "<root>"
                            for dir_rel, _ in (
                                *disc_errors.unscreened,
                                *disc_errors.unidentified,
                            )
                        }
                    )
                ),
                len(screening_held),
            )
        # Fold this run's directory result into the ledger. Deliberately AFTER
        # the file loop and the re-admission above: a crash before this point
        # leaves the ledger untouched, so the next run redoes the union rather
        # than believing a recovery that never got applied.
        state.reconcile_unwalkable_dirs(
            conn,
            project_id,
            reported=disc_errors.dirs,
            cleared=recovered,
            quarantine_after=unwalkable_quarantine_runs,
        )
        # Partial failure is still a completed run (ADR-41); a run where
        # every file failed is not "done" by any honest reading — likely an
        # infrastructure problem (store/embedder down) wearing per-file dress.
        # Two distinct total-failure shapes: every chunk/embed attempt failed
        # (existing check), or every hash attempt failed and nothing else in
        # the whole discovered set is in a known-good state (PR #14 review) —
        # a whole-tree permission/network-fs outage, where every candidate
        # lands in hash_errors and `to_index` stays empty, so the chunk/embed
        # check alone would never see it and the run would report "done"
        # despite indexing nothing. `verified + skipped == 0` (not just
        # `verified == 0`) is required: under the git fast path a single
        # transient failure on a narrow one-file candidate set also leaves
        # verified at 0, but the rest of the tree is legitimately healthy via
        # `skipped` (fast-path carry-forward, never in doubt) — that stays a
        # contained per-file failure, not a run-wide outage.
        #
        # The chunk/embed check needs the same remainder guard: every file in
        # to_index hashed successfully (each is counted in `verified`), so the
        # known-good remainder is `verified - len(to_index) + skipped`. With a
        # non-zero remainder, "every attempted file failed" is a scoped run's
        # one edited file hitting a transient embed/store error while the rest
        # of the tree is provably healthy — contained per ADR-41, not an
        # outage. Only when nothing outside to_index is in a known-good state
        # does total chunk/embed failure mean the infrastructure is down.
        known_good_remainder = diff.verified - len(to_index) + diff.skipped
        chunk_embed_all_failed = (
            bool(to_index)
            and len(file_errors) == len(to_index)
            and known_good_remainder == 0
        )
        # dir_errors counts here as well as hash_errors: a root that could not
        # be scanned at all produces ONLY a dir error, and that is the exact
        # whole-tree outage this check exists to catch.
        hash_all_failed = (
            bool(hash_errors) or bool(dir_errors)
        ) and diff.verified + diff.skipped == 0
        all_failed = chunk_embed_all_failed or hash_all_failed
        total_failed = len(file_errors) + len(hash_errors) + len(dir_errors)
        # `total_failed` counts directory entries too, so the file-count
        # wording lies for the shape that produces ONLY dir errors — an
        # unreadable or empty root reported "all 1 files failed" with zero
        # files failed (PR #24 review).
        if not all_failed:
            run_error = None
        elif dir_errors and not file_errors and not hash_errors:
            run_error = (
                f"discovery failed for {len(dir_errors)} location(s); "
                "no files could be verified"
            )
        else:
            run_error = f"all {total_failed} files failed"
        # Computed BEFORE `finish_run` so the run row can carry the verdict
        # rather than leave a reader to reconstruct it (ADR-58). Both drains
        # below are gated on it, and so is `state.last_full_run_was_clean`,
        # which used to re-derive it as `files_failed == 0` — true only while
        # every term here was a file-level failure, which stopped being true
        # when dir errors were added (PR #30 round 2) and again with
        # `screening_held`, which `files_failed` deliberately excludes because
        # nothing failed to index. A degraded run therefore reported
        # `files_failed == 0` while draining nothing, and the promotion policy
        # counted a dirty set it could not shrink (PR #31 review). One writer,
        # one persisted answer.
        #
        # `screening_held` earns its place here for the same reason as the
        # others: a stored file that a lost .gitignore pushed out of the
        # results is a file this run did not hash, so its stored hash may be
        # stale, and anchoring past it would leave the next fast path with no
        # reason to look at it again. The test is on what was actually held
        # back rather than on the fault itself, so an unreadable .gitignore
        # that excludes nothing currently indexed — the common case — still
        # advances the anchor instead of latching the project onto full walks.
        clean_run = (
            not file_errors
            and not hash_errors
            and not dir_errors
            and not screening_held
        )
        # ADR-60. `clean_run` above is the run's HEALTH verdict and keeps every
        # term it had. The two drains below ask a different question — "which
        # files is this run unsure about?" — and its honest answer is a SET,
        # not a boolean.
        #
        # Every stored path lands in exactly one bucket, and this names the
        # ones left in doubt: hashed-then-failed-to-index (`file_errors`),
        # failed to hash or to be screened (`hash_errors`, which carries the
        # stale stored hash forward), never seen because a directory could not
        # be walked (`unverified`), and held back from deletion because the
        # ignore rules that decide membership never loaded (`screening_held`).
        # The enumeration is exhaustive rather than hopeful: `diff.deleted` is
        # `stored - seen`, and the deletion block above partitions all of it
        # into `unverified` / `screening_held` / `provable`, the last of which
        # leaves `stored` entirely.
        unresolved = frozenset(p for p, _ in (*file_errors, *hash_errors)).union(
            unverified, screening_held
        )
        # So the gate becomes "advance when the doubt can be NAMED", not
        # "advance when there is none". What the old gate protected — the next
        # fast path must never skip a file whose state is unknown — is
        # delivered by recording those paths in `dirty_paths`, which already
        # means "owed re-admission next run" and which the H1 union above feeds
        # straight back into the candidate set. Blocking instead froze
        # `last_indexed_commit` for the whole project on one unreadable
        # directory (or one unreadable FILE, which leaves no ledger row at
        # all), and `compute_candidates` then diffed against an ever-older
        # commit forever (issue #28).
        #
        # Two conditions still block completely, and they are the point:
        #
        # * `unwalked is None` — the `<root>` sentinel, a path outside the
        #   root, or `follow_symlinks`. `unverified` does technically enumerate
        #   the paths even then, so this is a judgement rather than a
        #   necessity: under `<root>` that enumeration is the ENTIRE index, so
        #   advancing would write every path in the project into a JSON column
        #   on every run to buy a next run that hashes everything anyway. The
        #   walk proved nothing; ADR-57's trigger 1 already forces a full walk
        #   for these projects.
        # * `all_failed` — §3.2 rule 4 is untouched. A run that finishes
        #   `failed` never advances the anchor.
        #
        # Note this SUBSUMES the old rule rather than sitting beside it: when
        # `clean_run` is true, all four terms are empty and `unwalked` is `()`,
        # so `unresolved` is empty and both branches do exactly what they did
        # before. A healthy project cannot observe this change.
        may_advance = not all_failed and unwalked is not None
        state.finish_run(
            conn,
            run_id,
            "failed" if all_failed else "done",
            files_total=len(discovered),
            files_changed=len(to_index),
            chunks_written=chunks_written,
            fast_path_used=fast_path_active,
            candidate_count=len(candidates)
            if fast_path_active and candidates is not None
            else None,
            files_failed=total_failed,
            clean=clean_run,
            error=run_error,
        )
        if paths is not None:
            # Scoped runs never advance the anchor, so the H1 dirty-set write
            # below never fires for them — persist what they DID index here,
            # or content indexed only by scoped runs is invisible to the H1
            # re-admission and a revert-while-unwatched stays stale forever.
            # Union-only: can only widen the next fast path's candidate set
            # (§3.2 rule-1 safe).
            failed = {path for path, _ in file_errors}
            indexed_ok = [rel for rel in to_index if rel not in failed]
            if indexed_ok:
                state.add_dirty_paths(conn, project_id, indexed_ok)
        # The anchor may advance past a failure whose paths this run can name,
        # because those paths ride along in the same write (ADR-60). It may not
        # advance past one it cannot: `may_advance` is computed above, next to
        # the `unresolved` set it travels with.
        #
        # Tracked rather than re-derived for the log below: `may_advance` says
        # the run was ALLOWED to record a position, not that it did. A scoped
        # run has no anchor to write (`head is None`) and is not a full walk
        # (`candidates is not None`), so it takes neither branch however clean
        # it was — claiming otherwise would be a log line that lies about the
        # commonest run in the service.
        position_recorded = False
        if head is not None and may_advance:
            # Persist the working-tree-dirty set with the anchor (H1). The
            # fast path already captured it at run start (git_info); a
            # full-walk run re-queries `git status` here.
            if git_info is not None:
                new_dirty = git_info.dirty_paths
            else:
                new_dirty = (
                    await asyncio.to_thread(gitfast.status_dirty_paths, root_path)
                    or frozenset()
                )
            state.set_last_indexed_commit(
                conn, project_id, head, dirty_paths=set(new_dirty) | unresolved
            )
            position_recorded = True
        elif candidates is None and may_advance:
            # FULL walk with no anchor to record — a non-git root, or git
            # unavailable. `set_last_indexed_commit` is the only other writer
            # that shrinks the H1 dirty set, and it needs a commit, so without
            # this the union in `add_dirty_paths` only ever grows: on a non-git
            # watched project every scoped run adds what it indexed and nothing
            # ever removes it, and indexer's H1 re-admission unions the whole
            # accumulation back into the next scoped candidate set. It would
            # creep toward "re-hash every file ever indexed" on every watcher
            # run.
            #
            # Safe here and only here because a full walk hashed every
            # discovered file — so the only stored hashes still in doubt are
            # the ones it could not reach, which is precisely `unresolved`.
            # Writing that (rather than clearing outright) is what lets this
            # branch run at all on a project with a contained fault; before
            # ADR-60 it was gated on `clean_run` and a single permanently
            # unreadable path pinned the set forever (issue #28).
            state.set_dirty_paths(conn, project_id, unresolved)
            position_recorded = True
        if unresolved and position_recorded:
            # The visibility half of issue #28: the old behaviour was a
            # `last_indexed_commit` that silently stopped moving, with nothing
            # anywhere saying why. Say plainly that the position advanced and
            # what it is carrying, so "it moved despite errors" is something an
            # operator can read rather than infer. Count only — the paths are
            # at DEBUG below, per ADR-25 exposure.
            #
            # Deliberately NOT reported against `total_failed`: screening-held
            # deletions are carried here but excluded from that count (nothing
            # failed to index), so pairing the two printed "despite 0
            # failure(s)" on exactly the run this line exists to explain. The
            # carried count is the honest one — it is the number of paths this
            # sentence is actually about.
            logger.info(
                "index run %s: index position recorded with %d path(s) still "
                "unverified — they are carried forward for re-hashing, so none "
                "of them is skipped and the next run re-examines every one",
                run_id,
                len(unresolved),
            )
        # Completion milestone: counts + duration, so a finished run is visible
        # even when the dashboard isn't being watched. errors is a count; the
        # failed paths themselves stay at DEBUG (ADR-25 exposure).
        logger.info(
            "index run %s finished: status=%s files_indexed=%d chunks=%d errors=%d "
            "took=%.1fs",
            run_id,
            "failed" if all_failed else "done",
            len(to_index) - len(file_errors),
            chunks_written,
            total_failed,
            time.perf_counter() - run_started,
        )
        if total_failed:
            logger.debug(
                "index run %s failed paths: %s",
                run_id,
                ", ".join(
                    path for path, _ in (*file_errors, *hash_errors, *dir_errors)
                ),
            )
        return IndexResult(
            project_id=project_id,
            run_id=run_id,
            files_total=len(discovered),
            files_indexed=len(to_index) - len(file_errors),
            files_deleted=files_deleted,
            chunks_written=chunks_written,
            fast_path_used=fast_path_active,
            candidate_count=len(candidates)
            if fast_path_active and candidates is not None
            else None,
            files_failed=total_failed,
            # `unverified` is a retry list, not an error list: it carries no
            # run_file_errors row and is not counted in files_failed (nothing
            # failed on those paths — the run simply never reached them).
            # `dir_errors` is deliberately absent: every entry here is re-pended
            # as a file row by the caller, and a directory or the `<root>`
            # sentinel can never match a scoped run's exact candidate set.
            failed_paths=(
                *(path for path, _ in (*file_errors, *hash_errors)),
                *repend,
            ),
            unverified_suppressed=suppressed,
            discovery_degraded=len(screening_errors),
        )
    except BaseException as exc:
        # BaseException: CancelledError (e.g. server shutdown) must also mark
        # the run failed, or it would sit "running" forever.
        state.finish_run(conn, run_id, "failed", error=str(exc) or type(exc).__name__)
        raise

noesis.core.jobs

Job manager — one place both adapters launch and inspect index runs.

Part of the Core Engine's "Job/State manager" box (§3.1). REST (POST /projects, POST /projects/{id}/reindex) and the MCP reindex tool must behave identically (two thin adapters over one core), so this module owns the single launch path: open a run row, hand back ids immediately, and index in a background task tracked in ctx.jobs so the app lifespan can cancel orphans on shutdown.

M8 additions (ADR-40): watcher-scoped launches (paths narrows the candidate set, triggered_by records provenance), in-memory live progress per run (ctx.progress, read by the dashboard — deliberately not persisted: live progress of a dead process is meaningless), and pending-change clearing once a run has examined the files.

logger = logging.getLogger(__name__) module-attribute

launch_index_run(ctx, root_path, *, paths=None, triggered_by='manual', force=False)

Register (or re-open) the project and start indexing in the background. Returns the 202-style acceptance body shared verbatim by REST and MCP.

Fails fast with ValueError before touching state when root_path is missing or not a directory (an agent gets the answer now instead of polling a background failure), and on the mixed-model guard (state.register_project). If a run is already running for this project, launches nothing (a second concurrent index would race on the same collection and state rows) and returns that run's id with status: "already_running" — a distinct status so a scoped/watcher caller can tell its launch was skipped and re-arm its retry (H3). A real launch returns status: "accepted".

force is passed straight to :func:execute_run: it lets a discovery result of zero files count as deletion evidence when state still tracks files (ADR-55). Only an operator can make that call — nothing observable separates an emptied root from an unmounted one — so it is never set by the watcher, and the REST route is the only caller that exposes it. The MCP reindex tool deliberately does not: its caller is an agent.

Source code in src/noesis/core/jobs.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def launch_index_run(
    ctx: _ContextLike,
    root_path: str,
    *,
    paths: Sequence[str] | None = None,
    triggered_by: str = "manual",
    force: bool = False,
) -> dict[str, str]:
    """Register (or re-open) the project and start indexing in the
    background. Returns the 202-style acceptance body shared verbatim by
    REST and MCP.

    Fails fast with ValueError before touching state when *root_path* is
    missing or not a directory (an agent gets the answer now instead of
    polling a background failure), and on the mixed-model guard
    (state.register_project). If a run is already ``running`` for this
    project, launches nothing (a second concurrent index would race on the
    same collection and state rows) and returns that run's id with
    ``status: "already_running"`` — a distinct status so a scoped/watcher
    caller can tell its launch was skipped and re-arm its retry (H3). A
    real launch returns ``status: "accepted"``.

    *force* is passed straight to :func:`execute_run`: it lets a discovery
    result of zero files count as deletion evidence when state still tracks
    files (ADR-55). Only an operator can make that call — nothing observable
    separates an emptied root from an unmounted one — so it is never set by
    the watcher, and the REST route is the only caller that exposes it. The
    MCP `reindex` tool deliberately does not: its caller is an agent."""
    if not os.path.isdir(root_path):
        raise ValueError(f"root_path is not an existing directory: {root_path!r}")
    project_id = state.register_project(ctx.conn, root_path, ctx.embedder.model_id)
    # Promote a scoped run to a full walk when the scoped path has stopped
    # paying for itself (ADR-57). Decided HERE, before the run row is opened,
    # because `paths` feeds both `execute_run` and the `clear_pending_changes`
    # below — setting it to None in one place keeps the run and its pending
    # clear describing the same thing. Doing it inside `execute_run` instead
    # would leave the caller clearing only the old scoped set after a walk that
    # examined everything.
    #
    # Never promoted under `force`: that flag lets an empty discovery result
    # purge the index, and applying it to a whole tree the caller had
    # deliberately scoped is not what the operator asserted. (Unreachable
    # today — the only `force` caller passes no paths — but the guard is the
    # cheap half of that pairing.)
    if paths is not None and not force:
        reason = _promotion_reason(ctx, project_id, paths)
        if reason is not None:
            logger.info(
                "project %s: promoting a %d-path scoped run to a full walk (%s)",
                project_id,
                len(paths),
                reason,
            )
            paths = None
    # Atomic check-and-insert (state.try_start_run, BEGIN IMMEDIATE): a plain
    # read-then-insert is race-free on one event loop but not across the
    # dual-transport deployment (HTTP + stdio MCP sharing this DB), where two
    # near-simultaneous launches could both pass the check and race two index
    # runs onto the same collection.
    # max_concurrent (ADR-85) is enforced inside that same transaction, the
    # only place a cap can be atomic across the HTTP + stdio deployment.
    # It raises IndexCapacityReached rather than returning a status; every
    # caller of this function handles it explicitly.
    run_id, created = state.try_start_run(
        ctx.conn,
        project_id,
        triggered_by=triggered_by,
        scoped=paths is not None,
        max_concurrent=ctx.indexing.max_concurrent_index_runs,
    )
    if not created:
        return {
            "project_id": project_id,
            "run_id": run_id,
            "status": "already_running",
        }
    # Cut point for the pending clear: rows re-dirtied after this survive.
    started_iso = datetime.now(timezone.utc).isoformat()
    ctx.progress[run_id] = {
        "files_done": None,
        "files_to_index": None,
        "chunks_written": 0,
        "monotonic_start": time.monotonic(),
    }

    def _on_progress(done: int, total: int, chunks: int) -> None:
        entry = ctx.progress.get(run_id)
        if entry is not None:
            entry["files_done"] = done
            entry["files_to_index"] = total
            entry["chunks_written"] = chunks

    async def _run() -> None:
        try:
            result = await execute_run(
                ctx.conn,
                ctx.store,
                ctx.embedder,
                root_path,
                project_id,
                run_id,
                batch_size=ctx.embed_batch_size,
                git_fast_path=ctx.git_fast_path,
                paths=paths,
                force=force,
                unwalkable_quarantine_runs=(
                    getattr(ctx, "indexing", None) or IndexingSettings()
                ).unwalkable_quarantine_runs,
                on_progress=_on_progress,
            )
        except Exception:
            # execute_run already marked the run failed; log for the operator.
            logger.exception("index run %s failed", run_id)
        else:
            # The run examined these files — clear their pending rows, but
            # only up to the launch timestamp so a file re-dirtied mid-run
            # stays pending (resolved toward re-examination, ADR-40).
            state.clear_pending_changes(
                ctx.conn, project_id, paths=paths, before=started_iso
            )
            # Files that failed per-file containment (ADR-41) go straight
            # back to pending: their state rows are stale, and without a
            # pending row the watcher would never auto-retry them — only a
            # manual full run would (PR #10 review). No hot loop: a retry
            # fires only on the next event/quiet cycle or manual action.
            if result.failed_paths:
                state.upsert_pending_changes(
                    ctx.conn,
                    project_id,
                    [(p, "modified") for p in result.failed_paths],
                )

    task = asyncio.create_task(_run())
    ctx.jobs[run_id] = task

    def _cleanup(_t: asyncio.Task) -> None:
        ctx.jobs.pop(run_id, None)
        ctx.progress.pop(run_id, None)

    task.add_done_callback(_cleanup)
    return {"project_id": project_id, "run_id": run_id, "status": "accepted"}

run_progress(ctx, run_id)

Live progress for a running run: percent, counts, elapsed, ETA. None when the run is not tracked (finished, or another process's). ETA is naive linear extrapolation over files processed — honest enough for a progress bar, no smoothing pretence.

Source code in src/noesis/core/jobs.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def run_progress(ctx: _ContextLike, run_id: str) -> dict[str, Any] | None:
    """Live progress for a running run: percent, counts, elapsed, ETA.
    None when the run is not tracked (finished, or another process's).
    ETA is naive linear extrapolation over files processed — honest enough
    for a progress bar, no smoothing pretence."""
    entry = ctx.progress.get(run_id)
    if entry is None:
        return None
    done = entry["files_done"]
    total = entry["files_to_index"]
    elapsed = time.monotonic() - entry["monotonic_start"]
    percent: float | None = None
    eta: float | None = None
    if done is not None and total is not None:
        percent = 100.0 if total == 0 else round(done / total * 100.0, 1)
        if done > 0 and total > done:
            eta = round(elapsed / done * (total - done), 1)
        elif total == done:
            eta = 0.0
    return {
        "files_done": done,
        "files_to_index": total,
        "chunks_written": entry["chunks_written"],
        "percent": percent,
        "elapsed_s": round(elapsed, 1),
        "eta_s": eta,
    }

index_status(ctx, project_id) async

Latest run for a project, shaped identically for REST and MCP.

A registered project with no runs yet reports never_indexed with the run fields nulled — a stable shape beats a shape-shifting one for agent consumers.

Async so the quick state.* reads stay on the event loop (the shared sqlite conn is loop-owned; a worker-thread read can interleave inside another op's open BEGIN IMMEDIATE transaction) while only the synchronous Qdrant count round-trip is pushed to a worker thread.

drift is reported only when the expected chunk total held still across that round-trip and still disagreed with the store. The cost of that rule is worth stating: while a run is actively committing, drift reads False even if the store genuinely lost data — the first call after the run settles reports it. A false negative for a few seconds beats a false positive on every status poll during every index run.

unwalkable_dirs / quarantined_dirs (ADR-56) are the coverage half of the same health picture: directories discovery could not walk, and the subset that has failed long enough for their contents to stop being re-queued. Both zero is the healthy state. Non-zero does not mean anything was deleted — nothing under an unwalked directory is ever purged — it means what is indexed there cannot be proven current.

embedder_assets/embedder_ready mirror /healthz's ADR-77/78 fields (issue #47 finding 4, PR #50 round-4 review) — this is the shared REST/MCP status shape, so an MCP-only (stdio) caller with no HTTP surface to poll can now see the same cold-start warm-up signal a REST caller gets from /healthz. reranker_assets/reranker_ready are the same pair for the optional cross-encoder (issue #52), "disabled" when the reranker.enabled kill switch is off. Computed via prefetch.model_readiness/reranker_readiness, the same functions /healthz calls (PR #50 round-5 review) — not a second copy of the readiness logic kept in sync by hand.

Source code in src/noesis/core/jobs.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
async def index_status(ctx: _ContextLike, project_id: str) -> dict[str, Any]:
    """Latest run for a project, shaped identically for REST and MCP.

    A registered project with no runs yet reports ``never_indexed`` with
    the run fields nulled — a stable shape beats a shape-shifting one for
    agent consumers.

    Async so the quick ``state.*`` reads stay on the event loop (the shared
    sqlite conn is loop-owned; a worker-thread read can interleave inside
    another op's open BEGIN IMMEDIATE transaction) while only the
    synchronous Qdrant count round-trip is pushed to a worker thread.

    ``drift`` is reported only when the expected chunk total held still
    across that round-trip and still disagreed with the store. The cost of
    that rule is worth stating: while a run is actively committing, ``drift``
    reads False even if the store genuinely lost data — the first call after
    the run settles reports it. A false negative for a few seconds beats a
    false positive on every status poll during every index run.

    ``unwalkable_dirs`` / ``quarantined_dirs`` (ADR-56) are the coverage half
    of the same health picture: directories discovery could not walk, and the
    subset that has failed long enough for their contents to stop being
    re-queued. Both zero is the healthy state. Non-zero does not mean anything
    was deleted — nothing under an unwalked directory is ever purged — it means
    what is indexed there cannot be proven current.

    ``embedder_assets``/``embedder_ready`` mirror ``/healthz``'s ADR-77/78
    fields (issue #47 finding 4, PR #50 round-4 review) — this is the shared
    REST/MCP status shape, so an MCP-only (stdio) caller with no HTTP surface
    to poll can now see the same cold-start warm-up signal a REST caller gets
    from ``/healthz``. ``reranker_assets``/``reranker_ready`` are the same
    pair for the optional cross-encoder (issue #52), ``"disabled"`` when the
    ``reranker.enabled`` kill switch is off. Computed via
    ``prefetch.model_readiness``/``reranker_readiness``, the same functions
    ``/healthz`` calls (PR #50 round-5 review) — not a second copy of the
    readiness logic kept in sync by hand."""
    # Index health: what the state DB expects vs what Qdrant actually holds.
    # A mismatch is drift — a vector store that lost data (external collection
    # wipe) while state still reports the files indexed. Surfaced so agents
    # and the dashboard can see it without a reindex; a full reindex heals it.
    expected_chunks = state.expected_chunk_total(ctx.conn, project_id)
    vector_count = await asyncio.to_thread(ctx.store.count_project_points, project_id)
    # Re-read after the count: the Qdrant round-trip is a scheduling point, so
    # a live index run can commit chunks between the two readings. A total
    # that MOVED across that window means neither reading is a stable
    # expectation, so there is nothing to compare the count against — the two
    # readings must agree with each other before a disagreement with the count
    # counts as evidence. (Asking only whether either reading happens to equal
    # the count is not the same test and does not catch the in-flight case:
    # `upsert_chunks` lands points before `upsert_file` commits the row, so
    # mid-run the count sits ABOVE the expected total and both readings differ
    # from it.) Report the fresher figure.
    expected_after = state.expected_chunk_total(ctx.conn, project_id)
    drift = expected_chunks == expected_after and expected_after != vector_count
    expected_chunks = expected_after
    # Coverage health, alongside the store health above (ADR-56). `drift` says
    # the store lost content it should hold; these say part of the TREE was
    # never read, so what is indexed for it may be stale and cannot be proven
    # otherwise. An agent searching a project is entitled to know that before
    # trusting an answer, which is why this rides the shared REST/MCP shape and
    # not just the dashboard.
    unwalkable, quarantined = state.count_unwalkable_dirs(ctx.conn, project_id)
    from noesis.prefetch import UNKNOWN_RERANKER, model_readiness, reranker_readiness

    # Same two points as ``/healthz``'s copy of this call: gathered because the
    # probes are independent and nothing is gained by serializing them (the
    # cost measurement lives on that copy), and ``getattr`` with the sentinel
    # because this function is called with
    # hand-built duck-typed contexts (tests, adapters) that carry no reranker
    # attribute — which must not 500, and must not be reported as "disabled"
    # either, since nobody said it was off.
    (
        (embedder_assets, embedder_ready),
        (
            reranker_assets,
            reranker_ready,
        ),
    ) = await asyncio.gather(
        model_readiness(ctx.embedder),
        reranker_readiness(getattr(ctx, "reranker", UNKNOWN_RERANKER)),
    )
    run = state.get_latest_run(ctx.conn, project_id)
    if run is None:
        return {
            "project_id": project_id,
            "run_id": None,
            "status": "never_indexed",
            "files_total": None,
            "files_changed": None,
            "chunks_written": None,
            "started_at": None,
            "finished_at": None,
            "error": None,
            "expected_chunks": expected_chunks,
            "vector_count": vector_count,
            "drift": drift,
            "unwalkable_dirs": unwalkable,
            "quarantined_dirs": quarantined,
            "embedder_assets": embedder_assets,
            "embedder_ready": embedder_ready,
            "reranker_assets": reranker_assets,
            "reranker_ready": reranker_ready,
        }
    return {
        "project_id": project_id,
        "run_id": run["id"],
        "status": run["status"],
        "files_total": run["files_total"],
        "files_changed": run["files_changed"],
        "chunks_written": run["chunks_written"],
        "started_at": run["started_at"],
        "finished_at": run["finished_at"],
        "error": run["error"],
        "expected_chunks": expected_chunks,
        "vector_count": vector_count,
        "drift": drift,
        "unwalkable_dirs": unwalkable,
        "quarantined_dirs": quarantined,
        "embedder_assets": embedder_assets,
        "embedder_ready": embedder_ready,
        "reranker_assets": reranker_assets,
        "reranker_ready": reranker_ready,
    }