Metadata-Version: 2.5
Name: matrx-records
Version: 0.1.30
Summary: The records server: the eight agent verbs over the custom record store's doors, the merge-field resolver, and the record workflow nodes
Project-URL: Homepage, https://github.com/AI-Matrix-Engine/aidream-current
Project-URL: Repository, https://github.com/AI-Matrix-Engine/aidream-current
Author-email: Matrx <admin@aimatrx.com>
Maintainer-email: Matrx <admin@aimatrx.com>
License: MIT
Keywords: agents,custom-data,matrx,merge-field,records
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.13
Requires-Dist: matrx-files>=0.2.333
Requires-Dist: matrx-orm>=3.1.285
Requires-Dist: matrx-utils>=2.0.114
Requires-Dist: pydantic>=2.0.0
Provides-Extra: agent
Requires-Dist: matrx-ai>=0.5.687; extra == 'agent'
Requires-Dist: matrx-connect>=0.1.258; extra == 'agent'
Provides-Extra: graph
Requires-Dist: matrx-graph>=0.2.374; extra == 'graph'
Description-Content-Type: text/markdown

# matrx-records

The **records server**: the record read/write paths, the eight agent verbs and their
generated tool cache, the merge-field resolver and its provenance writer, and the record
workflow nodes.

It is imported by the app and never imports it. It talks to the database only through
`matrx-orm`, and only through the `custom.*` store's own doors, under the operating
person's own principal — there is no agent identity and there are no service roles.

```python
from matrx_records import Principal, RecordStore

store = RecordStore(Principal(user_id=uid, organization_id=org, claims=jwt_claims))
tables = await store.table_list()
```

What an organization has, for a model, in one call (XML; `fmt="json"` for JSON; `table=` for one table in full):

```python
from matrx_records.agent.schema import index_answer, schema_answer

answer = await schema_answer(principal, actor)            # {"schema": "<schema …>", "chars", "max_chars", "truncated"}
index = await index_answer(principal, actor)              # {"index": "<data_index …>", …}: names + row counts, capped
```

A link column that points at a built-in table reads `to="entity:<token>"` with `to_name` (the built-in table's own
word); the built-in table lists who links to it (`linked_from`, in the overview as `Table.Column`, in full with
`table=entity:<token>`); a whole answer says the value shape once (`[{"token", "id"}]`).

Host wiring is one call at startup:

```python
from matrx_records import configure_records
configure_records(database="supabase_automation_matrix", session_factory=my_act_as_user)
```

## Aggregates: the order and the derived measures (C1.2)

`RecordStore.record_aggregate` asks any of the store's twelve row measures (`STORE_MEASURES`; as of a moment,
`aggregate_as_of`, still five: `AS_OF_MEASURES`) and, with `derived=[...]`, the measures
`custom.record_aggregate` works out from others (`DERIVED_MEASURES`: ratio, running_total, active, goal —
one meaning across every engine; the body lives in `apps/shared/records/FEATURE.md` § Aggregate measures).
With no `order`, the door ranks by the measure (a count measure ranks by records); `order="count_desc"`
asks the count order by name. The agent's `record_aggregate` defaults to no order and takes `derived`
(not with `as_of`). Census: `common-docs/systems/data/custom-data/projects/data-for-every-client/discovery/C1-aggregate-census.md`.

## `records.write` — save by matching columns

`records.write` takes either a `record_id` or `match` ("The record where", `{column_key: value}`),
never both (`record_id_and_match`). With `match` it reads `record_query(match, limit=2)`:

- 0 rows: adds a record with `{**match, **values}` (`on_no_match="create"`, the default) or fails
  `no_match` (`on_no_match="fail"`);
- 1 row: writes `values` to it through the same asking door as every other agent write (approval
  setting, held-change pause, standing-rule path all unchanged);
- 2+ rows: fails `match_ambiguous`, naming the count and the first two ids; never picks one.

The output's `matched_by` is `record_id` | `match` | `created`. `expected_version` is only valid with
`record_id`. `match` values are plain scalars (an object would be read by the store as a date
window, so it is refused `match_value_not_plain`), and the store compares them as text, so the number
`1042` and the text `"1042"` find the same record. Known limit: two runs at the same moment that both
find nothing can both add one; an author who needs one per key wraps the step with
`data.one_at_a_time` keyed on the match values. No list form: `control.map` over the step.
Test: `aidream/graph_actions/tests/test_records_write_saves_by_matching_columns.py`.

## The scope system, read from the store (SCOPES-READS-SERVER)

Every server reader of scopes reads `matrx_records.store.scopes.ScopeReader` — never the old
`context.*` tables. A scope type is a Table the context system keeps, a scope a Record of it, a
context item a Field; the reader answers in the old column names:

```python
from matrx_records.store.scopes import ScopeReader

reader = ScopeReader.for_ambient(user_id=uid)          # the operating person, or the run's person
types = await reader.types(org_ids)                     # lists: the contract RPCs, one statement
scopes = await reader.scopes(org_ids, type_ids=[tid])
docs = await reader.scope_documents([org], type_ids=[tid])  # every Record WITH its values
one = await reader.scopes_by_id([sid])                  # by id, in whichever org it opens in
items = await reader.items(org, [tid])                  # Fields, with the old value_type word
```

