Skip to content

Service & state modules

Configuration, SQLite state store, file watcher, telemetry, and the dashboard read-model.

noesis.core.config

Runtime settings, read once at startup from config.toml (§3.7).

M2 added [embedder] and [qdrant] plus the state-DB path; M4 added [reranker]; M5 adds [structural]; M7 adds [git]. Everything has a working default so the service runs with no config file at all.

Path defaults are anchored, never cwd-relative: the HTTP server (run from a checkout) and the stdio MCP server (spawned with the agent host's cwd) must resolve the SAME state DB, or the MCP tools silently answer "unknown project_id" for every project registered via the dashboard. Same failure class — and same cure — as prefetch.default_fastembed_cache.

DEFAULT_QUERY_URL = 'http://127.0.0.1:6333' module-attribute

CONFIG_ENV = 'NOESIS_CONFIG' module-attribute

EmbedderSettings(model='nomic-ai/CodeRankEmbed', dim=768, batch_size=32, device=None) dataclass

model = 'nomic-ai/CodeRankEmbed' class-attribute instance-attribute

dim = 768 class-attribute instance-attribute

batch_size = 32 class-attribute instance-attribute

device = None class-attribute instance-attribute

RerankerSettings(model='BAAI/bge-reranker-v2-m3', enabled=False, preload=False, candidates=50, batch_size=16, device=None) dataclass

§3.7 [reranker]. enabled is both the kill switch and the per-request default: enabled=false (the pre-gate default, Finding 2) never loads the model and requests cannot opt in; enabled=true makes rerank default on with per-request opt-out. The M4 gate decision flips the shipped default from measured NDCG@10 data.

model = 'BAAI/bge-reranker-v2-m3' class-attribute instance-attribute

enabled = False class-attribute instance-attribute

preload = False class-attribute instance-attribute

candidates = 50 class-attribute instance-attribute

batch_size = 16 class-attribute instance-attribute

device = None class-attribute instance-attribute

StructuralSettings(max_results=100, timeout_s=10.0) dataclass

§3.7 [structural]. max_results caps matches per query (the request may ask for less, never more); timeout_s is the wall-clock scan budget — on expiry the scan stops and returns partial results with timed_out: true rather than erroring, since partial matches are still actionable to an iterating agent.

max_results = 100 class-attribute instance-attribute

timeout_s = 10.0 class-attribute instance-attribute

GitSettings(fast_path=True) dataclass

§3.7 [git]. fast_path=false disables candidate narrowing entirely — every run full hash-walks (the correctness baseline the fast path must match, §3.2 rule 1).

fast_path = True class-attribute instance-attribute

IndexingSettings(promote_after_scoped_runs=20, promote_candidate_fraction=0.25, unwalkable_quarantine_runs=5, max_concurrent_index_runs=4) dataclass

§3.7 [indexing] — the automatic path back to a full, anchored walk (ADR-56/57). Every automated trigger in the service is scoped, and only a full run drains the H1 dirty set or advances the anchor, so without these a project has no way out of a latched state (issue #25).

promote_after_scoped_runs: promote a scoped run to a full walk once this many scoped runs have started since the last completed full one. promote_candidate_fraction: promote when the effective candidate set (pending ∪ dirty) reaches this fraction of the indexed file count — the point where a scoped run stops being cheaper than the full walk it already pays for, since discovery stats and binary-sniffs every file either way. unwalkable_quarantine_runs: consecutive runs a directory must fail to be walked before the paths it hides stop being re-queued for retry.

0 disables each independently, restoring the pre-ADR-56 behaviour.

max_concurrent_index_runs (ADR-85) caps index runs across the whole machine, not per project — try_start_run already guarantees one run per project, and this bounds how many projects may run at once. The default of 4 is a judgment call, NOT a measurement: concurrent runs serialize on the single embedder worker (ADR-20) regardless, so a larger number buys no indexing throughput and only multiplies simultaneous file walks, open descriptors and executor pressure; a value of 1 would be a visible behaviour change, since today a second project need not wait behind a long run. Set it explicitly if your machine says otherwise.

promote_after_scoped_runs = 20 class-attribute instance-attribute

promote_candidate_fraction = 0.25 class-attribute instance-attribute

unwalkable_quarantine_runs = 5 class-attribute instance-attribute

max_concurrent_index_runs = 4 class-attribute instance-attribute

WatcherSettings(poll_interval_s=1.0) dataclass

§3.7 [watcher]. poll_interval_s is the PollingObserver snapshot cadence used only for watched roots on inotify-blind filesystems (9p/cifs/nfs/fuse/…, e.g. WSL2's /mnt/c); roots watched natively via inotify never poll and ignore it.

poll_interval_s = 1.0 class-attribute instance-attribute

ServerSettings(port=8000) dataclass

§3.8 [server]. Only the port is configurable: the host is fixed at 127.0.0.1 by CLAUDE.md rule 2, and exposing it as a knob would make a wildcard bind one config edit away. The shim (ADR-86) reads this to know where to find — or start — the shared server, so the port has to live somewhere both it and the operator agree on.

port = 8000 class-attribute instance-attribute

QdrantSettings(url=DEFAULT_QUERY_URL, collection='noesis_chunks', query_connections=None, query_queue_depth=None) dataclass

§3.3 [qdrant].

query_connections sizes the search connection pool and, 1:1, the search executor's slots (ADR-83/84). None means derive from the machine — the same "None means auto" convention embedder.device already uses — because the right value is a property of the host, not of the project. See derive_query_connections for the rule and the measurements behind it. Set it explicitly to override on a machine whose shape the rule guesses wrong.

query_queue_depth bounds how many searches may WAIT for a slot before the service starts rejecting instead of queueing without limit. None derives it from query_connections.

url = DEFAULT_QUERY_URL class-attribute instance-attribute

collection = 'noesis_chunks' class-attribute instance-attribute

query_connections = None class-attribute instance-attribute

query_queue_depth = None class-attribute instance-attribute

Settings(db_path=default_db_path(), embedder=EmbedderSettings(), reranker=RerankerSettings(), structural=StructuralSettings(), git=GitSettings(), watcher=WatcherSettings(), indexing=IndexingSettings(), qdrant=QdrantSettings(), server=ServerSettings()) dataclass

db_path = field(default_factory=default_db_path) class-attribute instance-attribute

embedder = field(default_factory=EmbedderSettings) class-attribute instance-attribute

reranker = field(default_factory=RerankerSettings) class-attribute instance-attribute

structural = field(default_factory=StructuralSettings) class-attribute instance-attribute

git = field(default_factory=GitSettings) class-attribute instance-attribute

watcher = field(default_factory=WatcherSettings) class-attribute instance-attribute

indexing = field(default_factory=IndexingSettings) class-attribute instance-attribute

qdrant = field(default_factory=QdrantSettings) class-attribute instance-attribute

server = field(default_factory=ServerSettings) class-attribute instance-attribute

default_db_path()

Absolute, cwd-independent default location for the state DB (user data dir, ~/.local/share/noesis/noesis.sqlite).

Source code in src/noesis/core/config.py
28
29
30
31
32
def default_db_path() -> Path:
    """Absolute, cwd-independent default location for the state DB
    (user data dir, ``~/.local/share/noesis/noesis.sqlite``)."""
    base = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
    return Path(base).expanduser() / "noesis" / "noesis.sqlite"

default_config_path()

Config lookup when neither an explicit path nor $NOESIS_CONFIG is given: ./config.toml when present (deliberate dev override for running from a checkout), else the anchored user config dir.

Source code in src/noesis/core/config.py
35
36
37
38
39
40
41
42
43
def default_config_path() -> Path:
    """Config lookup when neither an explicit path nor $NOESIS_CONFIG is
    given: ``./config.toml`` when present (deliberate dev override for
    running from a checkout), else the anchored user config dir."""
    cwd_cfg = Path("config.toml")
    if cwd_cfg.is_file():
        return cwd_cfg
    base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
    return Path(base).expanduser() / "noesis" / "config.toml"

available_cpus()

CPUs this process may actually run on.

os.cpu_count() reports the host's CPUs, which is wrong inside a cgroup-limited container — it would size the pool for hardware the process cannot use. sched_getaffinity reports the real allowance where it exists (Linux); everything else falls back.

Source code in src/noesis/core/config.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def available_cpus() -> int:
    """CPUs this process may actually run on.

    ``os.cpu_count()`` reports the host's CPUs, which is wrong inside a
    cgroup-limited container — it would size the pool for hardware the
    process cannot use. ``sched_getaffinity`` reports the real allowance
    where it exists (Linux); everything else falls back."""
    getaffinity = getattr(os, "sched_getaffinity", None)
    if getaffinity is not None:
        try:
            return max(1, len(getaffinity(0)))
        except OSError:
            pass
    return max(1, os.cpu_count() or 1)

derive_query_connections(configured=None)

Resolve the search pool size; configured wins when given.

Rule: clamp(available_cpus(), 2, 8).

Measured on a 4-CPU box, 16 concurrent searches, 5,000 points, hybrid, prefetch 50, against a live Qdrant 1.18.3 — throughput saturates exactly at cpu_count and stays flat well past it while latency climbs monotonically:

K=1  258 q/s  p95  4.7ms     K=6   375 q/s  p95 23.7ms
K=2  353 q/s  p95  8.1ms     K=8   375 q/s  p95 33.3ms
K=4  384 q/s  p95 16.0ms     K=12  379 q/s  p95 48.4ms

The knee sits at the CPU count because Qdrant is co-resident and competing for the same cores: past it, queries queue inside Qdrant instead of in our pool, buying latency for no throughput.

The ceiling of 8 is explicitly NOT measured — a bigger box was not available — which is precisely why the override exists.

Source code in src/noesis/core/config.py
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
def derive_query_connections(configured: int | None = None) -> int:
    """Resolve the search pool size; *configured* wins when given.

    Rule: ``clamp(available_cpus(), 2, 8)``.

    Measured on a 4-CPU box, 16 concurrent searches, 5,000 points, hybrid,
    prefetch 50, against a live Qdrant 1.18.3 — throughput saturates
    exactly at ``cpu_count`` and stays flat well past it while latency
    climbs monotonically:

        K=1  258 q/s  p95  4.7ms     K=6   375 q/s  p95 23.7ms
        K=2  353 q/s  p95  8.1ms     K=8   375 q/s  p95 33.3ms
        K=4  384 q/s  p95 16.0ms     K=12  379 q/s  p95 48.4ms

    The knee sits at the CPU count because Qdrant is co-resident and
    competing for the same cores: past it, queries queue inside Qdrant
    instead of in our pool, buying latency for no throughput.

    The ceiling of 8 is explicitly NOT measured — a bigger box was not
    available — which is precisely why the override exists."""
    if configured is not None:
        return configured
    return max(
        _MIN_QUERY_CONNECTIONS, min(_MAX_QUERY_CONNECTIONS, available_cpus())
    )

derive_query_queue_depth(connections, configured=None)

Resolve how many searches may queue for a slot; configured wins.

Source code in src/noesis/core/config.py
230
231
232
233
234
def derive_query_queue_depth(connections: int, configured: int | None = None) -> int:
    """Resolve how many searches may queue for a slot; *configured* wins."""
    if configured is not None:
        return configured
    return connections * _QUEUE_DEPTH_PER_CONNECTION

load_settings(config_path=None)

Load settings, falling back to defaults per key.

Resolution order: explicit config_path → $NOESIS_CONFIG → ./config.toml (dev override) → $XDG_CONFIG_HOME/noesis/config.toml. A relative db_path inside the file resolves against the file's own directory, never the process cwd — the cwd belongs to whoever spawned us.

Source code in src/noesis/core/config.py
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
def load_settings(config_path: str | Path | None = None) -> Settings:
    """Load settings, falling back to defaults per key.

    Resolution order: explicit *config_path* → ``$NOESIS_CONFIG`` →
    ``./config.toml`` (dev override) → ``$XDG_CONFIG_HOME/noesis/config.toml``.
    A relative ``db_path`` inside the file resolves against the file's own
    directory, never the process cwd — the cwd belongs to whoever spawned us.
    """
    if config_path is None:
        config_path = os.environ.get(CONFIG_ENV) or default_config_path()
    # expanduser first: an MCP host commonly sets NOESIS_CONFIG (or passes an
    # explicit path) as a literal "~/..." that no shell expanded. Without this
    # the is_file() check misses the real config and silently falls back to
    # zero-config defaults — reopening the default DB and reintroducing the
    # exact silent divergence ADR-44 closes.
    path = Path(config_path).expanduser()
    if not path.is_file():
        return Settings()
    with open(path, "rb") as fh:
        raw = tomllib.load(fh)
    emb = raw.get("embedder", {})
    rrk = raw.get("reranker", {})
    stru = raw.get("structural", {})
    git = raw.get("git", {})
    wat = raw.get("watcher", {})
    idx = raw.get("indexing", {})
    qdr = raw.get("qdrant", {})
    srv = raw.get("server", {})
    raw_db = raw.get("db_path")
    if raw_db is None:
        db_path = default_db_path()
    else:
        db_path = Path(raw_db).expanduser()
        if not db_path.is_absolute():
            db_path = (path.resolve().parent / db_path).resolve()
    return Settings(
        db_path=db_path,
        embedder=EmbedderSettings(
            model=emb.get("model", EmbedderSettings.model),
            dim=_require_positive_int(
                emb.get("dim", EmbedderSettings.dim), "embedder.dim"
            ),
            batch_size=_require_positive_int(
                emb.get("batch_size", EmbedderSettings.batch_size),
                "embedder.batch_size",
            ),
            device=emb.get("device", EmbedderSettings.device),
        ),
        reranker=RerankerSettings(
            model=rrk.get("model", RerankerSettings.model),
            enabled=_require_bool(
                rrk.get("enabled", RerankerSettings.enabled), "reranker.enabled"
            ),
            preload=_require_bool(
                rrk.get("preload", RerankerSettings.preload), "reranker.preload"
            ),
            candidates=_require_positive_int(
                rrk.get("candidates", RerankerSettings.candidates),
                "reranker.candidates",
            ),
            batch_size=_require_positive_int(
                rrk.get("batch_size", RerankerSettings.batch_size),
                "reranker.batch_size",
            ),
            device=rrk.get("device", RerankerSettings.device),
        ),
        structural=StructuralSettings(
            max_results=_require_positive_int(
                stru.get("max_results", StructuralSettings.max_results),
                "structural.max_results",
            ),
            timeout_s=_require_positive_float(
                stru.get("timeout_s", StructuralSettings.timeout_s),
                "structural.timeout_s",
            ),
        ),
        git=GitSettings(
            fast_path=_require_bool(
                git.get("fast_path", GitSettings.fast_path), "git.fast_path"
            ),
        ),
        watcher=WatcherSettings(
            poll_interval_s=_require_positive_float(
                wat.get("poll_interval_s", WatcherSettings.poll_interval_s),
                "watcher.poll_interval_s",
            ),
        ),
        indexing=IndexingSettings(
            promote_after_scoped_runs=_require_non_negative_int(
                idx.get(
                    "promote_after_scoped_runs",
                    IndexingSettings.promote_after_scoped_runs,
                ),
                "indexing.promote_after_scoped_runs",
            ),
            promote_candidate_fraction=_require_fraction(
                idx.get(
                    "promote_candidate_fraction",
                    IndexingSettings.promote_candidate_fraction,
                ),
                "indexing.promote_candidate_fraction",
            ),
            unwalkable_quarantine_runs=_require_non_negative_int(
                idx.get(
                    "unwalkable_quarantine_runs",
                    IndexingSettings.unwalkable_quarantine_runs,
                ),
                "indexing.unwalkable_quarantine_runs",
            ),
            max_concurrent_index_runs=_require_positive_int(
                idx.get(
                    "max_concurrent_index_runs",
                    IndexingSettings.max_concurrent_index_runs,
                ),
                "indexing.max_concurrent_index_runs",
            ),
        ),
        qdrant=QdrantSettings(
            url=qdr.get("url", QdrantSettings.url),
            collection=qdr.get("collection", QdrantSettings.collection),
            query_connections=_optional_positive_int(
                qdr.get("query_connections"), "qdrant.query_connections"
            ),
            query_queue_depth=_optional_positive_int(
                qdr.get("query_queue_depth"), "qdrant.query_queue_depth"
            ),
        ),
        server=ServerSettings(
            port=_require_positive_int(
                srv.get("port", ServerSettings.port), "server.port"
            ),
        ),
    )

noesis.core.state

SQLite state store — projects, per-file state, index runs.

WAL-mode single-file DB per the approved Overview §7 schema plus the last_indexed_commit column from the expanded doc §3.7. All mutating functions commit before returning; callers never manage transactions.

MixedModelError

Bases: ValueError

A project is already indexed with a different embedding model. Typed so adapters can map it to 409 without matching message text (PR #10 review).

IndexCapacityReached(running, limit, project_id=None)

Bases: Exception

Raised by try_start_run when the machine-wide cap is already met.

A distinct exception rather than a third return status, deliberately: the watcher's re-arm path matches the already_running status by string, so a new status value would have fallen through it silently — counting a run that never started and leaving pending files stuck. An unhandled exception is loud; a silently mishandled status is the bug this whole change is about.

Source code in src/noesis/core/state.py
637
638
639
640
641
642
643
644
645
646
647
648
def __init__(self, running: int, limit: int, project_id: str | None = None) -> None:
    self.running = running
    self.limit = limit
    # Carried so a caller that already committed a side effect (notably
    # POST /projects, which registers before it launches) can report that
    # side effect rather than only the refusal.
    self.project_id = project_id
    self.retry_after_seconds = 30
    super().__init__(
        f"index capacity reached: {running} runs already in flight, "
        f"limit {limit}"
    )

running = running instance-attribute

limit = limit instance-attribute

project_id = project_id instance-attribute

retry_after_seconds = 30 instance-attribute

agent_message()

Source code in src/noesis/core/state.py
650
651
652
653
654
655
656
657
def agent_message(self) -> str:
    return (
        f"Noesis is at indexing capacity — {self.running} index runs are "
        f"already in flight against a limit of {self.limit}. Nothing "
        f"failed and nothing was started; this project was not queued. "
        f"Retry once a run finishes, or raise "
        f"[indexing] max_concurrent_index_runs in config.toml."
    )

connect(db_path)

Source code in src/noesis/core/state.py
271
272
273
274
275
276
277
278
279
280
def connect(db_path: str | Path) -> sqlite3.Connection:
    db_path = Path(db_path)
    db_path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(db_path, check_same_thread=False)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=NORMAL")
    conn.execute("PRAGMA busy_timeout=5000")
    conn.execute("PRAGMA foreign_keys=ON")
    return conn

init_db(conn)

Source code in src/noesis/core/state.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def init_db(conn: sqlite3.Connection) -> None:
    conn.executescript(_SCHEMA)
    # Migrations run single-writer: the dual-transport deployment (HTTP +
    # stdio MCP on one DB) can call init_db concurrently, and an unguarded
    # check-then-ALTER races — the loser's ALTER raises 'duplicate column
    # name', a schema error busy_timeout cannot retry, aborting that
    # process's startup. BEGIN IMMEDIATE serializes the loop (the second
    # writer's table_info re-read then sees the committed column and
    # skips); the except is a backstop for a pre-lock writer running older
    # code, where skipping is correct — the column exists.
    conn.execute("BEGIN IMMEDIATE")
    try:
        for table, column, ddl_type in _MIGRATIONS:
            cols = {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}
            if column not in cols:
                try:
                    conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {ddl_type}")
                except sqlite3.OperationalError as exc:
                    if "duplicate column name" not in str(exc):
                        raise
    except BaseException:
        conn.rollback()
        raise
    conn.commit()

register_project(conn, root_path, embedding_model)

Source code in src/noesis/core/state.py
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
def register_project(
    conn: sqlite3.Connection, root_path: str | Path, embedding_model: str
) -> str:
    resolved = str(Path(root_path).resolve())
    row = conn.execute(
        "SELECT id, embedding_model FROM projects WHERE root_path = ?", (resolved,)
    ).fetchone()
    if row is not None:
        if row["embedding_model"] != embedding_model:
            raise MixedModelError(
                f"project at {resolved} is indexed with model "
                f"{row['embedding_model']!r}; refusing to serve mixed-model state. "
                f"Re-register requires a full re-index with {embedding_model!r}."
            )
        return row["id"]
    project_id = uuid.uuid4().hex
    now = _now()
    try:
        conn.execute(
            "INSERT INTO projects (id, root_path, embedding_model, created_at, updated_at)"
            " VALUES (?, ?, ?, ?, ?)",
            (project_id, resolved, embedding_model, now, now),
        )
        conn.commit()
        return project_id
    except sqlite3.IntegrityError:
        # Concurrent registration of the same root_path lost the UNIQUE race
        # (L4). Return the winner's id idempotently instead of surfacing a raw
        # IntegrityError, re-checking the model just as the fast path does.
        conn.rollback()
        row = conn.execute(
            "SELECT id, embedding_model FROM projects WHERE root_path = ?", (resolved,)
        ).fetchone()
        if row is None:
            raise
        if row["embedding_model"] != embedding_model:
            raise MixedModelError(
                f"project at {resolved} is indexed with model "
                f"{row['embedding_model']!r}; refusing to serve mixed-model state. "
                f"Re-register requires a full re-index with {embedding_model!r}."
            ) from None
        return row["id"]

get_project(conn, project_id)

Source code in src/noesis/core/state.py
353
354
def get_project(conn: sqlite3.Connection, project_id: str) -> sqlite3.Row | None:
    return conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()

list_projects(conn)

Source code in src/noesis/core/state.py
357
358
def list_projects(conn: sqlite3.Connection) -> list[sqlite3.Row]:
    return conn.execute("SELECT * FROM projects ORDER BY created_at").fetchall()

set_last_indexed_commit(conn, project_id, commit, *, dirty_paths=None)

Record the git fast-path anchor. Callers must invoke this only after a run completes successfully (§3.2 rule 4) — an anchor from a failed run would let the next fast path skip files the failed run never finished indexing.

dirty_paths (when provided) records the set the next run must re-admit as candidates (H1). Two populations since ADR-60, and the second is why this parameter is load-bearing rather than bookkeeping: the working-tree -dirty paths as of this anchor, PLUS every path the run could not verify. A run is allowed to anchor past a nameable failure precisely because those paths ride along here — the guarantee "the next fast path never skips a file whose state is unknown" is met by recording them, not by refusing to move (issue #28). The anchor and the set are written in ONE statement, so there is no window where the anchor advanced but the re-admission list did not.

Passing an empty iterable clears the stored set; None leaves it untouched.

Source code in src/noesis/core/state.py
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
def set_last_indexed_commit(
    conn: sqlite3.Connection,
    project_id: str,
    commit: str,
    *,
    dirty_paths: Iterable[str] | None = None,
) -> None:
    """Record the git fast-path anchor. Callers must invoke this only after
    a run completes successfully (§3.2 rule 4) — an anchor from a failed
    run would let the next fast path skip files the failed run never
    finished indexing.

    *dirty_paths* (when provided) records the set the next run must re-admit
    as candidates (H1). Two populations since ADR-60, and the second is why
    this parameter is load-bearing rather than bookkeeping: the working-tree
    -dirty paths as of this anchor, PLUS every path the run could not verify.
    A run is allowed to anchor past a *nameable* failure precisely because
    those paths ride along here — the guarantee "the next fast path never
    skips a file whose state is unknown" is met by recording them, not by
    refusing to move (issue #28). The anchor and the set are written in ONE
    statement, so there is no window where the anchor advanced but the
    re-admission list did not.

    Passing an empty iterable clears the stored set; None leaves it
    untouched."""
    if dirty_paths is None:
        conn.execute(
            "UPDATE projects SET last_indexed_commit = ?, updated_at = ? WHERE id = ?",
            (commit, _now(), project_id),
        )
    else:
        conn.execute(
            "UPDATE projects SET last_indexed_commit = ?, dirty_paths = ?,"
            " updated_at = ? WHERE id = ?",
            (commit, json.dumps(sorted(dirty_paths)), _now(), project_id),
        )
    conn.commit()

add_dirty_paths(conn, project_id, paths)

Union paths into the persisted dirty set (H1) WITHOUT touching last_indexed_commit. Scoped (watcher) runs never advance the anchor, so :func:set_last_indexed_commit never fires for them — yet the dirty content they indexed must still be re-admitted by the next fast path. Union-only: it can only widen the candidate set (§3.2 rule-1 safe).

The read and the write run in one BEGIN IMMEDIATE transaction. In practice try_start_run already serializes runs per project, even across processes, and this is only called from inside a run — but that invariant lives in another function, and a lost union here silently reopens the H1 gap this exists to close. Self-protecting beats depending on a caller's lock.

Runs on the caller's thread — execute_run calls it directly from the event loop — and BEGIN IMMEDIATE takes SQLite's write lock at the first statement rather than at commit. Under a foreign writer (the other transport mid-run) it can therefore block the loop for up to the shared connection's busy_timeout of 5s, once per scoped run. Accepted deliberately: the alternative is a dedicated short-timeout connection like telemetry's, which DROPS its write when the lock is contended — and unlike a telemetry row, a dropped union is a correctness loss that silently reopens the H1 gap. A bounded stall beats silent data loss. It must not be moved to a worker thread either: the shared connection is loop-owned, and a worker-thread write interleaving inside another operation's open transaction is the hazard jobs.index_status documents.

Source code in src/noesis/core/state.py
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
def add_dirty_paths(
    conn: sqlite3.Connection, project_id: str, paths: Iterable[str]
) -> None:
    """Union *paths* into the persisted dirty set (H1) WITHOUT touching
    ``last_indexed_commit``. Scoped (watcher) runs never advance the anchor,
    so :func:`set_last_indexed_commit` never fires for them — yet the dirty
    content they indexed must still be re-admitted by the next fast path.
    Union-only: it can only widen the candidate set (§3.2 rule-1 safe).

    The read and the write run in one ``BEGIN IMMEDIATE`` transaction. In
    practice ``try_start_run`` already serializes runs per project, even
    across processes, and this is only called from inside a run — but that
    invariant lives in another function, and a lost union here silently
    reopens the H1 gap this exists to close. Self-protecting beats
    depending on a caller's lock.

    Runs on the caller's thread — ``execute_run`` calls it directly from the
    event loop — and ``BEGIN IMMEDIATE`` takes SQLite's write lock at the
    first statement rather than at commit. Under a foreign writer (the other
    transport mid-run) it can therefore block the loop for up to the shared
    connection's ``busy_timeout`` of 5s, once per scoped run. Accepted
    deliberately: the alternative is a dedicated short-timeout connection
    like telemetry's, which DROPS its write when the lock is contended — and
    unlike a telemetry row, a dropped union is a correctness loss that
    silently reopens the H1 gap. A bounded stall beats silent data loss. It
    must not be moved to a worker thread either: the shared connection is
    loop-owned, and a worker-thread write interleaving inside another
    operation's open transaction is the hazard ``jobs.index_status``
    documents.
    """
    new = set(paths)
    if not new:
        return
    conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute(
            "SELECT dirty_paths FROM projects WHERE id = ?", (project_id,)
        ).fetchone()
        if row is None:
            conn.rollback()
            return
        current: set[str] = (
            set(json.loads(row["dirty_paths"])) if row["dirty_paths"] else set()
        )
        conn.execute(
            "UPDATE projects SET dirty_paths = ?, updated_at = ? WHERE id = ?",
            (json.dumps(sorted(current | new)), _now(), project_id),
        )
    except BaseException:
        conn.rollback()
        raise
    conn.commit()

set_dirty_paths(conn, project_id, paths)

REPLACE the persisted H1 dirty set without touching the anchor.

:func:set_last_indexed_commit is the only other writer that shrinks it, and it requires a commit — so a project with no git anchor (non-git root, or git unavailable) had no way to shrink the set at all and grew it without bound. Callers must have completed a FULL walk: that re-hashes every discovered file, so the only paths still owed H1 re-admission are the ones the walk could not verify.

paths is exactly that remainder (ADR-60). It was an unconditional clear until the caller was allowed to finish a walk that had contained failures: a full walk with, say, one unreadable subdirectory has re-hashed everything else, so clearing outright would drop the one set that must survive, while refusing to write at all is what froze the set in the first place (issue #28). Pass an empty iterable for the clean case — that is still the common one, and it behaves exactly as the old clear did.

A blind write, unlike :func:add_dirty_paths's read-modify-write, so it needs no explicit transaction: the caller is replacing the set with a value it derived from a walk of the whole tree, not merging into what is there.

Source code in src/noesis/core/state.py
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
def set_dirty_paths(
    conn: sqlite3.Connection, project_id: str, paths: Iterable[str]
) -> None:
    """REPLACE the persisted H1 dirty set without touching the anchor.

    :func:`set_last_indexed_commit` is the only other writer that shrinks it,
    and it requires a commit — so a project with no git anchor (non-git root,
    or git unavailable) had no way to shrink the set at all and grew it
    without bound. Callers must have completed a FULL walk: that re-hashes
    every discovered file, so the only paths still owed H1 re-admission are
    the ones the walk could not verify.

    *paths* is exactly that remainder (ADR-60). It was an unconditional clear
    until the caller was allowed to finish a walk that had contained failures:
    a full walk with, say, one unreadable subdirectory has re-hashed
    everything else, so clearing outright would drop the one set that must
    survive, while refusing to write at all is what froze the set in the first
    place (issue #28). Pass an empty iterable for the clean case — that is
    still the common one, and it behaves exactly as the old clear did.

    A blind write, unlike :func:`add_dirty_paths`'s read-modify-write, so it
    needs no explicit transaction: the caller is replacing the set with a value
    it derived from a walk of the whole tree, not merging into what is there."""
    conn.execute(
        "UPDATE projects SET dirty_paths = ?, updated_at = ? WHERE id = ?",
        (json.dumps(sorted(paths)), _now(), project_id),
    )
    conn.commit()

get_dirty_paths(conn, project_id)

The dirty-path set persisted at the last anchor advance (H1). Empty when unset or the project is unknown.

Source code in src/noesis/core/state.py
484
485
486
487
488
489
490
491
492
def get_dirty_paths(conn: sqlite3.Connection, project_id: str) -> frozenset[str]:
    """The dirty-path set persisted at the last anchor advance (H1). Empty
    when unset or the project is unknown."""
    row = conn.execute(
        "SELECT dirty_paths FROM projects WHERE id = ?", (project_id,)
    ).fetchone()
    if row is None or row["dirty_paths"] is None:
        return frozenset()
    return frozenset(json.loads(row["dirty_paths"]))

get_file_states(conn, project_id)

Source code in src/noesis/core/state.py
495
496
497
498
499
def get_file_states(conn: sqlite3.Connection, project_id: str) -> dict[str, str]:
    rows = conn.execute(
        "SELECT path, content_hash FROM files WHERE project_id = ?", (project_id,)
    ).fetchall()
    return {row["path"]: row["content_hash"] for row in rows}

get_file_chunk_counts(conn, project_id)

Stored per-file chunk_count for a project — the number of points the vector store should hold for each file. Drift self-heal compares this, file by file, against the live per-file point counts in Qdrant.

Source code in src/noesis/core/state.py
502
503
504
505
506
507
508
509
def get_file_chunk_counts(conn: sqlite3.Connection, project_id: str) -> dict[str, int]:
    """Stored per-file chunk_count for a project — the number of points the
    vector store should hold for each file. Drift self-heal compares this,
    file by file, against the live per-file point counts in Qdrant."""
    rows = conn.execute(
        "SELECT path, chunk_count FROM files WHERE project_id = ?", (project_id,)
    ).fetchall()
    return {row["path"]: int(row["chunk_count"]) for row in rows}

expected_chunk_total(conn, project_id)

Sum of stored per-file chunk_count for a project — the number of points the vector store should hold in total. COALESCE so a never-indexed project reads 0, never NULL.

Source code in src/noesis/core/state.py
512
513
514
515
516
517
518
519
520
def expected_chunk_total(conn: sqlite3.Connection, project_id: str) -> int:
    """Sum of stored per-file chunk_count for a project — the number of
    points the vector store should hold in total. COALESCE so a
    never-indexed project reads 0, never NULL."""
    row = conn.execute(
        "SELECT COALESCE(SUM(chunk_count), 0) AS n FROM files WHERE project_id = ?",
        (project_id,),
    ).fetchone()
    return int(row["n"])

indexed_file_total(conn)

Total tracked files across all projects — the wipe-signature check (a vector collection created while state already tracks indexed files).

Source code in src/noesis/core/state.py
523
524
525
526
527
def indexed_file_total(conn: sqlite3.Connection) -> int:
    """Total tracked files across all projects — the wipe-signature check
    (a vector collection created while state already tracks indexed files)."""
    row = conn.execute("SELECT COUNT(*) AS n FROM files").fetchone()
    return int(row["n"])

indexed_file_count(conn, project_id)

Files tracked for one project — the denominator the promotion trigger measures a scoped run's effective candidate set against (ADR-57).

Source code in src/noesis/core/state.py
530
531
532
533
534
535
536
def indexed_file_count(conn: sqlite3.Connection, project_id: str) -> int:
    """Files tracked for one project — the denominator the promotion trigger
    measures a scoped run's effective candidate set against (ADR-57)."""
    row = conn.execute(
        "SELECT COUNT(*) AS n FROM files WHERE project_id = ?", (project_id,)
    ).fetchone()
    return int(row["n"])

upsert_file(conn, project_id, path, content_hash, language=None, chunk_count=0)

Source code in src/noesis/core/state.py
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
def upsert_file(
    conn: sqlite3.Connection,
    project_id: str,
    path: str,
    content_hash: str,
    language: str | None = None,
    chunk_count: int = 0,
) -> None:
    conn.execute(
        """
        INSERT INTO files (id, project_id, path, language, content_hash,
                           chunk_count, last_indexed_at)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(project_id, path) DO UPDATE SET
          language = excluded.language,
          content_hash = excluded.content_hash,
          chunk_count = excluded.chunk_count,
          last_indexed_at = excluded.last_indexed_at
        """,
        (
            uuid.uuid4().hex,
            project_id,
            path,
            language,
            content_hash,
            chunk_count,
            _now(),
        ),
    )
    conn.commit()

delete_files(conn, project_id, paths)

Source code in src/noesis/core/state.py
571
572
573
574
575
576
577
578
def delete_files(
    conn: sqlite3.Connection, project_id: str, paths: Iterable[str]
) -> None:
    conn.executemany(
        "DELETE FROM files WHERE project_id = ? AND path = ?",
        [(project_id, p) for p in paths],
    )
    conn.commit()

fail_orphaned_runs(conn)

Mark 'running' runs whose OWNING PROCESS IS DEAD as failed. Called at process startup to clear crash leftovers — the launch guard would otherwise return a dead run id forever, silently no-opping every future launch (PR #10 review).

Owner-gated (M7): in the documented two-process deployment (HTTP + stdio MCP sharing the DB, m6 guide) a starting process must NOT fail the other process's LIVE run — that both loses the run and disarms the concurrent-run guard. Rows with no owner (pre-M7 DBs) predate ownership tracking and are treated as dead.

Source code in src/noesis/core/state.py
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 fail_orphaned_runs(conn: sqlite3.Connection) -> int:
    """Mark 'running' runs whose OWNING PROCESS IS DEAD as failed. Called at
    process startup to clear crash leftovers — the launch guard would
    otherwise return a dead run id forever, silently no-opping every future
    launch (PR #10 review).

    Owner-gated (M7): in the documented two-process deployment (HTTP + stdio
    MCP sharing the DB, m6 guide) a starting process must NOT fail the other
    process's LIVE run — that both loses the run and disarms the
    concurrent-run guard. Rows with no owner (pre-M7 DBs) predate ownership
    tracking and are treated as dead."""
    rows = conn.execute(
        "SELECT id, owner FROM index_runs WHERE status = 'running'"
    ).fetchall()
    dead = [
        row["id"] for row in rows if not row["owner"] or not _owner_alive(row["owner"])
    ]
    if not dead:
        return 0
    now = _now()
    conn.executemany(
        "UPDATE index_runs SET status = 'failed', error = 'interrupted',"
        " finished_at = ? WHERE id = ?",
        [(now, run_id) for run_id in dead],
    )
    conn.commit()
    return len(dead)

start_run(conn, project_id, *, triggered_by='manual', scoped=False)

Source code in src/noesis/core/state.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def start_run(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    triggered_by: str = "manual",
    scoped: bool = False,
) -> str:
    run_id = uuid.uuid4().hex
    conn.execute(
        "INSERT INTO index_runs (id, project_id, status, started_at, triggered_by,"
        " owner, scoped) VALUES (?, ?, 'running', ?, ?, ?, ?)",
        (run_id, project_id, _now(), triggered_by, _OWNER, int(scoped)),
    )
    conn.commit()
    return run_id

try_start_run(conn, project_id, *, triggered_by='manual', scoped=False, max_concurrent=None)

Atomically open a run — or return the one already running.

BEGIN IMMEDIATE takes SQLite's write lock up front, so the running-check and the insert are a single unit even across processes: the documented dual-transport deployment (HTTP server + stdio MCP on one DB) cannot both pass a read-then-insert guard and race two runs onto the same collection. Stale running rows whose owning process is dead are failed here (same owner probe as fail_orphaned_runs), so a crashed co-process can never jam the guard until a restart.

Returns (run_id, created) — created False means a live run already exists and run_id is that run's id.

max_concurrent (ADR-85) caps how many runs may be alive across the WHOLE machine, not per project. It is enforced here rather than in jobs.launch_index_run because only this transaction is atomic across processes: an asyncio.Semaphore would bound one process while the co-process proceeds unaware, which for the documented HTTP + stdio deployment is no cap at all. None means uncapped, which keeps every direct caller (indexer.prepare_run, tests) behaving exactly as before — only launch_index_run passes a limit, because it is the fan-out path where N projects can pile up.

The running-row scan is global for the same reason, so the dead-owner cleanup now covers other projects' orphans too. That is the same operation fail_orphaned_runs already performs at startup, and it has to happen here or a crashed co-process's stale row would count against the cap until the next restart.

scoped records whether this run was given an explicit candidate set, written at INSERT rather than at finish_run so a run that crashes still counts toward the promotion trigger (ADR-57) — otherwise a project that keeps dying mid-run would never promote.

Source code in src/noesis/core/state.py
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
def try_start_run(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    triggered_by: str = "manual",
    scoped: bool = False,
    max_concurrent: int | None = None,
) -> tuple[str, bool]:
    """Atomically open a run — or return the one already running.

    ``BEGIN IMMEDIATE`` takes SQLite's write lock up front, so the
    running-check and the insert are a single unit even across processes:
    the documented dual-transport deployment (HTTP server + stdio MCP on
    one DB) cannot both pass a read-then-insert guard and race two runs
    onto the same collection. Stale ``running`` rows whose owning process
    is dead are failed here (same owner probe as ``fail_orphaned_runs``),
    so a crashed co-process can never jam the guard until a restart.

    Returns ``(run_id, created)`` — ``created`` False means a live run
    already exists and ``run_id`` is that run's id.

    *max_concurrent* (ADR-85) caps how many runs may be alive across the
    WHOLE machine, not per project. It is enforced here rather than in
    ``jobs.launch_index_run`` because only this transaction is atomic across
    processes: an ``asyncio.Semaphore`` would bound one process while the
    co-process proceeds unaware, which for the documented HTTP + stdio
    deployment is no cap at all. ``None`` means uncapped, which keeps every
    direct caller (``indexer.prepare_run``, tests) behaving exactly as
    before — only ``launch_index_run`` passes a limit, because it is the
    fan-out path where N projects can pile up.

    The running-row scan is global for the same reason, so the dead-owner
    cleanup now covers other projects' orphans too. That is the same
    operation ``fail_orphaned_runs`` already performs at startup, and it has
    to happen here or a crashed co-process's stale row would count against
    the cap until the next restart.

    *scoped* records whether this run was given an explicit candidate set,
    written at INSERT rather than at ``finish_run`` so a run that crashes still
    counts toward the promotion trigger (ADR-57) — otherwise a project that
    keeps dying mid-run would never promote.
    """
    conn.execute("BEGIN IMMEDIATE")
    at_capacity: IndexCapacityReached | None = None
    try:
        rows = conn.execute(
            "SELECT id, project_id, owner FROM index_runs"
            " WHERE status = 'running' ORDER BY started_at DESC, rowid DESC",
        ).fetchall()
        alive: list[sqlite3.Row] = []
        dead: list[sqlite3.Row] = []
        for row in rows:
            (alive if (row["owner"] and _owner_alive(row["owner"])) else dead).append(
                row
            )
        if dead:  # dead owners: fail them now, exactly like fail_orphaned_runs —
            # even when an alive run also exists, or a crashed co-process's row
            # would sit "running" until the next restart's fail_orphaned_runs
            now = _now()
            conn.executemany(
                "UPDATE index_runs SET status = 'failed', error = 'interrupted',"
                " finished_at = ? WHERE id = ?",
                [(now, r["id"]) for r in dead],
            )
        mine = [r for r in alive if r["project_id"] == project_id]
        if mine or (max_concurrent is not None and len(alive) >= max_concurrent):
            if dead:
                conn.commit()  # persist the dead-row cleanup; releases the lock
            else:
                conn.rollback()  # nothing written; release the lock
            if mine:
                # This project's own run wins over the cap: the caller asked
                # about work that is already happening, which is a truthful
                # "already running", not a refusal.
                return mine[0]["id"], False
            at_capacity = IndexCapacityReached(
                running=len(alive), limit=max_concurrent, project_id=project_id
            )
        else:
            run_id = uuid.uuid4().hex
            conn.execute(
                "INSERT INTO index_runs (id, project_id, status, started_at,"
                " triggered_by, owner, scoped) VALUES (?, ?, 'running', ?, ?, ?, ?)",
                (run_id, project_id, _now(), triggered_by, _OWNER, int(scoped)),
            )
            conn.commit()
            return run_id, True
    except BaseException:
        conn.rollback()
        raise
    # Raised outside the try so the handler above cannot roll back a
    # transaction this branch has already settled.
    raise at_capacity

get_latest_run(conn, project_id)

Most recent index run for a project — the M6 get_index_status surface. Ordered by started_at (ISO-8601 UTC, lexicographically sortable); ties broken by rowid (insertion order).

Source code in src/noesis/core/state.py
755
756
757
758
759
760
761
762
763
def get_latest_run(conn: sqlite3.Connection, project_id: str) -> sqlite3.Row | None:
    """Most recent index run for a project — the M6 ``get_index_status``
    surface. Ordered by started_at (ISO-8601 UTC, lexicographically
    sortable); ties broken by rowid (insertion order)."""
    return conn.execute(
        "SELECT * FROM index_runs WHERE project_id = ?"
        " ORDER BY started_at DESC, rowid DESC LIMIT 1",
        (project_id,),
    ).fetchone()

finish_run(conn, run_id, status, *, files_total=None, files_changed=None, chunks_written=None, fast_path_used=None, candidate_count=None, files_failed=None, clean=None, error=None)

Close out a run row: status, counters, finish time, error.

The counters are written with COALESCE(?, col) so passing None leaves the stored value alone instead of erasing it. That matters because this can legitimately be called twice for one run: execute_run writes "done" with a full set of counters, and only afterwards does its remaining bookkeeping — add_dirty_paths (which takes SQLite's write lock under BEGIN IMMEDIATE and raises OperationalError past the 5s busy_timeout), the anchor write, and a git status subprocess. Any of those raising lands in the except BaseException handler, which calls this again with a status and an error and nothing else. Under the old unconditional SET, that second call blanked every counter the first had committed — a run whose content was fully indexed showed up on the dashboard as failed with no numbers at all (PR #24 round-8 review).

status, error and finished_at stay unconditional: the whole point of the second call is to overwrite those three, and error must be able to move back to NULL as well as to a message.

clean is the caller's own clean_run verdict and is COALESCE'd with the counters rather than written unconditionally, for the same reason: the second call does not recompute it. That is safe because every reader pairs it with status, so a run that reaches the failure path is excluded by the status test regardless of the verdict recorded before it (ADR-58).

Source code in src/noesis/core/state.py
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
def finish_run(
    conn: sqlite3.Connection,
    run_id: str,
    status: str,
    *,
    files_total: int | None = None,
    files_changed: int | None = None,
    chunks_written: int | None = None,
    fast_path_used: bool | None = None,
    candidate_count: int | None = None,
    files_failed: int | None = None,
    clean: bool | None = None,
    error: str | None = None,
) -> None:
    """Close out a run row: status, counters, finish time, error.

    The counters are written with ``COALESCE(?, col)`` so passing ``None``
    leaves the stored value alone instead of erasing it. That matters because
    this can legitimately be called **twice** for one run: ``execute_run``
    writes ``"done"`` with a full set of counters, and only afterwards does its
    remaining bookkeeping — ``add_dirty_paths`` (which takes SQLite's write
    lock under ``BEGIN IMMEDIATE`` and raises ``OperationalError`` past the
    5s ``busy_timeout``), the anchor write, and a ``git status`` subprocess.
    Any of those raising lands in the ``except BaseException`` handler, which
    calls this again with a status and an error and nothing else. Under the
    old unconditional ``SET``, that second call blanked every counter the
    first had committed — a run whose content was fully indexed showed up on
    the dashboard as failed with no numbers at all (PR #24 round-8 review).

    ``status``, ``error`` and ``finished_at`` stay unconditional: the whole
    point of the second call is to overwrite those three, and ``error`` must
    be able to move back to NULL as well as to a message.

    ``clean`` is the caller's own ``clean_run`` verdict and is COALESCE'd with
    the counters rather than written unconditionally, for the same reason: the
    second call does not recompute it. That is safe because every reader pairs
    it with ``status``, so a run that reaches the failure path is excluded by
    the status test regardless of the verdict recorded before it (ADR-58).
    """
    conn.execute(
        """
        UPDATE index_runs SET
          status = ?,
          files_total     = COALESCE(?, files_total),
          files_changed   = COALESCE(?, files_changed),
          chunks_written  = COALESCE(?, chunks_written),
          fast_path_used  = COALESCE(?, fast_path_used),
          candidate_count = COALESCE(?, candidate_count),
          files_failed    = COALESCE(?, files_failed),
          clean           = COALESCE(?, clean),
          finished_at = ?, error = ?
        WHERE id = ?
        """,
        (
            status,
            files_total,
            files_changed,
            chunks_written,
            None if fast_path_used is None else int(fast_path_used),
            candidate_count,
            files_failed,
            None if clean is None else int(clean),
            _now(),
            error,
            run_id,
        ),
    )
    conn.commit()

set_project_flags(conn, project_id, *, watch_enabled=None, auto_reindex=None)

Update the per-project watcher flags (ADR-40). None leaves a flag untouched.

Source code in src/noesis/core/state.py
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
def set_project_flags(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    watch_enabled: bool | None = None,
    auto_reindex: bool | None = None,
) -> None:
    """Update the per-project watcher flags (ADR-40). None leaves a flag
    untouched."""
    sets, params = [], []
    if watch_enabled is not None:
        sets.append("watch_enabled = ?")
        params.append(int(watch_enabled))
    if auto_reindex is not None:
        sets.append("auto_reindex = ?")
        params.append(int(auto_reindex))
    if not sets:
        return
    sets.append("updated_at = ?")
    params.extend([_now(), project_id])
    conn.execute(f"UPDATE projects SET {', '.join(sets)} WHERE id = ?", params)
    conn.commit()

set_index_config(conn, project_id, *, index_languages=None, max_file_bytes=None, follow_symlinks=False, extra_ignores=None)

Persist a project's index scope (ADR-42). index_languages / extra_ignores are JSON-encoded; an empty or None list stores NULL (meaning 'no filter' / 'all languages'). max_file_bytes None stores NULL (DiscoveryConfig default applies).

Source code in src/noesis/core/state.py
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
def set_index_config(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    index_languages: list[str] | None = None,
    max_file_bytes: int | None = None,
    follow_symlinks: bool = False,
    extra_ignores: list[str] | None = None,
) -> None:
    """Persist a project's index scope (ADR-42). ``index_languages`` /
    ``extra_ignores`` are JSON-encoded; an empty or None list stores NULL
    (meaning 'no filter' / 'all languages'). ``max_file_bytes`` None stores
    NULL (DiscoveryConfig default applies)."""
    langs_json = json.dumps(index_languages) if index_languages else None
    ignores_json = json.dumps(extra_ignores) if extra_ignores else None
    conn.execute(
        "UPDATE projects SET index_languages = ?, max_file_bytes = ?,"
        " follow_symlinks = ?, extra_ignores = ?, updated_at = ? WHERE id = ?",
        (
            langs_json,
            max_file_bytes,
            int(follow_symlinks),
            ignores_json,
            _now(),
            project_id,
        ),
    )
    conn.commit()

delete_project(conn, project_id)

Remove a project and all its state rows, child-first so the FK constraints hold (ADR-43). query_log rows are deliberately kept: metadata-only aggregates with no FK — deleting them would silently rewrite usage history.

Source code in src/noesis/core/state.py
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def delete_project(conn: sqlite3.Connection, project_id: str) -> None:
    """Remove a project and all its state rows, child-first so the FK
    constraints hold (ADR-43). ``query_log`` rows are deliberately kept:
    metadata-only aggregates with no FK — deleting them would silently
    rewrite usage history."""
    conn.execute(
        "DELETE FROM run_file_errors WHERE run_id IN"
        " (SELECT id FROM index_runs WHERE project_id = ?)",
        (project_id,),
    )
    conn.execute("DELETE FROM index_runs WHERE project_id = ?", (project_id,))
    conn.execute("DELETE FROM pending_changes WHERE project_id = ?", (project_id,))
    conn.execute("DELETE FROM watcher_stats WHERE project_id = ?", (project_id,))
    conn.execute("DELETE FROM unwalkable_dirs WHERE project_id = ?", (project_id,))
    conn.execute("DELETE FROM files WHERE project_id = ?", (project_id,))
    conn.execute("DELETE FROM projects WHERE id = ?", (project_id,))
    conn.commit()

watched_projects(conn)

Source code in src/noesis/core/state.py
909
910
911
912
def watched_projects(conn: sqlite3.Connection) -> list[sqlite3.Row]:
    return conn.execute(
        "SELECT * FROM projects WHERE watch_enabled = 1 ORDER BY created_at"
    ).fetchall()

upsert_pending_changes(conn, project_id, changes)

Record watcher-detected dirty files: (path, event_type) pairs. A re-event on the same path refreshes event_type and detected_at, so the row survives a clear cut at an earlier timestamp (the reindex race is resolved toward re-examination, never toward silent loss).

Source code in src/noesis/core/state.py
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
def upsert_pending_changes(
    conn: sqlite3.Connection,
    project_id: str,
    changes: Iterable[tuple[str, str]],
) -> None:
    """Record watcher-detected dirty files: (path, event_type) pairs. A
    re-event on the same path refreshes event_type and detected_at, so the
    row survives a clear cut at an earlier timestamp (the reindex race is
    resolved toward re-examination, never toward silent loss)."""
    now = _now()
    conn.executemany(
        """
        INSERT INTO pending_changes (project_id, path, event_type, detected_at)
        VALUES (?, ?, ?, ?)
        ON CONFLICT(project_id, path) DO UPDATE SET
          -- created + later modified is still a creation: the file has never
          -- been indexed. Deletion (or anything else) overwrites.
          event_type = CASE
            WHEN pending_changes.event_type = 'created'
                 AND excluded.event_type = 'modified'
            THEN 'created' ELSE excluded.event_type END,
          detected_at = excluded.detected_at
        """,
        [(project_id, path, event_type, now) for path, event_type in changes],
    )
    conn.commit()

list_pending_changes(conn, project_id)

Source code in src/noesis/core/state.py
943
944
945
946
947
948
949
950
def list_pending_changes(
    conn: sqlite3.Connection, project_id: str
) -> list[sqlite3.Row]:
    return conn.execute(
        "SELECT path, event_type, detected_at FROM pending_changes"
        " WHERE project_id = ? ORDER BY detected_at DESC, path",
        (project_id,),
    ).fetchall()

clear_pending_changes(conn, project_id, *, paths=None, before=None)

Clear pending rows after a run examined them. paths limits the clear to a scoped run's candidate set (None = full run cleared all); before keeps rows re-dirtied while the run was executing.

Source code in src/noesis/core/state.py
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
def clear_pending_changes(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    paths: Iterable[str] | None = None,
    before: str | None = None,
) -> None:
    """Clear pending rows after a run examined them. *paths* limits the
    clear to a scoped run's candidate set (None = full run cleared all);
    *before* keeps rows re-dirtied while the run was executing."""
    where = "project_id = ?"
    if before is not None:
        where += " AND detected_at <= ?"
    if paths is None:
        params = [project_id] + ([before] if before is not None else [])
        conn.execute(f"DELETE FROM pending_changes WHERE {where}", params)
    else:
        base = [project_id] + ([before] if before is not None else [])
        conn.executemany(
            f"DELETE FROM pending_changes WHERE {where} AND path = ?",
            [(*base, p) for p in paths],
        )
    conn.commit()

record_file_errors(conn, run_id, errors)

Source code in src/noesis/core/state.py
978
979
980
981
982
983
984
985
def record_file_errors(
    conn: sqlite3.Connection, run_id: str, errors: Iterable[tuple[str, str]]
) -> None:
    conn.executemany(
        "INSERT OR REPLACE INTO run_file_errors (run_id, path, error) VALUES (?, ?, ?)",
        [(run_id, path, err) for path, err in errors],
    )
    conn.commit()

list_file_errors(conn, run_id)

Source code in src/noesis/core/state.py
988
989
990
991
992
def list_file_errors(conn: sqlite3.Connection, run_id: str) -> list[sqlite3.Row]:
    return conn.execute(
        "SELECT path, error FROM run_file_errors WHERE run_id = ? ORDER BY path",
        (run_id,),
    ).fetchall()

list_unwalkable_dirs(conn, project_id)

Directories discovery could not walk, longest-standing first (ADR-56).

Empty is the healthy state. A row here does NOT mean anything was deleted or will be — it means part of the tree went unseen, so nothing under it can be proven absent.

Source code in src/noesis/core/state.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
def list_unwalkable_dirs(
    conn: sqlite3.Connection, project_id: str
) -> list[sqlite3.Row]:
    """Directories discovery could not walk, longest-standing first (ADR-56).

    Empty is the healthy state. A row here does NOT mean anything was deleted
    or will be — it means part of the tree went unseen, so nothing under it can
    be proven absent."""
    return conn.execute(
        "SELECT dir_path, consecutive_runs, first_seen_at, last_seen_at,"
        " last_error, quarantined_at FROM unwalkable_dirs WHERE project_id = ?"
        " ORDER BY first_seen_at, dir_path",
        (project_id,),
    ).fetchall()

count_unwalkable_dirs(conn, project_id)

(unwalkable, quarantined) counts for the status surfaces. The second is a subset of the first: COUNT(col) skips NULLs.

Source code in src/noesis/core/state.py
1011
1012
1013
1014
1015
1016
1017
1018
1019
def count_unwalkable_dirs(conn: sqlite3.Connection, project_id: str) -> tuple[int, int]:
    """``(unwalkable, quarantined)`` counts for the status surfaces. The second
    is a subset of the first: ``COUNT(col)`` skips NULLs."""
    row = conn.execute(
        "SELECT COUNT(*) AS n, COUNT(quarantined_at) AS q FROM unwalkable_dirs"
        " WHERE project_id = ?",
        (project_id,),
    ).fetchone()
    return int(row["n"]), int(row["q"])

reconcile_unwalkable_dirs(conn, project_id, *, reported, cleared, quarantine_after)

Fold one run's directory-level discovery result into the ledger (ADR-56).

reported are this run's DiscoveryErrors.dirs pairs — each bumps its row's consecutive-failure count. cleared are recorded paths this run proved walkable; their rows are deleted, which is what resets the count. The caller decides what "proved walkable" means, because that is path reasoning (indexer._under against the run's unwalked prefixes) and this module owns SQL only.

Deletes run before inserts. They are disjoint by construction — a path reported this run is by definition under this run's failures — but if that ever stopped holding, this order re-inserts at count 1 and merely DELAYS a quarantine. The other order would drop a row that had just been counted. Erring toward retrying too long is the same fail-safe direction as ADR-51.

quarantine_after is the consecutive-run threshold; 0 disables quarantine entirely and leaves quarantined_at NULL, so the retry behaviour reverts to what shipped in PR #24. quarantined_at is only ever set, never cleared: recovery deletes the whole row.

One BEGIN IMMEDIATE transaction for the same reason :func:add_dirty_paths uses one — a half-applied reconcile would either quarantine on a stale count or lose a recovery.

Source code in src/noesis/core/state.py
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
def reconcile_unwalkable_dirs(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    reported: Iterable[tuple[str, str]],
    cleared: Iterable[str],
    quarantine_after: int,
) -> None:
    """Fold one run's directory-level discovery result into the ledger (ADR-56).

    *reported* are this run's ``DiscoveryErrors.dirs`` pairs — each bumps its
    row's consecutive-failure count. *cleared* are recorded paths this run
    proved walkable; their rows are deleted, which is what resets the count.
    The caller decides what "proved walkable" means, because that is path
    reasoning (``indexer._under`` against the run's unwalked prefixes) and this
    module owns SQL only.

    Deletes run before inserts. They are disjoint by construction — a path
    reported this run is by definition under this run's failures — but if that
    ever stopped holding, this order re-inserts at count 1 and merely DELAYS a
    quarantine. The other order would drop a row that had just been counted.
    Erring toward retrying too long is the same fail-safe direction as ADR-51.

    *quarantine_after* is the consecutive-run threshold; ``0`` disables
    quarantine entirely and leaves ``quarantined_at`` NULL, so the retry
    behaviour reverts to what shipped in PR #24. ``quarantined_at`` is only
    ever set, never cleared: recovery deletes the whole row.

    One ``BEGIN IMMEDIATE`` transaction for the same reason
    :func:`add_dirty_paths` uses one — a half-applied reconcile would either
    quarantine on a stale count or lose a recovery.
    """
    reported = list(reported)
    cleared = [p for p in cleared]
    if not reported and not cleared:
        return
    now = _now()
    conn.execute("BEGIN IMMEDIATE")
    try:
        if cleared:
            conn.executemany(
                "DELETE FROM unwalkable_dirs WHERE project_id = ? AND dir_path = ?",
                [(project_id, p) for p in cleared],
            )
        if reported:
            conn.executemany(
                """
                INSERT INTO unwalkable_dirs (project_id, dir_path,
                    consecutive_runs, first_seen_at, last_seen_at, last_error)
                VALUES (?, ?, 1, ?, ?, ?)
                ON CONFLICT(project_id, dir_path) DO UPDATE SET
                  consecutive_runs = unwalkable_dirs.consecutive_runs + 1,
                  last_seen_at = excluded.last_seen_at,
                  last_error = excluded.last_error
                """,
                [(project_id, path, now, now, err) for path, err in reported],
            )
            if quarantine_after > 0:
                conn.execute(
                    "UPDATE unwalkable_dirs SET quarantined_at = ?"
                    " WHERE project_id = ? AND quarantined_at IS NULL"
                    " AND consecutive_runs >= ?",
                    (now, project_id, quarantine_after),
                )
    except BaseException:
        conn.rollback()
        raise
    conn.commit()

last_full_run_was_clean(conn, project_id)

Did the most recent finished full walk complete with no failures?

This is the best available answer to "could a promotion drain the H1 dirty set?", which is what the fraction trigger needs to know (ADR-57).

Deliberately left conservative by ADR-60, and this is the one paragraph to read before "fixing" it. The drains are no longer gated on clean_run: a full walk whose failures are all attributable now rewrites the dirty set to just the paths it could not verify. So a not-clean full walk does drain — but only down to a pinned floor, the unresolved set, which the next run re-derives identically while the fault is live. Counting that floor here would promote on a number promotion cannot move, which is exactly the latch the PR #30 review closed over two rounds: a broken subtree holding more than promote_candidate_fraction of the index would satisfy the threshold on every launch, forever. So this keeps reading clean, and keeps meaning "could a promotion drain the set to empty". The cost is a deferred promotion on a faulted project, which is the safe direction and no worse than before ADR-60.

Reads the run's persisted clean verdict rather than re-deriving it (ADR-58). It used to reconstruct it as files_failed == 0, which was true only while every term of clean_run was a file-level failure — and that has now drifted twice. Directory errors were the first (PR #30 round 2). Screening-held deletions were the second: they are deliberately absent from files_failed because nothing failed to index, so a degraded run reported files_failed == 0 while clean_run was False, and this function said "clean" about a run that had drained nothing — re-latching the fraction trigger on a dirty set promotion cannot shrink (PR #31 review). Persisting the writer's own verdict removes the class.

clean IS NULL means the row predates the column, so it falls back to the old derivation. That is right rather than merely compatible: those rows were written by code whose clean_run had no term the derivation missed.

Keyed on the outcome rather than the cause. Keying on unwalkable_dirs rows instead — the first version of this guard — covered only dir_errors, one of clean_run's terms (three then, four since ADR-58 added screening_held); a persistently unreadable file pins the set identically with no ledger row and latched the trigger just the same (PR #30 round-2 review). This subsumes the ledger check rather than sitting beside it.

Full runs only, and that restriction is the whole subtlety. A scoped run does not hash what is not in its candidate set, so a file that always fails to hash is simply never touched by one — every scoped run comes back clean while the fault is still there. Asking "was the last run clean" therefore flip-flops: clean scoped run → promote → the full walk hits the fault → not clean → no promote → clean scoped run → promote again. Only a full walk exercises what a full walk would exercise.

Runs still in flight are skipped (finished_at IS NOT NULL): their files_failed is NULL because they have not reported yet, not because they succeeded. scoped IS NULL rows predate the column and are read as full walks, consistently with :func:scoped_runs_since_full.

A project with no finished full run reads clean — there is nothing to drain either way, and the first full walk is exactly what reveals whether there is a fault. A NULL files_failed on a finished run (pre-ADR-41) reads NOT clean: the safe direction, since what this guards against is a permanent latch and the cost of being wrong is a deferred promotion.

Known gap, documented rather than coded (PR #30 round-3 review). What re-enables the caller's dirty term is a later clean full walk, and full walks come from the other two promotion triggers. So setting indexing.promote_after_scoped_runs = 0 while leaving promote_candidate_fraction on removes the fraction trigger's own recovery path: one transient failure during a full walk disables its dirty-driven half until some other full run happens. At the shipped defaults this is self-healing — the run-count trigger delivers a clean full walk within its threshold and the term comes back — and pending keeps counting either way, so the trigger is never wholly dead. Left as a documented interaction because the alternative is config-dependent guard logic that trades this latch for the one the guard exists to prevent.

Source code in src/noesis/core/state.py
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
def last_full_run_was_clean(conn: sqlite3.Connection, project_id: str) -> bool:
    """Did the most recent finished **full walk** complete with no failures?

    This is the best available answer to "could a promotion drain the H1 dirty
    set?", which is what the fraction trigger needs to know (ADR-57).

    **Deliberately left conservative by ADR-60, and this is the one paragraph
    to read before "fixing" it.** The drains are no longer gated on
    ``clean_run``: a full walk whose failures are all *attributable* now
    rewrites the dirty set to just the paths it could not verify. So a
    not-clean full walk does drain — but only down to a **pinned floor**, the
    unresolved set, which the next run re-derives identically while the fault
    is live. Counting that floor here would promote on a number promotion
    cannot move, which is exactly the latch the PR #30 review closed over two
    rounds: a broken subtree holding more than ``promote_candidate_fraction``
    of the index would satisfy the threshold on every launch, forever. So this
    keeps reading ``clean``, and keeps meaning "could a promotion drain the set
    **to empty**". The cost is a deferred promotion on a faulted project, which
    is the safe direction and no worse than before ADR-60.

    Reads the run's **persisted** ``clean`` verdict rather than re-deriving it
    (ADR-58). It used to reconstruct it as ``files_failed == 0``, which was
    true only while every term of ``clean_run`` was a file-level failure — and
    that has now drifted twice. Directory errors were the first (PR #30
    round 2). Screening-held deletions were the second: they are deliberately
    absent from ``files_failed`` because nothing failed to index, so a degraded
    run reported ``files_failed == 0`` while ``clean_run`` was False, and this
    function said "clean" about a run that had drained nothing — re-latching
    the fraction trigger on a dirty set promotion cannot shrink (PR #31
    review). Persisting the writer's own verdict removes the class.

    ``clean IS NULL`` means the row predates the column, so it falls back to
    the old derivation. That is right rather than merely compatible: those rows
    were written by code whose ``clean_run`` had no term the derivation missed.

    Keyed on the *outcome* rather than the cause. Keying on ``unwalkable_dirs``
    rows instead — the first version of this guard — covered only ``dir_errors``,
    one of ``clean_run``'s terms (three then, four since ADR-58 added
    ``screening_held``); a persistently unreadable **file** pins
    the set identically with no ledger row and latched the trigger just the same
    (PR #30 round-2 review). This subsumes the ledger check rather than sitting
    beside it.

    **Full** runs only, and that restriction is the whole subtlety. A scoped run
    does not hash what is not in its candidate set, so a file that always fails
    to hash is simply never touched by one — every scoped run comes back clean
    while the fault is still there. Asking "was the last run clean" therefore
    flip-flops: clean scoped run → promote → the full walk hits the fault →
    not clean → no promote → clean scoped run → promote again. Only a full walk
    exercises what a full walk would exercise.

    Runs still in flight are skipped (``finished_at IS NOT NULL``): their
    ``files_failed`` is NULL because they have not reported yet, not because
    they succeeded. ``scoped IS NULL`` rows predate the column and are read as
    full walks, consistently with :func:`scoped_runs_since_full`.

    A project with no finished full run reads clean — there is nothing to drain
    either way, and the first full walk is exactly what reveals whether there is
    a fault. A NULL ``files_failed`` on a finished run (pre-ADR-41) reads NOT
    clean: the safe direction, since what this guards against is a permanent
    latch and the cost of being wrong is a deferred promotion.

    **Known gap, documented rather than coded** (PR #30 round-3 review). What
    re-enables the caller's dirty term is a later clean full walk, and full
    walks come from the *other* two promotion triggers. So setting
    ``indexing.promote_after_scoped_runs = 0`` while leaving
    ``promote_candidate_fraction`` on removes the fraction trigger's own
    recovery path: one transient failure during a full walk disables its
    dirty-driven half until some other full run happens. At the shipped
    defaults this is self-healing — the run-count trigger delivers a clean full
    walk within its threshold and the term comes back — and ``pending`` keeps
    counting either way, so the trigger is never wholly dead. Left as a
    documented interaction because the alternative is config-dependent guard
    logic that trades this latch for the one the guard exists to prevent.
    """
    row = conn.execute(
        "SELECT status, files_failed, clean FROM index_runs"
        " WHERE project_id = ? AND finished_at IS NOT NULL"
        " AND (scoped = 0 OR scoped IS NULL)"
        " ORDER BY started_at DESC, rowid DESC LIMIT 1",
        (project_id,),
    ).fetchone()
    if row is None:
        return True
    if row["status"] != "done":
        return False
    if row["clean"] is not None:
        return bool(row["clean"])
    return row["files_failed"] == 0

scoped_runs_since_full(conn, project_id)

Scoped runs started since the last completed full walk (ADR-57).

What this measures is "has a full walk happened recently", not "has a drain happened". The two come apart, and the distinction is deliberate.

A full run that finishes done with contained per-file failures (ADR-41) is not a clean run, and it still resets this counter. Since ADR-60 such a run does take the drain branch when its failures are all attributable — the set is rewritten to the paths it could not verify — but it does not drain to empty, and an unattributable failure still takes no drain at all. So the gap between "a full walk happened" and "a drain happened" narrowed without closing, and what this counter measures is still the former. That looks wrong until you price the alternative: requiring a clean full run means a project with a permanently unreadable directory can never reset, so every launch past the threshold promotes. Measured at threshold 3 over 12 watcher runs on such a project: 3 full walks under this rule versus 9 under a clean-only rule — every run, on the population issue #25 is about, where the walk is slowest (9p/network mounts, ADR-45).

That comparison isolates this trigger (promote_candidate_fraction at 0), and it is only representative of the shipped defaults because the fraction trigger is separately stopped from latching the same way: it excludes the H1 dirty set once a ledger row makes that set undrainable (see jobs._promotion_reason). Before that fix the two latches compounded and the real figure at defaults was worse than the 3 quoted here — which is what the PR #30 review caught.

Nor would that have bought a drain at the time. Until ADR-60 the drain was blocked by the discovery error itself rather than by the promotion cadence, so promoting harder just re-walked a tree that still could not be drained — the gap issue #28 recorded. ADR-60 closed it in the other direction: a promoted full walk on a project with an attributable fault now rewrites the dirty set to the unverified remainder instead of leaving it pinned, so the periodic promotion this counter drives is what turns the old unbounded ramp into a bounded sawtooth. Promoting harder still would not help — the remainder is the floor, and no cadence gets under it.

The cost of this rule is bounded and self-healing: a transient failure on a full run delays the drain by one promotion cycle, and the next full run is clean and drains to empty.

A failed full run is different and does not reset: it may have stopped before walking anything, so it is not evidence a full walk happened at all.

scoped IS NULL rows predate the column. They are read as full walks for the baseline and never counted as scoped, so the counter simply starts from zero on an upgraded DB rather than inheriting a fabricated history.

Source code in src/noesis/core/state.py
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
def scoped_runs_since_full(conn: sqlite3.Connection, project_id: str) -> int:
    """Scoped runs started since the last *completed full walk* (ADR-57).

    What this measures is "has a full walk happened recently", **not** "has a
    drain happened". The two come apart, and the distinction is deliberate.

    A full run that finishes ``done`` with contained per-file failures
    (ADR-41) is not a *clean* run, and it still resets this counter. Since
    ADR-60 such a run does take the drain branch when its failures are all
    attributable — the set is rewritten to the paths it could not verify — but
    it does not drain to empty, and an unattributable failure still takes no
    drain at all. So the gap between "a full walk happened" and "a drain
    happened" narrowed without closing, and what this counter measures is
    still the former. That looks
    wrong until you price the alternative: requiring a clean full run means a
    project with a **permanently** unreadable directory can never reset, so
    every launch past the threshold promotes. Measured at threshold 3 over 12
    watcher runs on such a project: 3 full walks under this rule versus 9 under
    a clean-only rule — every run, on the population issue #25 is about, where
    the walk is slowest (9p/network mounts, ADR-45).

    That comparison isolates this trigger (``promote_candidate_fraction`` at
    0), and it is only representative of the shipped defaults because the
    fraction trigger is separately stopped from latching the same way: it
    excludes the H1 dirty set once a ledger row makes that set undrainable
    (see ``jobs._promotion_reason``). Before that fix the two latches
    compounded and the real figure at defaults was worse than the 3 quoted here
    — which is what the PR #30 review caught.

    Nor would that have bought a drain at the time. Until ADR-60 the drain was
    blocked by the discovery error itself rather than by the promotion cadence,
    so promoting harder just re-walked a tree that still could not be drained
    — the gap issue #28 recorded. ADR-60 closed it in the other direction:
    a promoted full walk on a project with an attributable fault now rewrites
    the dirty set to the unverified remainder instead of leaving it pinned, so
    the periodic promotion this counter drives is what turns the old unbounded
    ramp into a bounded sawtooth. Promoting harder still would not help — the
    remainder is the floor, and no cadence gets under it.

    The cost of this rule is bounded and self-healing: a *transient* failure on
    a full run delays the drain by one promotion cycle, and the next full run
    is clean and drains to empty.

    A **failed** full run is different and does not reset: it may have stopped
    before walking anything, so it is not evidence a full walk happened at all.

    ``scoped IS NULL`` rows predate the column. They are read as full walks for
    the baseline and never counted as scoped, so the counter simply starts from
    zero on an upgraded DB rather than inheriting a fabricated history."""
    row = conn.execute(
        """
        SELECT COUNT(*) AS n FROM index_runs
        WHERE project_id = ? AND scoped = 1 AND started_at > COALESCE(
              (SELECT MAX(started_at) FROM index_runs
               WHERE project_id = ? AND status = 'done'
                 AND (scoped = 0 OR scoped IS NULL)), '')
        """,
        (project_id, project_id),
    ).fetchone()
    return int(row["n"])

log_query(conn, *, interface, kind, project_id, channel=None, reranked=None, latency_ms=None, result_count=None)

Metadata-only usage telemetry (ADR-40): never stores query text.

Source code in src/noesis/core/state.py
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
def log_query(
    conn: sqlite3.Connection,
    *,
    interface: str,
    kind: str,
    project_id: str | None,
    channel: str | None = None,
    reranked: bool | None = None,
    latency_ms: float | None = None,
    result_count: int | None = None,
) -> None:
    """Metadata-only usage telemetry (ADR-40): never stores query text."""
    conn.execute(
        "INSERT INTO query_log (ts, interface, kind, project_id, channel,"
        " reranked, latency_ms, result_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        (
            _now(),
            interface,
            kind,
            project_id,
            channel,
            None if reranked is None else int(reranked),
            latency_ms,
            result_count,
        ),
    )
    conn.commit()

bump_watcher_stats(conn, project_id, *, events_seen=0, events_coalesced=0, auto_runs=0)

Source code in src/noesis/core/state.py
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def bump_watcher_stats(
    conn: sqlite3.Connection,
    project_id: str,
    *,
    events_seen: int = 0,
    events_coalesced: int = 0,
    auto_runs: int = 0,
) -> None:
    day = _now()[:10]
    conn.execute(
        """
        INSERT INTO watcher_stats (project_id, day, events_seen, events_coalesced, auto_runs)
        VALUES (?, ?, ?, ?, ?)
        ON CONFLICT(project_id, day) DO UPDATE SET
          events_seen = events_seen + excluded.events_seen,
          events_coalesced = events_coalesced + excluded.events_coalesced,
          auto_runs = auto_runs + excluded.auto_runs
        """,
        (project_id, day, events_seen, events_coalesced, auto_runs),
    )
    conn.commit()

get_setting(conn, key)

Source code in src/noesis/core/state.py
1297
1298
1299
1300
1301
def get_setting(conn: sqlite3.Connection, key: str) -> str | None:
    row = conn.execute(
        "SELECT value FROM app_settings WHERE key = ?", (key,)
    ).fetchone()
    return None if row is None else row["value"]

set_setting(conn, key, value)

Source code in src/noesis/core/state.py
1304
1305
1306
1307
1308
1309
1310
def set_setting(conn: sqlite3.Connection, key: str, value: str) -> None:
    conn.execute(
        "INSERT INTO app_settings (key, value) VALUES (?, ?)"
        " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
        (key, value),
    )
    conn.commit()

noesis.core.watcher

File watcher — near-real-time index freshness (Overview §4.9, ADR-40).

At most two watchdog observers serve every watched project: the native Observer (inotify on Linux) for roots on ordinary filesystems, and a PollingObserver for roots on filesystems where inotify is silently blind — network/host-passthrough mounts like WSL2's 9p drvfs (/mnt/c), CIFS, NFS, sshfs. On those, the kernel never delivers inotify events, so a watch schedules cleanly yet the handler never fires; polling is the only signal. Each observer's event thread does string checks only — no hashing, no file reads, no DB access — so watching never contends with the editor writing the file (stakeholder requirement: lightweight). Events are marshalled onto the asyncio loop, debounced and coalesced per (project, path), then written to pending_changes — the dashboard's "files awaiting reindex" view. For a project with auto_reindex enabled, a quiet period after the last event triggers a scoped run over exactly the pending paths (never a full re-embed; the run's own discovery + hash comparison stay authoritative).

Filtering here is deliberately a cheap approximation of discovery's rules (EXCLUDED_DIRS, secret + lockfile skip-lists, editor temp noise, the root .gitignore). Anything that slips through is at worst a cosmetic pending row: the scoped run re-applies discovery in full, and its clear step removes the row afterward. Nested .gitignore semantics are intentionally not replicated in the event path — correctness lives in the run, not the filter.

logger = logging.getLogger(__name__) module-attribute

WatcherManager(ctx, *, debounce_s=0.5, quiet_s=2.0, poll_interval_s=1.0)

Owns the observers, the debounce consumer, and per-project watches.

Constructed once in the app lifespan (ctx.watcher). Each observer thread (native inotify, and the polling fallback for inotify-blind mounts) starts lazily on the first watch that needs it, so test apps with no watched projects never spawn either. debounce_s is the flush cadence for pending rows; quiet_s is the no-events window required before an auto-reindex fires (a save burst becomes one scoped run, not N); poll_interval_s is the PollingObserver snapshot cadence (config watcher.poll_interval_s) — only polled roots pay it.

Source code in src/noesis/core/watcher.py
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
def __init__(
    self,
    ctx: Any,
    *,
    debounce_s: float = 0.5,
    quiet_s: float = 2.0,
    poll_interval_s: float = 1.0,
) -> None:
    self._ctx = ctx
    self.debounce_s = debounce_s
    self.quiet_s = quiet_s
    self.poll_interval_s = poll_interval_s
    self._observer: Any = None
    self._polling_observer: Any = None
    # root path -> inotify-blind fstype (or None). Caches the /proc/mounts
    # read + one-time warning so toggling watch on/off on the same root
    # neither re-reads /proc/mounts nor re-logs.
    self._fstype_cache: dict[str, str | None] = {}
    self._watches: dict[str, _ProjectWatch] = {}
    self._loop: asyncio.AbstractEventLoop | None = None
    self._queue: asyncio.Queue[tuple[str, str, str]] = asyncio.Queue()
    self._consumer: asyncio.Task | None = None
    # Accumulated between flushes: project_id -> {rel_path: event_type}.
    self._accum: dict[str, dict[str, str]] = {}
    self._seen_since_flush: dict[str, int] = {}
    self._last_event: dict[str, float] = {}

debounce_s = debounce_s instance-attribute

quiet_s = quiet_s instance-attribute

poll_interval_s = poll_interval_s instance-attribute

start()

Register watches for every watch_enabled project and start the consumer. Called from the app lifespan (loop is running).

Source code in src/noesis/core/watcher.py
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
def start(self) -> None:
    """Register watches for every watch_enabled project and start the
    consumer. Called from the app lifespan (loop is running)."""
    self._loop = asyncio.get_running_loop()
    self._consumer = self._loop.create_task(self._consume())
    for row in state.watched_projects(self._ctx.conn):
        self._schedule(row["id"], row["root_path"])
        # Catch-up: pending rows left over from a previous process (or
        # events missed while down) — if auto_reindex is on, run now.
        if not row["auto_reindex"]:
            continue
        # A project with recorded discovery failures gets a FULL catch-up
        # walk instead of a scoped one (ADR-56/57). Two reasons, and the
        # first is the one that matters: once quarantine stops re-pending
        # an unreadable subtree, that project may have NO pending rows
        # left — and every other automated trigger fires off a filesystem
        # event, which a dead mount does not produce. Without this, a
        # quarantined project would have nothing left that ever re-probes
        # it. Second, process start is when a fixed mount is most likely to
        # be noticed, and a full walk is what re-hashes the subtree.
        #
        # Exclusive with the scoped launch below: a second call would only
        # return `already_running` and waste the trip. The full run covers
        # the pending rows anyway — it clears them project-wide.
        if state.list_unwalkable_dirs(self._ctx.conn, row["id"]):
            self._launch(row["id"], None)
            continue
        pending = state.list_pending_changes(self._ctx.conn, row["id"])
        if pending:
            self._launch(row["id"], [p["path"] for p in pending])

stop() async

Source code in src/noesis/core/watcher.py
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
async def stop(self) -> None:
    # Stop the observers first (no new events), then drain what already
    # reached the queue and flush the accumulator — otherwise up to one
    # debounce window of events is dropped across a clean restart, and
    # start()'s catch-up only ever sees flushed rows (PR #10 review).
    # Async: the observer join is a blocking thread join (up to 5 s on a
    # slow dispatch) that must not stall the event loop mid-shutdown,
    # and the cancelled consumer must be awaited or the loop can tear
    # down while it is still pending ("Task was destroyed…"). Signal
    # both before joining either so the 5 s budgets overlap.
    observers = [
        o for o in (self._observer, self._polling_observer) if o is not None
    ]
    self._observer = None
    self._polling_observer = None
    for observer in observers:
        observer.stop()
    for observer in observers:
        await asyncio.to_thread(observer.join, 5)
    if self._consumer is not None:
        self._consumer.cancel()
        try:
            await self._consumer
        except asyncio.CancelledError:
            pass
        self._consumer = None
    while True:
        try:
            self._accumulate(self._queue.get_nowait())
        except asyncio.QueueEmpty:
            break
    try:
        self._flush()
    except Exception:  # noqa: BLE001 — shutdown must complete
        logger.exception("final watcher flush failed")
    self._watches.clear()

set_watch(project_id, enabled)

Live toggle from the dashboard. The flag is already persisted by the caller (core.dashboard); this only (un)schedules the OS watch.

Source code in src/noesis/core/watcher.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def set_watch(self, project_id: str, enabled: bool) -> None:
    """Live toggle from the dashboard. The flag is already persisted by
    the caller (core.dashboard); this only (un)schedules the OS watch."""
    if enabled:
        project = state.get_project(self._ctx.conn, project_id)
        if project is not None and project_id not in self._watches:
            self._schedule(project_id, project["root_path"])
    else:
        watch = self._watches.pop(project_id, None)
        if watch is not None and watch.observer is not None and watch.handle:
            watch.observer.unschedule(watch.handle)
        # Drop any buffered state for this project (H2). delete_project
        # calls this right before removing the projects row; a leftover
        # bucket would then fail pending_changes' FK on the next flush and,
        # because the accumulator is only cleared at the end of _flush,
        # re-raise every tick — wedging flush and auto-reindex for ALL
        # projects. Safe for a plain unwatch too: unbuffered events just
        # stop being recorded, which is what disabling the watch means.
        self._accum.pop(project_id, None)
        self._seen_since_flush.pop(project_id, None)
        self._last_event.pop(project_id, None)

watching(project_id)

Source code in src/noesis/core/watcher.py
314
315
def watching(self, project_id: str) -> bool:
    return project_id in self._watches

mode(project_id)

"polling"/"native" for a watched project, None otherwise. The dashboard shows a "polling" tag so degraded-signal roots (9p, network mounts) are visible, not just logged.

Source code in src/noesis/core/watcher.py
317
318
319
320
321
322
323
324
325
326
def mode(self, project_id: str) -> str | None:
    """``"polling"``/``"native"`` for a watched project, None otherwise.
    The dashboard shows a "polling" tag so degraded-signal roots (9p,
    network mounts) are visible, not just logged."""
    watch = self._watches.get(project_id)
    if watch is None:
        return None
    if watch.observer is self._polling_observer and watch.observer is not None:
        return "polling"
    return "native"

noesis.core.telemetry

Usage telemetry — metadata-only query logging (ADR-40).

Feeds the dashboard's usage page. Records that a query happened and how it performed (interface, kind, channel, latency, result count) — never the query text: queries routinely quote proprietary code, and a local DB is still a file that gets backed up, synced, and pasted into bug reports (ADR-25 spirit). Logging is fire-and-forget: a telemetry failure must never fail — or delay — the search that triggered it.

Writes are handed to a dedicated writer thread over a bounded queue and never touch the caller's ctx.conn. Two reasons, both from the dual-transport deployment (HTTP server + stdio MCP sharing one DB file):

  • ctx.conn has busy_timeout=5000, so an INSERT contending with the other process's index-run writes would stall the event loop up to 5s.
  • Even off the loop, an awaited write keeps the response waiting on that contention. Enqueueing returns immediately, so the query path pays nothing beyond a queue put.

The writer owns its own connections (one per DB path, busy_timeout=250) and is the only thread that touches them, so no lock is needed. On a full queue or a busy DB the row is dropped: telemetry may lose a row, never slow a query.

:class:QueryTelemetry holds all of that as instance state, and every AppContext owns one (ADR-59). That is what makes close() terminal: once a context tears its writer down, a late record_query drops its row instead of opening a fresh state.connect() handle the closing context will never reap. Terminality costs nothing here because there is no global to reset — a second context simply constructs a second writer, open from birth. LocalSTEmbedder is the same shape for the same reason (embedder.py: _closed, a terminal idempotent close(), and a _submit that refuses afterwards).

Dropping a late row is the right side to err on, and is not the same choice LocalSTEmbedder makes: a refused embedding is a correctness loss, so it raises; a refused telemetry row is this module's documented contract, so it returns quietly at DEBUG.

The bounded join at teardown is MCP-1's, not a caveat about ownership: a writer stuck on a foreign lock is abandoned rather than waited on forever. An abandoned writer keeps its own queue with the shutdown sentinel still in it, so it stops itself once the backlog clears, and it holds no reference back to the :class:QueryTelemetry that started it — an abandoned thread must not keep an entire AppContext alive.

Consequence worth knowing: the usage page is eventually consistent. A query is normally readable within microseconds, but it is not guaranteed to be there the instant the response returns — under the contention above it can lag up to 250ms or be dropped entirely. Anything that needs read-your-writes (tests, mainly) must await :meth:QueryTelemetry.flush.

logger = logging.getLogger(__name__) module-attribute

QueryTelemetry(queue_max=_QUEUE_MAX)

One query-telemetry writer, owned by one AppContext (ADR-59).

The worker thread starts lazily on the first accepted row (daemon, so never calling :meth:close is safe) and stops at :meth:close, which is terminal and idempotent. Two live contexts in one process therefore have two independent writers: neither one's teardown can discard the other's queued rows, retire the other's worker, or leave a handle to the other's DB open. That is a mechanism, not an invariant — the point of issue #27.

queue_max bounds the backlog. It is a constructor argument rather than a module constant to monkeypatch, which is the same thing instance state buys everywhere else here: a test that wants a small queue builds a small writer instead of mutating one every other test shares.

Source code in src/noesis/core/telemetry.py
165
166
167
168
169
def __init__(self, queue_max: int = _QUEUE_MAX) -> None:
    self._queue: queue.Queue[Any] = queue.Queue(maxsize=queue_max)
    self._lock = threading.Lock()
    self._worker: threading.Thread | None = None
    self._closed = False

record_query(conn, *, interface, kind, project_id, channel=None, reranked=None, latency_ms=None, result_count=None) async

Queue one metadata-only usage row and return.

conn is the caller's shared connection, and is used on the caller's own thread only — to name the DB file the writer should open, or to write inline when there is no file to open. The writer thread never touches it.

Source code in src/noesis/core/telemetry.py
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
async def record_query(
    self,
    conn: sqlite3.Connection,
    *,
    interface: str,
    kind: str,
    project_id: str | None,
    channel: str | None = None,
    reranked: bool | None = None,
    latency_ms: float | None = None,
    result_count: int | None = None,
) -> None:
    """Queue one metadata-only usage row and return.

    *conn* is the caller's shared connection, and is used on the
    caller's own thread only — to name the DB file the writer should
    open, or to write inline when there is no file to open. The writer
    thread never touches it.
    """
    fields: dict[str, Any] = dict(
        interface=interface,
        kind=kind,
        project_id=project_id,
        channel=channel,
        reranked=reranked,
        latency_ms=latency_ms,
        result_count=result_count,
    )
    try:
        if self._closed:
            # Terminal (ADR-59): a torn-down context records nothing more,
            # on either DB shape. Read without the lock deliberately — a
            # bool read cannot tear, this is not a correctness gate, and
            # the authoritative check is _submit's, which tests the same
            # flag under the lock close() holds.
            logger.debug("query telemetry: writer closed; dropping row")
            return
        # Quick read on the caller's thread: resolve the DB file behind the
        # shared conn so the writer opens the same DB. In-memory pragma, no
        # IO, no lock.
        row = conn.execute("PRAGMA database_list").fetchone()
        db_path = row[2] if row is not None else ""
        if not db_path:
            # In-memory DB: a second connection cannot reach it — write on
            # the shared conn as before (test-only shape; runtime DBs are
            # always files).
            state.log_query(conn, **fields)
            return
        if not self._submit((db_path, fields)):
            logger.debug("query telemetry row not accepted; dropping")
    except Exception:  # noqa: BLE001 — telemetry must never break the query path
        logger.debug("query telemetry write failed", exc_info=True)

flush(timeout=5.0) async

Wait until every row queued so far has been written.

The write is asynchronous by design, so anything that reads a row back right after recording it (tests, and the dashboard's usage page if it ever wants read-your-writes) needs this barrier. Returns when the rows land or timeout elapses; it never raises.

Source code in src/noesis/core/telemetry.py
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
async def flush(self, timeout: float = 5.0) -> None:
    """Wait until every row queued so far has been written.

    The write is asynchronous by design, so anything that reads a row
    back right after recording it (tests, and the dashboard's usage page
    if it ever wants read-your-writes) needs this barrier. Returns when
    the rows land or *timeout* elapses; it never raises."""
    # The barrier goes in while the lock is still held. Releasing it first
    # and putting afterwards leaves a window where close() retires the
    # writer and finishes its drain, so the barrier lands in a queue no
    # worker will ever serve and this waits the full timeout for nothing
    # (PR #24 review). close() cannot start until it acquires this same
    # lock, so the barrier is now either served by the live worker or set
    # by close()'s drain.
    barrier = _Barrier()
    deadline = time.monotonic() + timeout
    while True:
        with self._lock:
            live = self._worker is not None and self._worker.is_alive()
            if self._closed or not live:
                # Nothing to wait for. A writer that was never started has
                # been handed nothing; one that close() stopped has either
                # written its backlog (the join returned) or is finishing
                # it on a queue it still owns, and in that second case
                # anything already queued is written, not stranded.
                return
            try:
                self._queue.put_nowait(barrier)
                break
            except queue.Full:
                pass
        # A full queue is the opposite of "nothing to wait for": it is the
        # maximum backlog, reached only when the writer is stalled on a
        # foreign lock — the one time a caller most needs a real barrier.
        # Dropping ROWS on overflow is the documented contract; dropping
        # the BARRIER and returning would report "flushed" with a full
        # queue pending (PR #24 review). So retry under the same deadline.
        # A blocking `put(barrier, timeout=...)` is not the fix: the queue
        # is only safe to read under the lock, and holding it across a
        # blocking call would stall the `_submit` on the query path that
        # this whole module exists to keep out of the way.
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            # Waited the caller's whole budget without ever queuing the
            # barrier. A flush that spends its timeout and gives up is
            # honest; one that returns instantly is not.
            return
        await asyncio.sleep(min(_FLUSH_RETRY_S, remaining))
    await asyncio.to_thread(
        barrier.event.wait, max(0.0, deadline - time.monotonic())
    )

close(timeout=5.0)

Stop the writer thread, draining what is already queued.

Terminal and idempotent: after this, :meth:record_query drops rows rather than starting a second worker. Called from close_runtime_context beside ctx.conn.close() so the telemetry handles do not outlive the runtime that created them — an open second handle to the state DB blocks temp-directory cleanup on Windows and WSL, and survives a DB file removal. Bounded like the model workers (MCP-1): a stuck writer is abandoned, never waited on forever.

Source code in src/noesis/core/telemetry.py
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
def close(self, timeout: float = 5.0) -> None:
    """Stop the writer thread, draining what is already queued.

    Terminal and idempotent: after this, :meth:`record_query` drops rows
    rather than starting a second worker. Called from
    ``close_runtime_context`` beside ``ctx.conn.close()`` so the
    telemetry handles do not outlive the runtime that created them — an
    open second handle to the state DB blocks temp-directory cleanup on
    Windows and WSL, and survives a DB file removal. Bounded like the
    model workers (MCP-1): a stuck writer is abandoned, never waited on
    forever.
    """
    with self._lock:
        if self._closed:
            # Idempotent, and deliberately does not wait for the first
            # caller's drain — same contract as LocalSTEmbedder.close().
            return
        self._closed = True
        worker = self._worker
    # From here the queue is frozen: every put path tests _closed under
    # the lock just released, so nothing new can arrive and the queue is
    # this function's alone for the rest of its body.
    if worker is None or not worker.is_alive():
        # Still drain: a retired writer must not leave rows sitting in a
        # queue nobody will ever serve, which is what makes flush()'s
        # no-worker early return honest.
        _discard_queued(self._queue)
        return
    try:
        self._queue.put_nowait(_SHUTDOWN)
    except queue.Full:
        # The writer is behind, not gone. Clear the backlog so the sentinel
        # lands rather than leaking the thread — those rows were already
        # droppable under the overflow contract.
        _discard_queued(self._queue)
        try:
            self._queue.put_nowait(_SHUTDOWN)
        except queue.Full:  # pragma: no cover — the queue was just emptied
            logger.warning("telemetry queue full; writer thread abandoned")
    worker.join(timeout=timeout)
    if worker.is_alive():
        logger.warning(
            "telemetry writer did not stop within %.0fs; abandoning "
            "(daemon thread)",
            timeout,
        )
        # Do NOT drain here. The worker still owns this queue and has not
        # reached the sentinel yet — `_discard_queued` would swallow it,
        # and the worker would then block on `work.get()` forever with its
        # connections open: precisely the handle leak this function exists
        # to prevent (PR #24 review, reproduced with a 250ms-per-row
        # backlog against a 1s join). The backlog is the worker's to
        # finish, and it will: exactly one sentinel is ever enqueued, only
        # `_writer_loop` consumes one, and it returns the moment it does.
        return
    # After the join, not before it: rows ahead of the sentinel are written
    # by the exiting worker. Nothing can have landed behind it, so this
    # normally finds an empty queue — it runs anyway so that the degraded
    # branch above, which discards a backlog and re-puts the sentinel while
    # the worker is concurrently draining, cannot leave a row behind.
    _discard_queued(self._queue)

noesis.core.dashboard

Dashboard read models + settings mutations (M8, ADR-40).

All SQL and aggregation for the human monitoring surface lives here — api/dashboard.py renders templates and forwards JSON, nothing more (thin-adapter rule). Everything reads the local SQLite state; nothing here may perform network I/O (CLAUDE.md rule 2).

logger = logging.getLogger(__name__) module-attribute

VALID_DEVICES = ('auto', 'cuda', 'mps', 'cpu') module-attribute

overview(ctx)

The GET / read model: every project's health at a glance.

Source code in src/noesis/core/dashboard.py
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
def overview(ctx: Any) -> dict[str, Any]:
    """The GET / read model: every project's health at a glance."""
    projects = [_project_summary(ctx, row) for row in state.list_projects(ctx.conn)]
    # Local import, matching jobs.py's existing convention for reaching into
    # noesis.prefetch (index_status imports model_readiness/reranker_readiness
    # the same way) — prefetch.py lives outside core/ on purpose (its own
    # module docstring), and job_status only reads an in-memory dict, no I/O.
    from noesis.prefetch import job_status

    return {
        "projects": projects,
        "totals": {
            "projects": len(projects),
            "files": sum(p["file_count"] for p in projects),
            "chunks": sum(p["chunk_count"] for p in projects),
            "pending": sum(p["pending_count"] for p in projects),
            "running": sum(
                1
                for p in projects
                if p["last_run"] is not None and p["last_run"]["status"] == "running"
            ),
        },
        "device": device_info(ctx),
        # Issue #51: the dashboard's "Download models" progress, process-wide
        # rather than per-project (see runtime.AppContext.prefetch_job).
        "prefetch": job_status(ctx),
    }

project_detail(ctx, project_id)

Per-project drill-down: pending files, recent runs, failed files.

Source code in src/noesis/core/dashboard.py
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
def project_detail(ctx: Any, project_id: str) -> dict[str, Any] | None:
    """Per-project drill-down: pending files, recent runs, failed files."""
    project = state.get_project(ctx.conn, project_id)
    if project is None:
        return None
    summary = _project_summary(ctx, project)
    pending = [dict(row) for row in state.list_pending_changes(ctx.conn, project_id)]
    runs = [
        dict(row)
        for row in ctx.conn.execute(
            "SELECT * FROM index_runs WHERE project_id = ?"
            " ORDER BY started_at DESC, rowid DESC LIMIT 20",
            (project_id,),
        ).fetchall()
    ]
    # Failed files of the most recent run that recorded any — the
    # actionable set (older runs' failures were either fixed or recur here).
    failed_files: list[dict[str, Any]] = []
    for run in runs:
        errors = state.list_file_errors(ctx.conn, run["id"])
        if errors:
            failed_files = [
                {"path": e["path"], "error": e["error"], "run_id": run["id"]}
                for e in errors
            ]
            break
    # Unwalkable directories, each with the number of indexed files it hides —
    # the figure that tells an operator whether this is a stray subdirectory or
    # most of the project (ADR-56). Counted from `files` rather than from disk:
    # the whole problem is that the directory cannot be read, so stored state
    # is the only thing that can answer "how much is behind this".
    unwalkable_dirs = []
    for row in state.list_unwalkable_dirs(ctx.conn, project_id):
        dir_path = row["dir_path"]
        if is_attributable_prefix(dir_path):
            # Prefix match without LIKE: `_` is a single-character wildcard
            # there, and directory names contain underscores constantly, so
            # `src/my_module` also matched `src/myXmodule/...` and inflated the
            # count (PR #30 review). `substr` compares the separator-terminated
            # prefix literally — the same containment rule `indexer._under`
            # applies, which is why `pkg` must not match `pkg2/`.
            hidden = ctx.conn.execute(
                "SELECT COUNT(*) AS n FROM files WHERE project_id = ?"
                " AND (path = ? OR substr(path, 1, length(?) + 1) = ? || '/')",
                (project_id, dir_path, dir_path, dir_path),
            ).fetchone()["n"]
        else:
            # `<root>`, or a path outside the root: no prefix describes it, so
            # every stored file is behind it.
            hidden = summary["file_count"]
        unwalkable_dirs.append({**dict(row), "files_hidden": hidden})
    return {
        **summary,
        "pending_files": pending,
        "recent_runs": runs,
        "failed_files": failed_files,
        "unwalkable_dirs": unwalkable_dirs,
    }

usage(ctx, days=30)

The usage-page read model (ADR-40): index activity, index health, search usage, watcher activity — everything derived, nothing stored beyond what the run/query/watcher tables already hold.

Source code in src/noesis/core/dashboard.py
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
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
def usage(ctx: Any, days: int = 30) -> dict[str, Any]:
    """The usage-page read model (ADR-40): index activity, index health,
    search usage, watcher activity — everything derived, nothing stored
    beyond what the run/query/watcher tables already hold."""
    conn = ctx.conn
    # Day-granularity cutoff on both sides: stored timestamps are ISO with a
    # 'T' separator + tz offset, SQLite's datetime() emits space-separated —
    # comparing them raw is only lexically right away from the boundary
    # (PR #10 review). substr → date-vs-date is exact.
    cutoff = f"-{days} days"
    _DAY = "substr({col}, 1, 10) >= date('now', ?)"

    runs_per_day = [
        dict(row)
        for row in conn.execute(
            f"""
            SELECT substr(started_at, 1, 10) AS day,
                   COUNT(*) AS runs,
                   SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed,
                   SUM(CASE WHEN triggered_by = 'watcher' THEN 1 ELSE 0 END) AS watcher_runs,
                   COALESCE(SUM(files_changed), 0) AS files_changed,
                   COALESCE(SUM(chunks_written), 0) AS chunks_written
            FROM index_runs
            WHERE {_DAY.format(col="started_at")}
            GROUP BY day ORDER BY day
            """,
            (cutoff,),
        ).fetchall()
    ]
    run_stats = dict(
        conn.execute(
            f"""
            SELECT COUNT(*) AS total_runs,
                   SUM(CASE WHEN fast_path_used = 1 THEN 1 ELSE 0 END) AS fast_path_runs,
                   AVG(CASE WHEN finished_at IS NOT NULL AND started_at IS NOT NULL
                       THEN (julianday(finished_at) - julianday(started_at)) * 86400.0
                       END) AS avg_duration_s
            FROM index_runs
            WHERE {_DAY.format(col="started_at")}
            """,
            (cutoff,),
        ).fetchone()
    )

    queries_per_day = [
        dict(row)
        for row in conn.execute(
            f"""
            SELECT substr(ts, 1, 10) AS day,
                   COUNT(*) AS queries,
                   SUM(CASE WHEN interface = 'mcp' THEN 1 ELSE 0 END) AS mcp,
                   SUM(CASE WHEN interface = 'rest' THEN 1 ELSE 0 END) AS rest,
                   SUM(CASE WHEN kind = 'structural' THEN 1 ELSE 0 END) AS structural,
                   SUM(CASE WHEN reranked = 1 THEN 1 ELSE 0 END) AS reranked
            FROM query_log
            WHERE {_DAY.format(col="ts")}
            GROUP BY day ORDER BY day
            """,
            (cutoff,),
        ).fetchall()
    ]
    latencies = [
        row["latency_ms"]
        for row in conn.execute(
            f"SELECT latency_ms FROM query_log"
            f" WHERE {_DAY.format(col='ts')} AND latency_ms IS NOT NULL"
            f" ORDER BY latency_ms",
            (cutoff,),
        ).fetchall()
    ]

    def pct(p: float) -> float | None:
        if not latencies:
            return None
        idx = min(len(latencies) - 1, int(round(p * (len(latencies) - 1))))
        return round(latencies[idx], 1)

    channel_mix = [
        dict(row)
        for row in conn.execute(
            f"SELECT COALESCE(channel, 'structural') AS channel, COUNT(*) AS queries"
            f" FROM query_log WHERE {_DAY.format(col='ts')}"
            f" GROUP BY channel ORDER BY queries DESC",
            (cutoff,),
        ).fetchall()
    ]

    watcher_per_day = [
        dict(row)
        for row in conn.execute(
            """
            SELECT day,
                   SUM(events_seen) AS events_seen,
                   SUM(events_coalesced) AS events_coalesced,
                   SUM(auto_runs) AS auto_runs
            FROM watcher_stats
            WHERE day >= date('now', ?)
            GROUP BY day ORDER BY day
            """,
            (cutoff,),
        ).fetchall()
    ]

    # Direct grouped queries instead of a full _project_summary per project
    # (which also computes live progress) — the health table needs 6 fields
    # (PR #10 review).
    file_counts = {
        r["project_id"]: r
        for r in conn.execute(
            "SELECT project_id, COUNT(*) AS files,"
            " COALESCE(SUM(chunk_count), 0) AS chunks"
            " FROM files GROUP BY project_id"
        ).fetchall()
    }
    pending_counts = {
        r["project_id"]: r["n"]
        for r in conn.execute(
            "SELECT project_id, COUNT(*) AS n FROM pending_changes GROUP BY project_id"
        ).fetchall()
    }
    last_done = {
        r["project_id"]: r["finished_at"]
        for r in conn.execute(
            "SELECT project_id, MAX(finished_at) AS finished_at"
            " FROM index_runs WHERE status = 'done' GROUP BY project_id"
        ).fetchall()
    }
    health = []
    for row in state.list_projects(conn):
        pid = row["id"]
        counts = file_counts.get(pid)
        latest = state.get_latest_run(conn, pid)
        health.append(
            {
                "id": pid,
                "name": PurePath(row["root_path"]).name or row["root_path"],
                "file_count": counts["files"] if counts else 0,
                "chunk_count": counts["chunks"] if counts else 0,
                "pending_count": pending_counts.get(pid, 0),
                "index_age_s": _age_seconds(last_done.get(pid)),
                "files_failed": (latest["files_failed"] if latest else 0) or 0,
            }
        )

    return {
        "days": days,
        "index_activity": {
            "per_day": runs_per_day,
            "total_runs": run_stats["total_runs"] or 0,
            "fast_path_runs": run_stats["fast_path_runs"] or 0,
            "avg_duration_s": (
                None
                if run_stats["avg_duration_s"] is None
                else round(run_stats["avg_duration_s"], 2)
            ),
        },
        "search_usage": {
            "per_day": queries_per_day,
            "total_queries": sum(q["queries"] for q in queries_per_day),
            "latency_p50_ms": pct(0.50),
            "latency_p95_ms": pct(0.95),
            "channel_mix": channel_mix,
        },
        "watcher_activity": {"per_day": watcher_per_day},
        "index_health": health,
    }

set_project_flags(ctx, project_id, *, watch_enabled=None, auto_reindex=None)

Persist watcher flags and apply them live. Enabling auto_reindex on a project with pending changes triggers an immediate catch-up scoped run — the toggle means "keep me fresh", not "keep me fresh starting with the next keystroke".

Source code in src/noesis/core/dashboard.py
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
def set_project_flags(
    ctx: Any,
    project_id: str,
    *,
    watch_enabled: bool | None = None,
    auto_reindex: bool | None = None,
) -> dict[str, Any] | None:
    """Persist watcher flags and apply them live. Enabling auto_reindex on
    a project with pending changes triggers an immediate catch-up scoped
    run — the toggle means "keep me fresh", not "keep me fresh starting
    with the next keystroke"."""
    project = state.get_project(ctx.conn, project_id)
    if project is None:
        return None
    state.set_project_flags(
        ctx.conn, project_id, watch_enabled=watch_enabled, auto_reindex=auto_reindex
    )
    watcher = getattr(ctx, "watcher", None)
    if watcher is not None and watch_enabled is not None:
        watcher.set_watch(project_id, watch_enabled)
    if auto_reindex:
        pending = state.list_pending_changes(ctx.conn, project_id)
        if pending:
            try:
                jobs.launch_index_run(
                    ctx,
                    project["root_path"],
                    paths=[p["path"] for p in pending],
                    triggered_by="watcher",
                )
            except (ValueError, state.IndexCapacityReached) as exc:
                # Best effort by design: the flag change the operator asked
                # for must succeed even when the catch-up run cannot start.
                logger.warning("catch-up reindex skipped: %s", exc)
    refreshed = state.get_project(ctx.conn, project_id)
    assert refreshed is not None
    return _project_summary(ctx, refreshed)

reindex_pending(ctx, project_id)

Dashboard action: scoped run over the current pending set (or a plain incremental run when nothing is pending — the button always means "make it fresh now").

Source code in src/noesis/core/dashboard.py
412
413
414
415
416
417
418
419
420
421
422
423
def reindex_pending(ctx: Any, project_id: str) -> dict[str, Any] | None:
    """Dashboard action: scoped run over the current pending set (or a
    plain incremental run when nothing is pending — the button always
    means "make it fresh now")."""
    project = state.get_project(ctx.conn, project_id)
    if project is None:
        return None
    pending = state.list_pending_changes(ctx.conn, project_id)
    paths = [p["path"] for p in pending] or None
    return jobs.launch_index_run(
        ctx, project["root_path"], paths=paths, triggered_by="manual"
    )

device_info(ctx)

Current compute-device state for the dashboard settings surface.

Source code in src/noesis/core/dashboard.py
436
437
438
439
440
441
442
443
444
445
446
447
def device_info(ctx: Any) -> dict[str, Any]:
    """Current compute-device state for the dashboard settings surface."""
    setting = state.get_setting(ctx.conn, "compute_device") or "auto"
    pin = _config_pin(ctx)
    embedder = ctx.embedder
    return {
        "setting": setting,
        "config_pin": pin,
        "effective_source": "config.toml" if pin else "setting",
        "resolved": getattr(embedder, "resolved_device", None),
        "available": available_devices(),
    }

set_compute_device(ctx, device)

Persist the device choice and hot-retarget the loaded models (generation-bump reload, ADR-40). Raises ValueError on an invalid value or when config.toml pins either model's device (operator config wins).

Source code in src/noesis/core/dashboard.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def set_compute_device(ctx: Any, device: str) -> dict[str, Any]:
    """Persist the device choice and hot-retarget the loaded models
    (generation-bump reload, ADR-40). Raises ValueError on an invalid
    value or when config.toml pins either model's device (operator config
    wins)."""
    if device not in VALID_DEVICES:
        raise ValueError(f"device must be one of {', '.join(VALID_DEVICES)}")
    if _config_pin(ctx):
        raise ValueError(
            "device is pinned in config.toml; remove the [embedder]/[reranker]"
            " device pin to control it from the dashboard"
        )
    state.set_setting(ctx.conn, "compute_device", device)
    target = None if device == "auto" else device
    for model in (ctx.embedder, getattr(ctx, "reranker", None)):
        setter = getattr(model, "set_device", None)
        if setter is not None:
            setter(target)
    return device_info(ctx)

delete_project(ctx, project_id) async

Remove a project's index state entirely (ADR-43): cancel its running index task, unschedule its watch, drop its Qdrant points, delete its SQLite rows. Touches ONLY derived index state — never the project's source tree. Returns False for an unknown project.

Order matters: the watch goes first, then runs are drained, then points, then rows — everything that could write must be silenced before the wipe.

The watch is unscheduled before the drain because draining awaits, and an await hands the loop back to the watcher's consumer task. Its _maybe_auto_reindex gates on auto_reindex alone — never on watch_enabled — so the instant the cancelled run is marked failed it would happily start a fresh one for this project and that run, never cancelled, would write points after the wipe. set_watch(False) is what actually disarms it: it drops the project's _last_event bucket, which is the collection that method iterates.

The drain loops rather than cancelling once: the watcher is not the only launcher. A concurrent REST/MCP reindex can win the same window, and a single cancel-then-wipe would sail straight past it. Each pass costs at most one file's upsert, and the bound keeps a pathological relaunch storm from wedging the request — the startup sweep reclaims anything that somehow still slips through.

The cancelled task is awaited, not just cancelled, and that await is only meaningful because indexer.execute_run shields its upsert and waits out the in-flight write before dying: cancelling a task parked on await asyncio.to_thread(...) otherwise returns at once while the worker thread runs on, landing its points after the wipe and orphaning them under a dead project_id. The two halves are one fix — dropping either reopens the leak. runtime.py's startup sweep is the backstop for the orphans no wipe could prevent (a killed process).

Source code in src/noesis/core/dashboard.py
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
async def delete_project(ctx: Any, project_id: str) -> bool:
    """Remove a project's index state entirely (ADR-43): cancel its running
    index task, unschedule its watch, drop its Qdrant points, delete its
    SQLite rows. Touches ONLY derived index state — never the project's
    source tree. Returns False for an unknown project.

    Order matters: the watch goes first, then runs are drained, then points,
    then rows — everything that could write must be silenced before the wipe.

    The watch is unscheduled *before* the drain because draining awaits, and
    an await hands the loop back to the watcher's consumer task. Its
    ``_maybe_auto_reindex`` gates on ``auto_reindex`` alone — never on
    ``watch_enabled`` — so the instant the cancelled run is marked failed it
    would happily start a fresh one for this project and that run, never
    cancelled, would write points after the wipe. ``set_watch(False)`` is
    what actually disarms it: it drops the project's ``_last_event`` bucket,
    which is the collection that method iterates.

    The drain loops rather than cancelling once: the watcher is not the only
    launcher. A concurrent REST/MCP ``reindex`` can win the same window, and
    a single cancel-then-wipe would sail straight past it. Each pass costs at
    most one file's upsert, and the bound keeps a pathological relaunch storm
    from wedging the request — the startup sweep reclaims anything that
    somehow still slips through.

    The cancelled task is *awaited*, not just cancelled, and that await is
    only meaningful because indexer.execute_run shields its upsert and waits
    out the in-flight write before dying: cancelling a task parked on
    ``await asyncio.to_thread(...)`` otherwise returns at once while the
    worker thread runs on, landing its points after the wipe and orphaning
    them under a dead project_id. The two halves are one fix — dropping
    either reopens the leak. runtime.py's startup sweep is the backstop for
    the orphans no wipe could prevent (a killed process)."""
    project = state.get_project(ctx.conn, project_id)
    if project is None:
        return False
    watcher = getattr(ctx, "watcher", None)
    if watcher is not None:
        watcher.set_watch(project_id, False)
    for _ in range(_DELETE_DRAIN_PASSES):
        latest = state.get_latest_run(ctx.conn, project_id)
        if latest is None or latest["status"] != "running":
            break
        task = ctx.jobs.get(latest["id"])
        if task is None:
            # Marked running but not ours: another transport's process owns
            # it and we cannot cancel across processes. Wipe anyway — its
            # points are that process's to orphan, and the startup sweep is
            # what reclaims them.
            break
        task.cancel()
        await asyncio.gather(task, return_exceptions=True)
    await asyncio.to_thread(ctx.store.delete_project_points, project_id)
    state.delete_project(ctx.conn, project_id)
    logger.info("project %s deleted (%s)", project_id, project["root_path"])
    return True

supported_languages()

Canonical languages Noesis indexes, with their extensions and whether structural (AST) search supports them. Static — derived from the language maps.

Source code in src/noesis/core/dashboard.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def supported_languages() -> list[dict[str, Any]]:
    """Canonical languages Noesis indexes, with their extensions and whether
    structural (AST) search supports them. Static — derived from the language
    maps."""
    by_name: dict[str, list[str]] = {}
    for ext, name in EXT_TO_LANGUAGE.items():
        by_name.setdefault(name, []).append(ext)
    return [
        {
            "language": name,
            "extensions": sorted(exts),
            "structural": name in LANGUAGE_MAP,
        }
        for name, exts in sorted(by_name.items())
    ]

browse_dir(path=None)

List sub-directories for the register folder-picker (ADR-42).

Directories only, never file contents — the picker chooses a project root. Localhost-only surface (rule 2); errors on an unreadable or non-directory path. Defaults to the user's home directory.

Source code in src/noesis/core/dashboard.py
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
def browse_dir(path: str | None = None) -> dict[str, Any]:
    """List sub-directories for the register folder-picker (ADR-42).

    Directories only, never file contents — the picker chooses a project
    root. Localhost-only surface (rule 2); errors on an unreadable or
    non-directory path. Defaults to the user's home directory."""
    base = Path(path).expanduser() if path else Path.home()
    try:
        base = base.resolve()
    except OSError as exc:
        raise ValueError(f"cannot resolve path: {exc}") from exc
    if not base.is_dir():
        raise ValueError(f"not a directory: {base}")
    entries: list[dict[str, str]] = []
    try:
        for child in sorted(base.iterdir(), key=lambda p: p.name.lower()):
            try:
                if child.is_dir():
                    entries.append({"name": child.name, "path": str(child)})
            except OSError:
                continue  # unreadable child — skip, don't fail the listing
    except OSError as exc:
        raise ValueError(f"cannot list directory: {exc}") from exc
    parent = str(base.parent) if base.parent != base else None
    return {"path": str(base), "parent": parent, "entries": entries}

preview_scan(ctx, root_path, *, index_languages=None, max_file_bytes=None, follow_symlinks=False, extra_ignores=None) async

Pre-flight: run discovery only (no hashing, no embed, no state write) and report what WOULD be indexed — file count + per-language breakdown (ADR-42). The same walk a real index does, in a threadpool so it never blocks the event loop.

Source code in src/noesis/core/dashboard.py
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
async def preview_scan(
    ctx: Any,
    root_path: str,
    *,
    index_languages: list[str] | None = None,
    max_file_bytes: int | None = None,
    follow_symlinks: bool = False,
    extra_ignores: list[str] | None = None,
) -> dict[str, Any]:
    """Pre-flight: run discovery only (no hashing, no embed, no state write)
    and report what WOULD be indexed — file count + per-language breakdown
    (ADR-42). The same walk a real index does, in a threadpool so it never
    blocks the event loop."""
    if not os.path.isdir(root_path):
        raise ValueError(f"root_path is not an existing directory: {root_path!r}")
    cfg = _discovery_config(
        index_languages=index_languages,
        max_file_bytes=max_file_bytes,
        follow_symlinks=follow_symlinks,
        extra_ignores=extra_ignores,
    )
    loop = asyncio.get_running_loop()
    files = await loop.run_in_executor(None, discover_files, root_path, cfg)
    by_lang: dict[str, int] = {}
    for rel in files:
        lang = detect_language(rel) or "other"
        by_lang[lang] = by_lang.get(lang, 0) + 1
    breakdown = sorted(
        ({"language": k, "files": v} for k, v in by_lang.items()),
        key=lambda d: (-d["files"], d["language"]),
    )
    return {
        "root_path": str(Path(root_path).resolve()),
        "total_files": len(files),
        "by_language": breakdown,
    }

register_project(ctx, root_path, *, watch=False, auto_reindex=False, index_languages=None, max_file_bytes=None, follow_symlinks=False, extra_ignores=None, index_now=False)

Register a project from the dashboard (ADR-42), persist its index scope + watcher flags, optionally start the first index. Raises ValueError on a missing directory or the mixed-model guard.

index_now=False registers without indexing (the 'Add only' action); True also launches the first run ('Add + index now').

Source code in src/noesis/core/dashboard.py
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
def register_project(
    ctx: Any,
    root_path: str,
    *,
    watch: bool = False,
    auto_reindex: bool = False,
    index_languages: list[str] | None = None,
    max_file_bytes: int | None = None,
    follow_symlinks: bool = False,
    extra_ignores: list[str] | None = None,
    index_now: bool = False,
) -> dict[str, Any]:
    """Register a project from the dashboard (ADR-42), persist its index
    scope + watcher flags, optionally start the first index. Raises
    ValueError on a missing directory or the mixed-model guard.

    ``index_now=False`` registers without indexing (the 'Add only' action);
    ``True`` also launches the first run ('Add + index now')."""
    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)
    state.set_index_config(
        ctx.conn,
        project_id,
        index_languages=index_languages,
        max_file_bytes=max_file_bytes,
        follow_symlinks=follow_symlinks,
        extra_ignores=extra_ignores,
    )
    state.set_project_flags(
        ctx.conn, project_id, watch_enabled=watch, auto_reindex=auto_reindex
    )
    # Unconditional: re-registering an already-watched project with
    # watch=False must also unschedule the live OS watch, or events keep
    # flowing while the flag reads off (PR #10 review).
    watcher = getattr(ctx, "watcher", None)
    if watcher is not None:
        watcher.set_watch(project_id, watch)
    run: dict[str, Any] | None = None
    if index_now:
        try:
            run = jobs.launch_index_run(ctx, root_path, triggered_by="manual")
        except state.IndexCapacityReached as exc:
            # The project is already registered by this point. Failing the
            # whole request would leave the operator with a registered
            # project and an error, so report no run instead — the same
            # outcome as index_now=False, which the UI already renders, and
            # the Reindex button covers the retry.
            logger.warning("register: initial index run not started: %s", exc)
    project = state.get_project(ctx.conn, project_id)
    assert project is not None
    return {"project": _project_summary(ctx, project), "run": run}