# `cleveragents.acms` — Advanced Context Management System

The `acms` package implements the **Universal Knowledge Ontology (UKO)** vocabulary
support for the Advanced Context Management System.  It provides a four-layer
ontology hierarchy for representing code semantics across multiple programming
languages, enabling actors to reason about large codebases with structured,
budget-constrained context views.

See [ADR-014](../adr/ADR-014-context-management-acms.md) for the design rationale
and [`docs/modules/uko-provenance.md`](../modules/uko-provenance.md) for provenance
tracking details.

---

## Architecture Overview

The UKO is organized into four layers:

| Layer | Scope | Examples |
|-------|-------|---------|
| **Layer 0** | Universal primitives | `Container`, `Atom`, `Boundary`, `dependsOn` |
| **Layer 1** | General code domain | `TypeDefinition`, `Callable` |
| **Layer 2** | Programming paradigms | `uko-oo:`, `uko-func:`, `uko-proc:` |
| **Layer 3** | Language-specific | `uko-py:`, `uko-ts:`, `uko-rs:`, `uko-java:` |

---

## Namespace Prefixes

| Prefix | IRI | Layer |
|--------|-----|-------|
| `uko-oo:` | `https://cleveragents.ai/ontology/uko/oo#` | 2 |
| `uko-func:` | `https://cleveragents.ai/ontology/uko/func#` | 2 |
| `uko-proc:` | `https://cleveragents.ai/ontology/uko/proc#` | 2 |
| `uko-py:` | `https://cleveragents.ai/ontology/uko/py#` | 3 |
| `uko-ts:` | `https://cleveragents.ai/ontology/uko/ts#` | 3 |
| `uko-rs:` | `https://cleveragents.ai/ontology/uko/rs#` | 3 |
| `uko-java:` | `https://cleveragents.ai/ontology/uko/java#` | 3 |

---

## Core Types

### `ProvenanceInfo`

```python
from cleveragents.acms import ProvenanceInfo

class ProvenanceInfo(BaseModel):
    source_resource: str        # IRI of the source resource
    valid_from: datetime        # When this triple became valid
    is_current: bool            # Whether this is the current revision
    created_by: str             # Agent or process that created this
    revision_chain: list[str]   # Ordered list of prior revision IRIs
```

Provenance contract attached to every typed triple in the UKO graph.  Enables
temporal queries and point-in-time ontology state reconstruction.

---

### `UKOClass`

```python
from cleveragents.acms import UKOClass

class UKOClass(BaseModel):
    uri: str                    # Fully-qualified OWL class URI
    label: str                  # Human-readable label
    parent_uri: str | None      # rdfs:subClassOf parent URI
    description: str = ""       # Optional description
```

Represents an OWL class definition within a UKO vocabulary.

---

### `UKOProperty`

```python
from cleveragents.acms import UKOProperty

class UKOProperty(BaseModel):
    uri: str                    # Fully-qualified OWL property URI
    label: str                  # Human-readable label
    domain_uri: str             # rdfs:domain class URI
    range_uri: str              # rdfs:range class URI
    parent_uri: str | None      # rdfs:subPropertyOf parent URI
```

Represents an OWL object property definition within a UKO vocabulary.

---

### `UKOVocabulary`

```python
from cleveragents.acms import UKOVocabulary

class UKOVocabulary(BaseModel):
    prefix: str                         # Namespace prefix (e.g. "uko-py:")
    iri: str                            # Namespace IRI
    classes: tuple[UKOClass, ...]       # OWL classes in this vocabulary
    properties: tuple[UKOProperty, ...]  # OWL properties in this vocabulary
    layer2_deps: tuple[Layer2Dependency, ...]  # Layer 2 dependencies
```

Container for a complete UKO vocabulary (classes + properties + dependencies).

---

### `Layer2Dependency`

```python
from cleveragents.acms import Layer2Dependency

class Layer2Dependency(BaseModel):
    iri: str    # Layer 2 vocabulary IRI this vocabulary depends on
```

Declares a dependency from a Layer 3 vocabulary on a Layer 2 paradigm vocabulary.

---

## Layer 2 — Paradigm Vocabularies

### `ParadigmVocabulary`

```python
from cleveragents.acms import ParadigmVocabulary

class ParadigmVocabulary(BaseModel):
    prefix: str                         # e.g. "uko-oo:"
    iri: str                            # Namespace IRI
    classes: tuple[VocabularyClass, ...]
    properties: tuple[VocabularyProperty, ...]
```

Immutable (frozen) Pydantic model for a Layer 2 paradigm vocabulary.

**Built-in paradigm vocabularies:**

```python
from cleveragents.acms import get_oo_vocabulary, get_func_vocabulary, get_proc_vocabulary

oo_vocab = get_oo_vocabulary()      # Object-Oriented paradigm (uko-oo:)
func_vocab = get_func_vocabulary()  # Functional paradigm (uko-func:)
proc_vocab = get_proc_vocabulary()  # Procedural paradigm (uko-proc:)
```

---

### `VocabularyRegistry`

```python
from cleveragents.acms import VocabularyRegistry, DuplicateVocabularyError

registry = VocabularyRegistry(vocabularies=(get_oo_vocabulary(),))

# Register a vocabulary
registry.register(get_func_vocabulary())

# Look up by prefix
vocab = registry.get_by_prefix("uko-oo:")

# Look up by IRI
vocab = registry.get_by_iri("https://cleveragents.ai/ontology/uko/oo#")

# List all registered prefixes
prefixes = registry.list_prefixes()

# List all vocabularies
all_vocabs = registry.list_all()

# Unregister
registry.unregister("uko-oo:")
```

