> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monolex.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Scope & Index Management

> Project database ownership, schema-v17 corpus policy, deep-index health, selective recovery, exclusions, and cleanup in monogram 0.98.11.

Every Monogram query is answered by one registered project database. Correct output therefore depends on three separate facts: which root owns the query, whether the core index is current, and whether the optional semantic companion is verified for the same corpus policy.

*Documents the public OpenCLIs release `monogram 0.98.11`.*

## One project, one database

By default, project databases and the registry live under:

```text theme={null}
~/.monolex/monogram/
```

`MONOGRAM_HOME=<dir>` relocates the core/semantic database estate under
`<dir>/monogram/`. Since 0.98.2 it also relocates sequence sessions under
`<dir>/problem-definitions/`; without the override those sessions remain under
the workspace's `.monogram/problem-definitions/`. This keeps isolated CI,
benchmark, and disposable-worktree patches free of Monogram state while still
allowing portable prepared indexes.

```bash theme={null}
monogram list --health
monogram stats --deep
```

`stats` is the current-query authority: it shows the selected database path, registered root, schema/corpus identity, builder state, failure cache, and optional deep status.

## Which database answers?

Monogram resolves the deepest registered ancestor of the current working directory. It searches upward, not downward.

```text theme={null}
/repo                 root index answers while cwd is /repo
├── apps/web          nested index answers only while cwd is inside apps/web
└── libs/engine       nested index answers only while cwd is inside libs/engine
```

Consequences:

1. A nested registered project wins while your current directory is inside it.
2. A query from `/repo` cannot automatically use a richer database registered at `/repo/apps/web`.
3. A miss from the outer root is not proof that a symbol is absent from nested projects.

Monogram prints a descendant-index hint when a more specific registered project may own a miss. Follow it and rerun from that subtree.

```bash theme={null}
cd /repo/apps/web
monogram symbols createSession
```

## Inspect the index estate

```bash theme={null}
monogram list
monogram list --health
monogram list --stale
monogram list --sort=size
monogram list --json
```

| Health flag | Meaning                                                                                      |
| ----------- | -------------------------------------------------------------------------------------------- |
| blank       | Independent, usable project database                                                         |
| `stale`     | Registered source files changed after the index state                                        |
| `ORPHAN`    | The registered source directory no longer exists                                             |
| `dangling`  | Registry/database ownership is incomplete                                                    |
| `empty`     | The database exists but contains no usable indexed files                                     |
| `covered`   | Actual rows are already covered by an ancestor index; eligible for optional registry cleanup |

`covered` is based on row overlap, not path nesting alone.

## Incremental index and full rebuild

```bash theme={null}
# Everyday path: incremental core refresh plus the persisted deep policy
monogram index .

# Run a query after an incremental refresh
monogram search "new symbol" -r

# Full crash-safe rebuild
monogram reindex .
```

| Operation                     | Use it for                                                                |
| ----------------------------- | ------------------------------------------------------------------------- |
| Query with no refresh         | Deliberately inspect the existing snapshot; read the freshness disclosure |
| `-r` / `--reindex` on a query | Incrementally refresh first, then run the query                           |
| `monogram index <path>`       | Explicit incremental index/reconciliation                                 |
| `monogram reindex <path>`     | Full rebuild for schema/corpus recovery or suspected corruption           |

Despite the shared spelling, the query flag `-r` is incremental; the standalone `reindex` command is a full rebuild.

## Schema-v17 corpus policy

A successful full index records the corpus policy required to reproduce the database:

* extensions and language selection;
* workspace expansion;
* scope and nested-project exclusions;
* explicit `--add` roots;
* Wasm/format participation where applicable;
* whether the semantic companion is part of the effective policy.

The build writes a durable catch-up marker before mutation, publishes the root/database registry mapping, and reconciles the exact corpus. If a process stops mid-update, the pending marker remains evidence that the two planes may not agree.

### Extraction contract, not executable version

Monogram stores an extraction-contract epoch separately from the binary's
SemVer. Incremental writes remain valid when a newer or differently labeled
binary implements the same corpus contract. If the stored epoch differs, the
writer refuses to stamp current provenance and requires a full rebuild.