Values kept as files are read whole with `ScopeReader.whole_value(scope, key)`.
The old scope tables are retired (2026-10-05); the store is the only writer, so there is nothing to compare against.

## The server half — routing an existing record path (CUT-N-13)

An `aidream` path that reads or writes records asks the gateway, and the gateway decides
**per caller**: the record store when `custom/system_enabled` resolves on for that
person's organization, the path's own existing body when it does not.

```python
from matrx_records.server import route_read

rows = await route_read(
    source="context.scopes",                       # the legacy relation
    match={"id": scope_id},
    legacy=lambda: Scopes.filter(id=scope_id).values("id", "name"),
)
```

`legacy` is the OFF arm, so today's behavior is unchanged while the knob is false and it
is impossible to route a path without naming what it used to do. **The ramp is per SOURCE:**
the switch says the organization keeps its data in the store, not that every relation has
moved, so a source with no Table of its own slug is *not adopted yet* and keeps reading and
writing today's tables — the `Route` says so, with the remedy. Only a source whose Table
exists resolves through the store (`RecordsGateway.route_for`; feedback f35b12ec). `attrs=True` when the
legacy arm hands back model instances; `RecordsGateway.read_joined(...)` for a path whose
legacy arm is a SQL `JOIN` across two record-bearing relations.

Which paths those are is a **query**, never a list:

```python
from matrx_records.server import the_enumeration

for path in await the_enumeration():
    print(path.relative_path, path.sources, path.routed)
```

It intersects matrx-orm's model registry with `platform.deprecated_relations` (the
platform's own supersession register) and then reads the repository's import graph.
The host's `tests/package_host_contracts/matrx_records/test_server_paths_against_the_store.py` is parametrized over it, so a path nobody
repointed fails by name and a legacy relation declared tomorrow pulls its paths in with
no code change.

## The outside door's verbs (TABLE-API-1, 2026-09-29)

The table API and the AI Matrx MCP (aidream `services/table_api`) reach the store only through
these, as the person: `table_read` (a Table's words, Fields and choice options), `record_page`
(`custom.read_records_page`: filter, search, sort, page, total), `record_headers_of` (version and
timestamps), `table_of`, `records_holding` (ids per key value, one statement), `record_change_many`
and `record_upsert` (one transaction; advisory lock on the key; a person's verb, or an agent's
only with `change_approval` saying nobody is asked) and `record_archive` (a person's archive /
restore; an agent uses `record_delete`, which asks first).


## What an agent reads of the template gallery (2026-11-02)

`tables_template` `list` cuts each card to `agent.table_doors.AGENT_CARD_KEYS` plus the footprint's one line
(`agent_card`); the screen reads the `templates` door itself and keeps the full card. One Company Setup read was
27,447 characters for 20 cards and was carried through every later turn. Guard:
`aidream/api/mcp/agent_service/tests/test_table_doors_tools.py::test_an_agent_reads_a_gallery_card_as_what_it_needs_to_choose_and_install`.

## An automation may name its fields by key or label (2026-11-02)

`tables_automation` `create` / `update` resolve, before `custom.automation_declare`, every field written by its exact
key or label to that field's id (`agent.table_doors._spec_with_field_ids`): the trigger's `field`, `{"field": …}`
references in the condition and copied values (the watched table), and an action's `values` keys and `where` (that
action's own `table_id`, else the watched table). An unknown word is sent as written, so the store still refuses it
in its own words. 21 of 38 setup-agent automation calls had been refused for this. Guard:
`aidream/api/mcp/agent_service/tests/test_table_doors_tools.py::test_an_automation_written_with_field_names_reaches_the_store_with_field_ids`.
The walk reaches every depth (2026-11-12): a step inside an `if` (`branches[].actions`, `else`) or a `for_each`
(`actions`) resolves exactly as a top-level one, by its own `table_id`. Guard:
`tests/test_an_automation_names_nested_fields_by_id.py`.

## One round trip per read, query and asked write (workflow lane B, 2026-11-12)

`record_read`, `record_read_many`, `record_query` (without `as_of`) and `record_propose` (with a
`table_id`, no big text) ask their doors in ONE statement as the principal
(`matrx_records.principal.together` over `matrx_orm.call_functions_together`): the same doors, the
same authority, one trip instead of a session around several. A refused statement, an `as_of` read, a
change that must wait, or a value big enough to need its file carried takes the door-by-door path,
which keeps every refusal and wait exactly as before. `records.read` steps of one run that run side by
side share ONE statement (`matrx_graph.actions.Coalescer`). The asked write is the question
(`custom.agent_change_approval`) and the write in one statement, the write gated on
`approval_required = false`, so the two cannot disagree.

**What "completed" means while a write is in flight:** a `records.write` step is a step like any
other, so its run's `run_completed` is sent only after every write step has landed (or the run fails
with the write's own refusal). The answer reaches the person earlier through the output step, which
waits only on its own inputs. There is no write that outlives its run's completion, so completion
never claims a write that has not landed. Tests: `tests/test_a_record_read_is_one_round_trip.py`,
`tests/test_an_asked_write_is_one_round_trip.py`.