**Thread safety:** `VocabularyRegistry` is **not** thread-safe.  Populate once
during module initialisation under the GIL; do not mutate from multiple threads.

**Raises:** `DuplicateVocabularyError` if a vocabulary with the same prefix or IRI
is already registered.

---

## Detail Level Maps

Detail level maps control how much semantic detail is included in context views
for each code construct.  They form an inheritance chain: Layer 3 maps extend
Layer 2 maps, which extend Layer 1 maps.

### Built-in Maps

```python
from cleveragents.acms import (
    CODE_DETAIL_LEVEL_MAP,   # Layer 1 general code domain
    OO_DETAIL_LEVEL_MAP,     # Layer 2 Object-Oriented
    FUNC_DETAIL_LEVEL_MAP,   # Layer 2 Functional
    PROC_DETAIL_LEVEL_MAP,   # Layer 2 Procedural
)
```

Each map is a `DetailLevelMap` with a `.levels` dict mapping level names to
integer depth values.

### `DetailLevelMapBuilder`

```python
from cleveragents.acms import DetailLevelMapBuilder

builder = DetailLevelMapBuilder(parent=OO_DETAIL_LEVEL_MAP)
builder.insert("uko-py:decorator", depth=3)
builder.insert("uko-py:type_stub", depth=4)
py_map = builder.build()
```

Builds a new `DetailLevelMap` by inserting level entries into a parent map.

### `build_detail_level_map`

```python
from cleveragents.acms import build_detail_level_map

level_map = build_detail_level_map(
    parent=OO_DETAIL_LEVEL_MAP,
    insertions=[("uko-py:decorator", 3), ("uko-py:type_stub", 4)],
)
```

Functional alternative to `DetailLevelMapBuilder`.

### `build_effective_map`

```python
from cleveragents.acms import build_effective_map

effective = build_effective_map(
    parent=OO_DETAIL_LEVEL_MAP,
    child=PYTHON_DETAIL_LEVELS,
)
```

Merges a parent map and a child map into a single effective map, with child
entries taking precedence over parent entries.

### `resolve_detail_level`

```python
from cleveragents.acms import resolve_detail_level

depth = resolve_detail_level(
    name="uko-py:function",
    maps=[PYTHON_DETAIL_LEVELS, OO_DETAIL_LEVEL_MAP, CODE_DETAIL_LEVEL_MAP],
)
```

Walks the inheritance chain (Layer 3 → Layer 2 → Layer 1) to resolve a named
detail level to its integer depth.  Returns `None` if not found in any map.

---

## Layer 3 — Language Vocabularies

### Python (`uko-py:`)

```python
from cleveragents.acms import (
    PYTHON_VOCABULARY,    # ParadigmVocabulary for Python
    PYTHON_DETAIL_LEVELS, # DetailLevelMap for Python
    PythonModule,
    PythonClass,
    PythonFunction,
    PythonDecorator,
    PythonTypeStub,
)
```

| Class | Parent | Description |
|-------|--------|-------------|
| `PythonModule` | `uko-oo:Module` | A Python `.py` module |
| `PythonClass` | `uko-oo:Class` | A Python class definition |
| `PythonFunction` | `uko-oo:Method` | A Python function or method |
| `PythonDecorator` | `uko-oo:Annotation` | A Python decorator |
| `PythonTypeStub` | `uko-oo:Interface` | A `.pyi` type stub |

### TypeScript (`uko-ts:`)

```python
from cleveragents.acms import (
    TYPESCRIPT_VOCABULARY,
    TYPESCRIPT_DETAIL_LEVELS,
    TypeScriptModule,
    TypeScriptClass,
    TypeScriptFunction,
    TypeScriptInterface,
)
```

### Rust (`uko-rs:`)

```python
from cleveragents.acms import (
    RUST_VOCABULARY,
    RUST_DETAIL_LEVELS,
    RustStruct,
    RustTrait,
    RustImpl,
    RustFunction,
    RustDeriveAttribute,
)
```

### Java (`uko-java:`)

```python
from cleveragents.acms import (
    JAVA_VOCABULARY,
    JAVA_DETAIL_LEVELS,
    JavaClass,
    JavaInterface,
    JavaMethod,
    JavaAnnotation,
    JavaCheckedException,
)
```

---

## Usage Example

```python
from cleveragents.acms import (
    VocabularyRegistry,
    get_oo_vocabulary,
    get_func_vocabulary,
    PYTHON_VOCABULARY,
    PYTHON_DETAIL_LEVELS,
    OO_DETAIL_LEVEL_MAP,
    resolve_detail_level,
)

# Build a registry with Layer 2 paradigm vocabularies
registry = VocabularyRegistry(
    vocabularies=(
        get_oo_vocabulary(),
        get_func_vocabulary(),
    )
)

# Resolve a detail level for a Python function
depth = resolve_detail_level(
    name="uko-py:function",
    maps=[PYTHON_DETAIL_LEVELS, OO_DETAIL_LEVEL_MAP],
)
print(f"Python function detail depth: {depth}")

# Look up a vocabulary by prefix
oo_vocab = registry.get_by_prefix("uko-oo:")
print(f"OO vocabulary has {len(oo_vocab.classes)} classes")
```

---

> **Note:** The ACMS module is internal to the context assembly pipeline.
> Direct use is only needed when implementing custom context strategies.
> For typical usage, configure context policies via `agents context` CLI
> commands — see the [Specification](../specification.md) for details.