```text theme={null}
same contract epoch + changed binary version ──▶ incremental write allowed
different contract epoch ──────────────────────▶ fail closed, then reindex
```

This gate tracks the shape and meaning of extracted data. A release-number
change alone is neither evidence that a rebuild is needed nor permission to
reuse an incompatible corpus.

### Deep policy and fail-closed reads

The normal `monogram index .` includes the semantic companion. A successful deep build must be rebuilt and verified before the pending marker can clear. If core or semantic reconciliation fails:

* the command exits non-zero;
* pending/invalid state remains visible;
* official deep readers fail closed instead of treating stale semantic data as current.

```bash theme={null}
monogram index . --deep
monogram semantic status
```

A deliberate full `--no-deep` index establishes an own-index-only policy and can clear against that policy. It is not a way to downgrade a previously pending deep recovery through `--files-from`; selective recovery must honor the stored policy.

## Index options

```bash theme={null}
monogram index <path> [options]
```

| Option                    | Effect                                                              |
| ------------------------- | ------------------------------------------------------------------- |
| `--ext ts,rs,...`         | Use an explicit extension set                                       |
| `--add <dir>`             | Add an otherwise excluded dependency/source root; repeatable        |
| `--workspace`             | Force Cargo/npm workspace expansion                                 |
| `--no-workspace`          | Pin the walk to the supplied path                                   |
| `--deep`                  | Explicitly request the semantic companion                           |
| `--no-deep`               | Establish an own-index-only full policy                             |
| `--exclude-nested`        | Skip subdirectories that are separately registered projects         |
| `--no-gc`                 | Retain rows for vanished files during this pass                     |
| `--skip-if-locked`        | Daemon/watcher mode yields instead of contending for the index lock |
| `--files-from <file-or->` | Reconcile authoritative event paths from a file or stdin            |

Automatic deleted-file GC refuses a suspicious blast radius when both thresholds are crossed: more than 20 candidate rows and more than 50% of the corpus. Inspect with `monogram prune --dry-run`; override only after proving the registered root is correct.

## Selective `--files-from` recovery

`monogram index --files-from` is the event-carrier path used by watchers and recovery workflows. It replays the stored schema-v17 policy instead of inventing a smaller one.

```bash theme={null}
monogram index . --files-from changed-paths.txt
printf '%s\n' src/session.rs | monogram index . --files-from -
```

Input records are exact newline paths. Existing files are force-reread even when mtime/failure caches would normally skip them. Directory records reconcile the exact subtree. Missing paths, symlinks, and special-file witnesses remove stale rows or subtrees.

The semantic companion is marked invalid before core mutation. Existing-file
events may refresh only those files when the companion is already current.
During the paired pass, Monogram can run bounded scoped refresh rounds for
content or corpus-membership drift it actually observes. A new or removed
source outside the authoritative carrier is not silently accepted: unresolved
structural drift keeps the semantic generation invalid and requires a broader
index. A missing or stale companion also widens semantic reconciliation to the
project root. Any incomplete core or deep pass leaves readers fail-closed.

`monogram reindex` rejects `--files-from`: a full rebuild owns the entire corpus by definition.

NIIA's dirty-index workflow uses this carrier and can recover a durable catch-up marker left by a stopped run. The watcher subscription and explicit `--add` roots must intersect; otherwise use an explicit carrier or a full index.

## Exclusions and explicit scope

Two root-relative surfaces are unioned:

1. `.monogramignore` — one directory/prefix per line, with `#` comments.
2. `.monogram/scope.json` — managed by `monogram scope`.

Both core and deep walkers honor the effective union.

```bash theme={null}
monogram scope
monogram scope exclude vendor/archive
monogram scope include vendor/archive
monogram scope apply --dry-run
monogram scope apply
```

`scope exclude` changes future policy. `scope apply` removes already-indexed rows under the excluded prefixes from Monogram's own databases. It does not delete source, but the database mutation is immediate; preview it first.

Hidden entries remain excluded even when `--add` is used. Use a narrow dependency root such as `--add node_modules/@tauri-apps/api`, not an entire generated/vendor estate, when you need one external type surface.

## Workspace behavior

