Metadata-Version: 2.5
Name: lexwheel-core
Version: 0.1.0
Summary: Core term catalog for lexwheel: manual curation, time-based retirement, SQLite store.
Project-URL: Homepage, https://github.com/Suadeo03/lexwheel
Project-URL: Source, https://github.com/Suadeo03/lexwheel
Project-URL: Issues, https://github.com/Suadeo03/lexwheel/issues
Author: Brian Dillon
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic>=2.6
Requires-Dist: pyyaml>=6
Description-Content-Type: text/markdown

# lexwheel-core

A single-tenant term catalog: curate keywords by hand, tag them, give them a language, and let
them retire on a date or after disuse. SQLite by default, YAML in and out. It stores and serves
terms; it does not scan text (that is [kascade](https://github.com/Suadeo03/kascade)'s job, and
the two need not know about each other).

```
pip install lexwheel-core
```

Python 3.11+. Depends on `pydantic` and `pyyaml` only. The full `lexwheel` package adds
org-level catalogs, a feedback lifecycle, suggestions and outcome attribution on top of this one.

## A curated keyword service

Campaign terms expire with the campaign; evergreen terms fade if nobody uses them.

```python
from lexwheel_core import Catalog
cat = Catalog()   # sqlite:///lexwheel.db
cat.add("black friday",     label="campaign", weight=0.8, expires_at="2026-12-01",
        tags={"channel:web"})
cat.add("loyalty rewards",  label="program",  weight=0.7)
cat.add("free shipping",    label="offer",    weight=0.6, tags={"channel:email"})
# the search service records hits it finds with its own matcher
for hit in search_hits:
    cat.record_match(hit.term_id)
cat.sweep()                                   # nightly: expiry, inactivity, recovery
web_terms = cat.terms(tags={"channel:web"})   # what the web tagger should load
cat.export_yaml("catalog.yaml")               # git-reviewable snapshot
```

"black friday" retires on 1 December without anyone remembering to remove it. Terms nobody hits
for 60 days drop in weight, and retire 90 days later unless they start matching again.

`Catalog` is synchronous. `AsyncCatalog` has the same methods as coroutines.

## Terms

| Field | Notes |
| --- | --- |
| `text`, `label`, `weight` | Weight is 0.0 to 1.0. Label is a lowercase slug. |
| `kind` | `literal` (default), `template`, `synonym_group`, `anchor`, `cross_rule`. Payloads are validated, never expanded. |
| `lang` | BCP 47 tag or `None` (language-neutral). Part of term identity. |
| `tags` | `key:value` strings. `terms(tags=...)` also returns untagged terms unless `tags_only=True`. |
| `expires_at` | Fixed retirement time. A bare date means 00:00 UTC. |
| `band` | Derived from weight (`direct` ≥ 0.75, `indicator` ≥ 0.40, else `oblique`). Never stored. |

Identity is `(normalised text, label, lang)`; adding a duplicate raises `DuplicateTermError`.

```python
cat.terms(lang="fr-CA")        # fr-CA, bare fr, and language-neutral terms; not en
cat.terms(label="offer", kinds=["literal"], statuses=("active", "declining", "retired"))
cat.update(term_id, weight=0.9, notes="tuned")
cat.retire(term_id, reason="campaign over");  cat.reactivate(term_id)
cat.exclude(term_id)           # never returned by terms(), still stored
cat.version()                  # changes on every write that affects terms(); use it as a cache key
cat.changes(term_id)           # change log: who, what, before and after
```

## Retirement

`sweep(now=None)` applies, once per term and in this order:

1. **Expiry.** `expires_at` has passed: retired.
2. **Recovery.** Declining, and at least `recovery_min_matches` matches since it started declining: active again at its original weight.
3. **Retire.** Declining for more than `declining_days`: retired.
4. **Decline.** Active, no `expires_at`, and unmatched for more than `inactivity_days`: declining, weight × `decay_factor`.

`record_match` and `record_matches` log hits; they never change status, the next `sweep` does.
Retired terms are kept and readable with `statuses=("retired",)`.

## YAML

```yaml
lexwheel: 1
terms:
  - text: "can't afford groceries"
    label: food-insecurity
    weight: 0.92
    lang: en
    tags: [setting:primary-care]
    expires_at: 2027-03-31
    flags: [alert_on_negated]
```

`cat.import_yaml(path, on_duplicate="skip" | "error" | "max_weight")` and `cat.export_yaml(path)`.
Export is sorted by label, text, lang so diffs stay small. Unsaid's phrase dictionaries import with
`cat.import_yaml(directory, format="unsaid")`.

## Integrity checks

`cat.check()` returns `Issue(code, severity, term_ids, message)` for: `band-mismatch`,
`duplicate-across-labels`, `deny-listed-token`, `short-token`, `template-unresolved`,
`cross-rule-unknown-label`, `expired-active`. Installing the package registers a pytest fixture
that fails a test on any error:

```python
def test_catalog_is_clean(lexwheel_check):
    lexwheel_check("catalog.yaml")
```

## Configuration

Layers, later wins: package defaults, then `lexwheel.toml` (`Catalog(config=...)` or `LEXWHEEL_CONFIG`)
or a dict, then environment variables such as `LEXWHEEL_RETIREMENT__INACTIVITY_DAYS=30`.
A key listed under `[locks].keys` by an earlier layer raises `ConfigLockedError` if a later layer
sets it. `cat.config.explain()` shows each key, its value and where it came from.

```toml
acknowledge_defaults = false

[lexwheel.store]
url = "sqlite:///lexwheel.db"      # or "memory://"; sqlite:////abs/path.db for absolute paths

[lexwheel.bands]
direct = 0.75
indicator = 0.40

[lexwheel.retirement]
inactivity_days = 60
declining_days = 90
decay_factor = 0.75
recovery_min_matches = 1
```

The band and retirement defaults were tuned on one clinical text corpus. Until you set them, or
set `acknowledge_defaults = true`, the first `Catalog` opened in a process emits
`DefaultThresholdsWarning` naming the keys still at their defaults.

## License

Apache License 2.0. Copyright 2026 Brian Dillon. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
