@geonosis/document 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,157 @@
1
1
  # @geonosis/document
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 115366f: `documentStore` is a composition over `@geonosis/db`'s doors — `defineLog` for the revisions,
8
+ `projectionOf` per entity for the documents table, `project`/`aggregate` for `heads` and
9
+ `aggregate` — and the domain spells no SQL (#411). Every contract holds: `hashOf` over the same
10
+ eleven facts, `succeed` at lineage+1 version 1, `at` the database clock, the walls on both legs.
11
+ `documentMigrations` renders through `projectionMigrations` and `logMigrations`: the log's
12
+ `version` and `compensation_of` columns are `bigint` (were `integer`); everything else reads the
13
+ same; `0003_document_revisions.sql` is the one file that changes. The surface table's clock cast is gone — `EntityRow`'s
14
+ clocks are numbers at the floor (#412).
15
+ - eac9ead: `Document.extend` gains `view?: StandardSchemaV1` — what a single-document read RENDERS, defaulting
16
+ to the entity's own `body`; `ViewOf<Entity>` reads it back, and `documentEntities` folds `views`
17
+ beside `bodies`/`cards`. `DocumentDefinition` and `DocumentEntity` gain the type parameter
18
+ `ViewSchema` (defaulting to the body schema) that carries it.
19
+
20
+ `documentSurface({ registry, store, schema })` (#403's T4+T5, folded into one) is new: the wire
21
+ contract as a TABLE, folded over the registry rather than authored by hand. Per entity: `get`,
22
+ `list` (the cursor/sort/filter shape off `EntityListing`, the page envelope with each item's
23
+ instance and card), `history`, `verify`, `commit`, `retire`, `reinstate`, `setStatus` (a `commit` of
24
+ `withStatus` guarded by `canTransition`). Across entities: `heads`, `aggregate`, `shared` (the link
25
+ door: `scope: 'token'`, `{ token }` in, `{ entity, view }` out as a union folded over the registry,
26
+ pending on `document.shared`; `LinkVerifierPort` declared beside the archive and timestamp ports).
27
+ The saga rows (`create`, `send`, `duplicate`, `runStarted`) are
28
+ declared with their own input/output and `call: { pending: 'T3', workflow }` — bound once
29
+ `src/workflows/` lands. `schema: { enum, object, union }` is the one place a consumer's validator
30
+ library (zod) enters; `@geonosis/document` itself stays library-free.
31
+
32
+ ### Patch Changes
33
+
34
+ - Updated dependencies [75dcf32]
35
+ - Updated dependencies [eb688df]
36
+ - Updated dependencies [8bc67fa]
37
+ - Updated dependencies [00ccfd5]
38
+ - Updated dependencies [c985c38]
39
+ - Updated dependencies [ae4a081]
40
+ - @geonosis/db@0.9.0
41
+
42
+ ## 0.2.0
43
+
44
+ ### Minor Changes
45
+
46
+ - 7f24da6: `aggregate` no longer hardcodes the physical column `"total"` in `sum("total")::text` — it reads it,
47
+ `heads`'s own `"status"`/`"issueDate"` predicates, and the bucket expression's column off ONE
48
+ `columnOf` map, the same one `heads`'s select list already used. `DocumentColumns` gains `total`, a
49
+ renamed `total` column now also carried through `documentMigrations`' DDL and its per-column
50
+ sortable index.
51
+ - 7f24da6: The core knows a validator CONTRACT, never a schema library (#383): `DocumentDefinition` and
52
+ `DocumentEntity`'s `body`, `draft`, `incoming` and `card.schema` type parameters are bound to
53
+ `StandardSchemaV1` (`@standard-schema/spec`, types only) instead of `zod.ZodTypeAny` — zod, valibot
54
+ or a hand-built `{ '~standard': { validate, vendor, version } }` object all satisfy it equally, and
55
+ `zod` leaves `peerDependencies` (it stays a `devDependency` for the tests). `DocumentHead` and
56
+ `DocumentRecord` are no longer `z.infer<...>` of a zod schema — both are plain object types, and
57
+ `Document.head`/`Document.record` are `StandardSchemaV1` validators DERIVED by the new
58
+ `validatorOf` from two exported declarative field specs, `Document.headFields` and
59
+ `Document.recordFields` (the `FieldKind` union is exported too) — the base still enforces its own
60
+ contract on `headOf`, but a consumer folds `headFields` into their own library instead of restating
61
+ the seven fields by hand. `card` is now `{ schema, of(document, { counterpartyName }) }` instead of
62
+ a bare function, so a consumer's wire card schema travels beside the function that builds it.
63
+
64
+ `documentEntities` folds over the map's values instead of building a union itself: `nameSchema`,
65
+ `bodySchema` and `bodyDecoder` are REMOVED — removed without an alias at 0.x by agreement with the
66
+ one consumer; three lines in their door replace them: `names` for `nameSchema` (build your own enum
67
+ over it), `fold((e) => e.body)` (or the new `bodies` array) for `bodySchema` (build your own union),
68
+ and your own `z.union(...).compile()`/equivalent over `bodies` for `bodyDecoder`. `fold(pick)` reads
69
+ a per-entity fact off every entity in one place, typed over the union of the map's values; `bodies`
70
+ and `cards` are the DISTINCT declared body/card schemas, both `StandardSchemaV1[]`. A layer that
71
+ owns a per-entity decision registers by extending the fold and checks its own coverage once, at its
72
+ composition root — never a `satisfies Record<Names, T>` map filled in per call site.
73
+ - 7f24da6: The write model is now one verb, `commit` — an append-only log the application role cannot
74
+ rewrite (a guarded `revoke update, delete` plus a `before update or delete` trigger), a projection
75
+ derived from it, `ref` as the address (D-065). New doors: `commit`, `retire`, `succeed`,
76
+ `reinstate`, `at`, `asOf`, `history`, `verify`, `rebuild`, `canonicalOf`/`hashOf`, `systemActor`/
77
+ `isSystemActor`, the `ArchivePort`/`TimestampPort` types, `documentStore({ archive })`. Removed:
78
+ `upsert` (replaced by `commit`) and `revisions` (replaced by `history`) — `documentMigrations` now
79
+ requires `appRole` whenever its log renders (the default).
80
+ - 7f24da6: `documentStore({ registry, seam, table?, schema?, columns? })` (T2/S1): one physical table for
81
+ every document entity in a registry, discriminated by a `constants` column (`entity` unless
82
+ `columns.entity` names another) so two entities on one table never see each other's rows under the
83
+ same `number`. Per entity, `defineEntity` from `@geonosis/db` with `onRetiredConflict: 'replace'`,
84
+ `columns.version` declared, `indexed`/`sortable`/`filterable` over the seven `Document.headFields`
85
+ columns, and `item` that runs a stored body through the entity's own `migrateBody` then its
86
+ `~standard.validate` — a stored body that fails its own schema after migration is a refusal naming
87
+ the entity and the number, never an item. Writes run the entity's own `prepare` then `stampBody`.
88
+ `documentMigrations({ table?, schema?, columns? })` renders that table's DDL over `@geonosis/db`'s
89
+ `entityMigrations`: `total` is `numeric` (a text column orders `'9.00' > '10.00'`, and `total` is a
90
+ sortable, filterable listing column), every other head column `text`, plus a listing index on
91
+ `(entity, issueDate)` no per-column sortable index gives the table. `AnyDocumentEntity` is
92
+ exported from `documentEntities`'s own module (the bound `documentStore` and `documentEntities`
93
+ share). `@geonosis/db` and `@geonosis/conformance` join `dependencies` (`workspace:^`) — the core
94
+ did not declare them because it did not import them.
95
+ - 7f24da6: `documentStore(...)`'s composed store (T2/S2) grows two doors beside its per-entity `Entity`s:
96
+ `heads({ columns, entity?, order, where? })` — a projection over the head columns plus `entity` and
97
+ `number`, `entity` a single kind or a set (RECENT's own read narrows `kind IN ($kinds)`), `order` an
98
+ array (HEADS FOR MATCHING orders by `kind, number`) — and `aggregate({ by?, entity?, entities?,
99
+ measures, where? })` — `where` OPTIONAL (a plain `count()` with no range is one row), `by: 'status' |
100
+ 'entity' | { bucket: 'day' | 'week' | 'month', of: 'issueDate' }`, `measures: ('count' |
101
+ 'sum:total')[]`, `count` as a number and `sum:total` as a DECIMAL STRING (`sum("total")::text`,
102
+ `'0'` for an empty group), ordered by the `by` key. Both are tenant-scoped by the seam and exclude
103
+ retired rows. Six consumer reads (STATUS BREAKDOWN, TIME SERIES, COUNT BY ENTITY, RECENT, COUNT per
104
+ org, HEADS FOR MATCHING) are each a case in `domains/document/src/store/postgres.test.ts`, over real
105
+ Postgres 17 and 18, with hand-computed decimal sums (`12.50 + 0.25 = 12.75`, no float crossing).
106
+ - 7f24da6: `layer-walls` holds a NEW plant beside the core's: the store may reach `@geonosis/db` and
107
+ `@geonosis/conformance`, never `@geonosis/workflows` directly (`src/walls.test.ts`,
108
+ `src/__fixtures__/walls/domains/document/src/store/store-reaches-the-engine.ts`).
109
+ `create-geonosis`'s document scaffold entry now composes `documentStore` inside the tenant session
110
+ (`definitions.session`) instead of handing back the bare, un-composed registry. README: a "Store"
111
+ section, and "what does not exist yet" shortened to what T2 has not shipped.
112
+ - 7f24da6: `documentStore`/`documentMigrations` gain `revisions` (on by default, `document_revisions`;
113
+ `false` to opt out), keyed by `(tenant, entity, number, version)`. A changed upsert's `after.upsert`
114
+ inserts the row it overwrote (the prior body and its prior `updated_at`, plus `replaced_at`); an
115
+ identical body writes none. `after.replace` deletes a dead document's revisions before the row that
116
+ takes its number is inserted (W72's "nothing inherited"), and the undo of a changed upsert deletes
117
+ the one row that write inserted rather than replaying a new one. `store.revisions({ entity, number
118
+ })` answers `{ version, body, updatedAt, replacedAt }[]` ordered by version, migrated and validated
119
+ through the entity's own schema exactly as `item()` reads a document — a stored revision failing
120
+ its schema is refused naming the entity, the number AND the version.
121
+
122
+ ### Patch Changes
123
+
124
+ - 7f24da6: `UpsertOutput.replaced` gains `changed: boolean` (#396) — the same comparison that already decided
125
+ the version bump, now exposed instead of leaving a caller to re-derive it. `replaced` itself is
126
+ present whenever a previous row existed, identical body or not, so without this a caller could not
127
+ tell a real change from a no-op re-upsert. `domains/document`'s store deletes its own duplicated
128
+ `bodyChanged`/`canonicalOf` and reads `answered.replaced?.changed` off the floor instead.
129
+ - 02c80d6: `appRoleStatements` takes `appendOnly?: string[]` (`@geonosis/db`) — table names excluded from its
130
+ blanket grant's UPDATE and DELETE, holding regardless of whether it runs before or after the
131
+ migration that creates them (#408, from during.day's own provisioning order: migrate as owner, then
132
+ create the role, which the shipped code left with only the trigger standing — SQLSTATE P0001, never
133
+ the grant's own 42501). `@geonosis/document` exports `appendOnlyTables()` (the log's own name) and
134
+ `documentRoleStatements(appRole)` for a consumer that provisions its role by hand, outside
135
+ `appRoleStatements`.
136
+ - 4c00092: `fieldPatterns` (`Record<'calendarDate' | 'decimal', RegExp>`) is exported from the core — the
137
+ exact patterns `validatorOf` checks those two `FieldKind`s against — so a consumer's own zod (or
138
+ other) fold names neither regex a second time (#409, from during.day's own fold restating both).
139
+ - b583b8e: The log's own `committed | retired | reinstated` column is `revision_kind`, configurable via
140
+ `columns.revisionKind` — never the hard-coded `kind`, which collided with a consumer whose entity
141
+ column (`columns.entity`) is itself named `kind` (#407, from during.day's swap against the 0.2.0
142
+ candidate). The shipped `document_revisions` migration and the store's own reads/writes move to the
143
+ new name.
144
+ - 7f24da6: `EntityRow` gains `version?: number`, present when the entity declares `columns.version` —
145
+ `selected()` names the column so `get`/`list`/`listAll` carry it, at no extra statement. The
146
+ document store's `item()` reads it off the row directly; `withRealVersion` and the `seam.scoped`
147
+ wrappers it forced around `get`/`list`/`listAll` are gone, so a listing spends one select on the
148
+ page rather than one per row.
149
+ - Updated dependencies [7f24da6]
150
+ - Updated dependencies [7f24da6]
151
+ - Updated dependencies [02c80d6]
152
+ - Updated dependencies [7f24da6]
153
+ - @geonosis/db@0.8.0
154
+
3
155
  ## 0.1.1
4
156
 
5
157
  ### Patch Changes
package/README.md CHANGED
@@ -10,40 +10,63 @@ pnpm add @geonosis/document
10
10
 
11
11
  ## `Document`
12
12
 
13
- `Document = { head, record, extend }`. `head` is the indexed facts every document has —
14
- `status`, `issueDate`, `dueDate`, `counterparty`, `externalRef`, `revision`, `total`, every one
15
- nullable. Two refusals the schema makes that a looser one would not:
13
+ The core knows a CONTRACT, never a schema library: `body`, `draft`, `incoming` and `card.schema`
14
+ are each bound to `StandardSchemaV1` alone (`@standard-schema/spec`, types only — zod, valibot or a
15
+ hand-built `{ '~standard': { validate, vendor, version } }` object all satisfy it equally). Document
16
+ shouldn't know anything about schema; we extend, we do it.
17
+
18
+ `Document = { headFields, head, recordFields, record, extend }`. `headFields` is the declarative
19
+ FIELD SPEC every document's indexed facts are named from — `{ status: 'text', issueDate:
20
+ 'calendarDate', dueDate: 'calendarDate', counterparty: 'text', externalRef: 'text', revision:
21
+ 'text', total: 'decimal' }`, every field nullable. `head` is a `StandardSchemaV1` DERIVED from
22
+ `headFields` by `validatorOf` (exported, one small checker per `FieldKind`) — the base enforcing
23
+ its own contract, never a second listing of the fields. A consumer's wire schema folds
24
+ `headFields` into its own library instead of naming the seven fields by hand, and `fieldPatterns`
25
+ (exported) is `validatorOf`'s own `calendarDate`/`decimal` regexes so that fold names neither
26
+ pattern twice (#409). Two refusals the derived validator makes that a looser one would not:
16
27
 
17
28
  - `issueDate` and `dueDate` are calendar strings, `YYYY-MM-DD` or `null` — a `headOf` that answers
18
- with prose is refused at the `Document.head` parse, not accepted and read wrong three files
29
+ with prose is refused at the `Document.head` validation, not accepted and read wrong three files
19
30
  later.
20
31
  - `total` is a decimal STRING or `null` — money never crosses this boundary as a float.
21
32
 
22
- `record` is `{ version, createdAt, updatedAt }` — what storage adds once a document is written.
33
+ `recordFields` is `{ version: 'positiveInt', createdAt: 'int', updatedAt: 'int' }` and `record` is
34
+ its derived validator — what storage adds once a document is written.
23
35
 
24
36
  `Document.extend(definition)` takes the shape an entity decides (`name`, `noun`, `basePath`,
25
37
  `body`, `draft`, `incoming`, `statuses`, `numbering`, `fromDraft`, `headOf`, `searchText`,
26
38
  `statusOf`, `withStatus`, `prepare`, `merge`, `onSent`, `copy`, `removable`, `card`, and optionally
27
39
  `bodyVersion`/`migrations` — see body versioning below) and returns it with `is()`, a type guard
28
- narrowing on the entity's own name. `InstanceOf`, `BodyOf`, `DraftOf`, `IncomingOf`, `StatusOf`,
29
- `CardOf` and `NameOf` read the pieces back off an entity, generically.
40
+ narrowing on the entity's own name. `card` is `{ schema, of(document, { counterpartyName }) }` — ONE
41
+ shape, what the list endpoint returns per row and what the UI's list reads; the floor carries the
42
+ card's schema and never looks inside it. `view` (optional) is what a single-document READ renders —
43
+ absent, `Document.extend` fills it with the entity's own `body` schema, so a consumer that never
44
+ needs a distinct render shape names nothing extra. `InstanceOf`, `BodyOf`, `DraftOf`, `IncomingOf`,
45
+ `StatusOf`, `CardOf`, `ViewOf` and `NameOf` read the pieces back off an entity, generically, through
46
+ `StandardSchemaV1.InferOutput`.
30
47
 
31
48
  ## `documentEntities`
32
49
 
50
+ Document shouldn't know anything about schema — we extend, we do it (#383). A per-entity fact
51
+ (`card`, `headOf`, …) is declared once, at the entity's OWN `Document.extend` call — never a second
52
+ map a layer fills in per entity later. Totality lives at that extension site: `Document.extend`'s
53
+ own parameter type refuses an entity that leaves a required fact undecided, so a consumer never
54
+ reaches for a `satisfies Record<Names, T>` map to catch it (the pattern this ruling retires).
55
+
33
56
  `documentEntities({ memo: Memo, receipt: Receipt, … })` takes a map of `Document.extend` results,
34
57
  keyed by name, and:
35
58
 
36
59
  - refuses a map whose key does not match the definition's own `name` — a mismatch here is a row
37
60
  whose `entity` column nothing can find again;
38
- - derives `names` off the map's OWN keys — never a hand-written union, so a consumer's own
39
- `satisfies Record<Names, T>` map fails to compile the moment a new entity joins this one and that
40
- consumer has not decided for it (the totality guarantee `keyof typeof entities` gave the
41
- reference this floor was extracted from, and the reason the return type carries `names` rather
42
- than a caller reading `Object.keys` and hoping);
43
- - derives `nameSchema` (`z.enum`) and `bodySchema` (`z.union` over the DISTINCT declared body
44
- schemas — two entities sharing a shape contribute it once) — both read off the map, never
45
- restated;
46
- - `bodyDecoder` is `bodySchema` run through `z.compile` once, for a store that parses every row;
61
+ - derives `names` off the map's OWN keys — never a hand-written union;
62
+ - `fold(pick)` reads a per-entity fact off EVERY entity the map holds, in one place, typed over the
63
+ union of the map's values (`registry.fold((e) => e.card.schema)`) — a layer that owns a
64
+ cross-entity concern (a union type, a compiled decoder, a per-entity effect) registers by
65
+ extending the fold and checks its own coverage once, at ITS composition root; that layer, never
66
+ this one, is where `z.union`/`z.compile`/`z.enum` now live;
67
+ - `bodies`, `cards` and `views` are the DISTINCT declared body/card/view schemas (`StandardSchemaV1[]`,
68
+ deduplicated by identity) — the layer that needs a union or a compiled decoder builds it with its
69
+ OWN library;
47
70
  - `instance(name, parts)` stamps a document with the entity name it was minted for; `named(name)`
48
71
  hands back one entity's own definition.
49
72
 
@@ -67,18 +90,152 @@ nothing.
67
90
  `documentIdentifiers(name)` derives every spelling a surface needs from one hyphenated entity name:
68
91
  `camel`, `pascal`, `pluralCamel`, `snake`, `snakePlural`, `path`.
69
92
 
93
+ ## Store
94
+
95
+ `documentStore({ registry, seam, table?, schema?, columns?, revisions?, archive? })` is ONE table
96
+ for every document entity the registry holds — never one table per entity — plus the append-only
97
+ log beside it, and it spells no SQL: the log is `@geonosis/db`'s `defineLog` keyed by `(entity,
98
+ ref, lineage)` with `revision_kind` as its extra column and `hashOf` as its `hash`; each entity's
99
+ projection is `projectionOf` over the documents table, keyed `{ column: 'number', param: 'ref' }`
100
+ (`ref` per D-065 is the parameter, `number` the head field and column), discriminated by
101
+ `constants: { [columns.entity ?? 'entity']: name }`, carrying `lineage` beside its row;
102
+ `get`/`list`/`listAll` are the projection's own; `heads` and `aggregate` are `project` and
103
+ `aggregate` on one further `defineEntity` over the same table with no constant, whose `filterable`
104
+ columns are the seven head columns, the entity column and `created_at`. Every write is `lockLatest`
105
+ → `append` → `write` in one transaction; `at`, `asOf`, `history`, `verify` are the log's own doors
106
+ on the current lineage; `rebuild` folds `latestPerStream` to the highest lineage per `(entity, ref)`
107
+ and writes it back.
108
+
109
+ `documentMigrations({ table?, schema?, columns?, revisions?, appRole })` is `projectionMigrations`
110
+ (the seven head columns typed off `FieldKind`, `lineage` carried, `hash`, the version column as the
111
+ sequence) plus the `(entity, issueDate)` listing index, then `logMigrations` for the revisions
112
+ table unless `revisions: false` — the same walls the floor renders for any log, with `revision_kind`
113
+ constrained to `committed | retired | reinstated`. `appRole` is required whenever the log renders
114
+ (the default): the name a consumer's application connects as, the same law as `@geonosis/db`'s own
115
+ `appRoleStatements`. The log's own kind column is `columns.revisionKind`, `'revision_kind'` when
116
+ unnamed — never `'kind'`, which is what these docs use for `columns.entity` (#407).
117
+
118
+ ## Writes
119
+
120
+ There is ONE write verb, `commit`. `store.<entity>.commit({ ref, body, actor, reason? })` appends
121
+ an immutable revision and updates the projection, in one transaction: it locks the lineage's latest
122
+ row, computes `version + 1`, and answers `{ committed: true, version, hash, previous: { version,
123
+ hash } | null }`. An identical body (canonical) writes nothing and answers `{ committed: false,
124
+ version }` instead — the current version, never a new one. `actor` is REQUIRED on every write — a
125
+ principal's id, or `systemActor(name)` (exported, `core/actor`) for an unattended one
126
+ (`systemActor('recurring.generate')`); `isSystemActor(actor)` reads it back. `reason` is optional
127
+ prose.
128
+
129
+ A revision carries `tenant, entity, ref, lineage, version, kind, body, actor, reason, at, prevHash,
130
+ hash` (`kind`: `'committed' | 'retired' | 'reinstated'`) plus `compensationOf` (nullable — the
131
+ version an undo compensates). `at` is the DATABASE clock, never the application's. Every revision's
132
+ `hash` is `hashOf` (`core/hash`, exported) over the canonical form of everything but
133
+ `compensationOf` — `prevHash` is null only at version 1 of a lineage, so the chain is tamper-evident
134
+ from the first write; a consumer's own archive recomputes the SAME `hashOf`/`canonicalOf`, the one
135
+ canonicaliser both sides use.
136
+
137
+ `store.<entity>.retire({ ref, actor, reason? })` is a commit of kind `retired` — the body is the
138
+ last one, unchanged; the projection's `retired_at` is set; a retired document refuses `commit`.
139
+ `store.<entity>.succeed({ ref, body, actor, reason? })` is the only door back from retired: it opens
140
+ a NEW LINEAGE at version 1 — the old lineage's rows are untouched, its own `history` still reads.
141
+ `store.<entity>.reinstate({ ref, actor, reason? })` un-retires the SAME lineage (kind `reinstated`)
142
+ — never a new one.
143
+
144
+ The log the application role CANNOT rewrite has two walls, and both must stand for the write to be
145
+ refused at the PRIVILEGE (SQLSTATE 42501) rather than only at the trigger (P0001): a
146
+ `before update or delete` trigger that raises regardless of privilege — the owner is walled by this
147
+ alone, and `documentMigrations` renders it plus a guarded `revoke update, delete` that is a no-op
148
+ until the named role exists — and the grant itself, which is `@geonosis/db`'s
149
+ `appRoleStatements`'s to get right: its blanket `grant … on all tables` re-broadens whatever the
150
+ guarded revoke stripped, in EITHER provisioning order, unless it is told to exclude this table.
151
+ Call it with `appendOnly: appendOnlyTables()` (this domain's own export, naming its log) — this
152
+ holds regardless of whether migrations or the role come first (#408). A consumer that provisions
153
+ its role by hand, outside `appRoleStatements`, calls this domain's own `documentRoleStatements(
154
+ appRole)` instead, AFTER the role exists.
155
+
156
+ `undos` (D-063 clause 2) APPEND, never remove: the undo of a `commit` is a new revision restoring
157
+ the prior body; the undo of a FIRST commit (a create, no prior body to restore) is a `retired`
158
+ revision instead; the undo of a `retire` is a `reinstated` revision on the same lineage. Every
159
+ compensating revision carries `compensationOf`, naming the version it undoes — the archive shows
160
+ the rollback structurally, never in prose.
161
+
162
+ `documentStore({ archive })` (optional, `ArchivePort` from `core/ports`) copies a commit's revision
163
+ to `<tenant>/<entity>/<lineage>/<version>.json` AFTER its own transaction has committed — never
164
+ inside it, so an archive that is down never rolls a durable write back; the answer carries
165
+ `archived: false` instead, and a later ticket's workflow is what retries it. `TimestampPort` (a
166
+ trusted third party's timestamp over a hash) is declared beside it, not implemented by anything
167
+ here.
168
+
169
+ ## Reads
170
+
171
+ `store.<entity>.get({ ref })` is the projection's live head — migrated, validated, excludes a
172
+ retired document, as before. `store.<entity>.at({ ref, version })` and
173
+ `.asOf({ ref, at })` read the CURRENT lineage's own history: an exact version, or the latest
174
+ revision at or before an instant. `store.<entity>.history({ ref, lineage? })` answers `{ version,
175
+ kind, actor, reason, at, hash, body }[]` by version — `lineage` defaults to the current one, but an
176
+ explicit one (the value `succeed` left behind) still reads in full. `store.<entity>.verify({ ref,
177
+ lineage? })` recomputes every hash of a lineage from version 1 and answers `{ ok: true, versions }`
178
+ or `{ ok: false, brokenAt, expected, found }` — a fact no privilege can hide, since the log's own
179
+ bytes are what it reads.
180
+
181
+ `store.rebuild({ entity? })` (tenant-scoped) rewrites the projection from the log's own latest
182
+ version of its latest lineage, per `(entity, ref)`, and answers how many rows it wrote — a
183
+ consumer's repair tool, and the exam's own way of proving the projection is truly DERIVED.
184
+
185
+ `store.heads({ columns, entity?, order, where? })` is a PROJECTION, never an aggregate: the head
186
+ columns plus `entity` and `number`, `entity` one kind or a set, `order` every column a page is
187
+ ordered by (the tie-break included). `store.aggregate({ by?, entity?, entities?, measures, where? })`
188
+ answers `count` and `sum:total` — `where` OPTIONAL (a plain count with no range is one row) —
189
+ grouped by `'status' | 'entity' | { bucket: 'day' | 'week' | 'month', of: 'issueDate' }`. `count` is
190
+ a number; `sum:total` is a DECIMAL STRING (`sum("total")::text`, `'0'` for an empty group) — money
191
+ never crosses this door as a float either. Both are tenant-scoped by the seam and exclude retired
192
+ rows.
193
+
194
+ ## Surfaces
195
+
196
+ `documentSurface({ registry, store, schema })` (#403's T4+T5, folded into one) is the wire
197
+ CONTRACT — never a second file naming a domain's shapes twice. It returns a TABLE, an array of
198
+ rows (`{ name, verb: 'query' | 'mutation', path, scope: 'org' | 'public' | 'token', input, output,
199
+ call }`), derived by FOLDING over the registry, never a map a caller fills: per entity `get`,
200
+ `list` (input the cursor/sort/filter shape `EntityListing` already answers, output the page
201
+ envelope with each item's own instance AND card), `history`, `verify`, `commit`, `retire`,
202
+ `reinstate`, `setStatus` (a `commit` of `withStatus(body)` guarded by `canTransition` — refuses a
203
+ transition the entity's own status machine never declared, before it writes); across entities,
204
+ `heads`, `aggregate` and `shared`. `shared` is the link door: `scope: 'token'`, input `{ token }`,
205
+ output the union over every entity of `{ entity, view }` folded off the registry, the tenant read
206
+ from the token by `LinkVerifierPort` and never from the handle; it is declared pending on the
207
+ `document.shared` workflow like the saga rows. The saga rows an entity gets for free — `create`
208
+ (with numbering), `send`, `duplicate`, `runStarted` — are DECLARED with their own input/output and
209
+ `call: { pending: 'T3', workflow }` in place of a function: an adapter mounting the table refuses
210
+ those BY NAME (`typeof row.call !== 'function'`), never with a stub answer.
211
+
212
+ The table is the contract; an adapter (tRPC, REST, MCP) is thin — it reads a row's `name`, `verb`,
213
+ `path` and `scope` for its own wiring, hands `input`/`output` to whatever transport-level
214
+ validation it already does, and calls `call(handle, params)` with a handle already open for the
215
+ right tenant. `documentSurface` never touches a validator library itself: `schema: { enum, object,
216
+ union }` is a three-builder adapter the CALLER hands in, so `setStatus`'s enum (built from the
217
+ entity's own `statuses`) and `shared`'s union (folded from the registry's views) come back as REAL
218
+ schemas of whatever library the caller's `object`/`union`/`enum` wrap them in — zod is the one
219
+ place it enters a repo composing this domain, never a dependency of `@geonosis/document` itself
220
+ (`src/no-schema-library-at-runtime.test.ts` holds the built door to that).
221
+
70
222
  ## What does not exist yet
71
223
 
72
- This ticket ships `src/core/` only. `src/store/` (one table, its revisions, the entity-floor
73
- composition), `src/workflows/` (the org's engine, the only internal folder that may import it),
74
- `src/contract/` (the wire schemas), `src/surface/` (the procedure/route/tool mounts), `src/ui/`
75
- (the view axis) and `src/conformance/` (the exam a consumer runs against their own provider) are
76
- later tickets — the internal layout is declared now (and held by `layer-walls`) so each lands
77
- inside the wall already drawn for it.
224
+ `src/store/` ships the commits (`commit`, `retire`, `succeed`, `reinstate`, `get`, `at`, `asOf`,
225
+ `history`, `verify`, `rebuild`, `heads`, `aggregate`) and the archive/timestamp ports declared, not
226
+ mirrored; it ships no search projection yet. `upsert` and `revisions` are GONE (replaced by
227
+ `commit`; `history`). `src/surface/` ships the table above; its saga rows stay PENDING until
228
+ `src/workflows/` (the org's engine, the only internal folder that may import it — the archive
229
+ mirror lands there too) lands and binds them. `src/contract/` (a layer the surface table already
230
+ supersedes — #403), `src/ui/` (the view axis) and `src/conformance/` (the exam a consumer runs
231
+ against their own provider) are later tickets — the internal layout is declared now (and held by
232
+ `layer-walls`) so each lands inside the wall already drawn for it.
78
233
 
79
234
  ## One door, and what holds it
80
235
 
81
236
  `sideEffects: false`; inside the package the in-package wall is `layer-walls`, planted in
82
237
  `src/__fixtures__/walls/` and proved through the real binary in `src/walls.test.ts` — the core may
83
- reach `@geonosis/conformance` and nothing else; only `src/workflows/` may reach `@geonosis/workflows`
238
+ reach `@geonosis/conformance` and nothing else, the store may reach `@geonosis/db` and
239
+ `@geonosis/conformance` and nothing else, `src/surface/` may reach the core, the store and the
240
+ workflows layer and nothing lower, and only `src/workflows/` may reach `@geonosis/workflows`
84
241
  directly (D-052 — the org's engine is a direct dependency of this domain).