Indexing a member of a Cargo or npm workspace can expand to the workspace root so cross-package edges resolve. Use:

* `--no-workspace` when the supplied subtree is intentionally the full corpus;
* `--workspace` when expansion is required but auto-detection is ambiguous;
* `--exclude-nested` at a large monorepo root when separately registered subprojects should not be duplicated.

Always verify the resulting root with `monogram stats` rather than inferring it from the command argument.

## Freshness disclosure

Before investigations, Monogram compares the registered index to the filesystem and reports `fresh`, `stale`, or `fresh (sampled)` for very large corpora. Results are still from the current database snapshot; the banner does not silently refresh them.

```bash theme={null}
MONOGRAM_FRESH_CHECK=full monogram stats
MONOGRAM_FRESH_CHECK=off monogram search "known snapshot"
```

Use `full` when exact checking matters. Use `off` only when an external controller already owns freshness and the snapshot boundary is explicit.

## Pruning the current database

```bash theme={null}
monogram prune --dry-run
monogram prune
```

Current-database prune removes vanished source rows and stale deleted-file failure-cache entries. It is not bounded by the automatic GC blast-radius refusal, so the preview is important.

## Registry and database cleanup

```bash theme={null}
monogram prune --registry
monogram prune --registry --covered
monogram prune --registry --force
```

Registry mode plans stale, orphan, dangling, and optionally covered database cleanup. It synchronizes a root tombstone before recorded-generation deletion so interrupted cleanup can rediscover residue on retry. Without `--force`, treat the result as a plan.

### Reindex generation retention

A crash-safe reindex publishes a new database generation only after validation.
Version 0.98.11 then applies a bounded retention rule:

```text theme={null}
all live registry CURRENT pointers ───────────────▶ always protected
newest previously served superseded generation ─▶ one rollback/reader margin
older superseded + same-root crash orphans ──────▶ reclaimed
```

The sweep checks recorded root provenance before removal. It does not delete a
generation owned by another registered project, and it preserves one recently
served generation so an in-flight reader or immediate rollback is not cut off.

## Prepared-index guard

Set `MONOGRAM_PREPARED_INDEX=1` when a benchmark or CI harness must hold an immutable prepared index. It blocks local mutators including:

* `monogram index` and `monogram reindex`;
* query-time `-r` refresh;
* `monogram prune`;
* `monogram boot init`.

Read-only query and MCP surfaces remain available against the prepared snapshot.

## Claude hook boundary

`monogram hook claude` is an optional fail-quiet PostToolUse carrier. It updates at most one supported core-index file only when the database is registered, current schema/builder/root policy matches, and the event is well formed.

It does not create or migrate databases, run the deep pass, perform GC, or bypass locks/prepared-index guards. If the hook skips an event, use ordinary `monogram index .` to reconcile the project.

### Shipped hook lifecycle

The public 0.98.11 binary exposes the lifecycle commands directly:

| Command                                     | Contract                                                                                                                               |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `monogram hook install [--settings <path>]` | Idempotently merges the PostToolUse entry into `~/.claude/settings.json` (or the selected file) while preserving every unrelated hook. |
| `monogram hook status [--settings <path>]`  | Reports whether the exact Monogram matcher and installed-binary command are present.                                                   |
| `monogram hook remove [--settings <path>]`  | Removes only the matching Monogram entry and leaves other PostToolUse hooks intact.                                                    |

The carrier keeps the same guarded single-file core refresh. While a sequence
is open, it additionally emits Claude PostToolUse
`additionalContext` reminding the agent to run `sequence finish` after the
final Edit/Write. The reminder is throttled to 300 seconds by default;
`MONOGRAM_HOOK_REMINDER_SECS` overrides that interval. `status` is read-only;
`install` and `remove` write the selected Claude settings file.

## Verification checklist

```bash theme={null}
monogram list --health
monogram stats --deep
monogram semantic status
monogram verify
```

Keep these proof layers separate:

1. `list --health` proves registry/database estate state.
2. `stats --deep` proves the database selected for this working directory.
3. `semantic status` proves whether deep evidence is current and usable.
4. `verify` proves the installed binary's embedded guide/Book build consistency, not the freshness of a project index.
