graphddb 0.7.9 → 0.8.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.
Files changed (45) hide show
  1. package/README.md +6 -6
  2. package/dist/cdc/index.d.ts +389 -4
  3. package/dist/cdc/index.js +4 -3
  4. package/dist/{chunk-ZPNRLOKA.js → chunk-GS4C5VGO.js} +4 -6
  5. package/dist/chunk-HNY2EJPV.js +1184 -0
  6. package/dist/{chunk-NYM7K2ST.js → chunk-I4LEJ4TF.js} +3812 -6724
  7. package/dist/{chunk-PFFPLD4B.js → chunk-L2NEDS7U.js} +725 -2112
  8. package/dist/chunk-L4QRCHRQ.js +278 -0
  9. package/dist/chunk-LGHSZIEE.js +187 -0
  10. package/dist/chunk-N4NWYNGZ.js +1987 -0
  11. package/dist/{chunk-PDUVTYC5.js → chunk-XTWXMOHD.js} +0 -1
  12. package/dist/cli.js +63 -252
  13. package/dist/index.d.ts +23 -1548
  14. package/dist/index.js +100 -1778
  15. package/dist/internal/index.d.ts +84 -0
  16. package/dist/internal/index.js +701 -0
  17. package/dist/{maintenance-view-adapter-BATUh_I8.d.ts → key-DR7_lpyk.d.ts} +538 -2975
  18. package/dist/linter/index.d.ts +39 -6
  19. package/dist/linter/index.js +22 -4
  20. package/dist/{registry-CXhP4TaE.d.ts → linter-C-vypgut.d.ts} +22 -22
  21. package/dist/prepared-artifact-BpPgkXEo.d.ts +281 -0
  22. package/dist/spec/index.d.ts +506 -4
  23. package/dist/spec/index.js +36 -17
  24. package/dist/testing/index.d.ts +2 -2
  25. package/dist/testing/index.js +4 -3
  26. package/dist/transform/index.d.ts +460 -1
  27. package/dist/transform/index.js +2085 -2
  28. package/dist/types-2PMXEn5x.d.ts +1205 -0
  29. package/dist/types-BXLzIcQD.d.ts +450 -0
  30. package/docs/cdc-projection.md +5 -5
  31. package/docs/class-hydration.md +1 -1
  32. package/docs/cqrs-contract.md +28 -20
  33. package/docs/design-patterns.md +5 -5
  34. package/docs/docs-generation.md +6 -6
  35. package/docs/middleware.md +15 -15
  36. package/docs/mutation-command-derivation.md +52 -42
  37. package/docs/prepared-statements.md +14 -14
  38. package/docs/python-bridge.md +113 -66
  39. package/docs/spec.md +153 -124
  40. package/docs/testing.md +9 -8
  41. package/package.json +20 -5
  42. package/dist/chunk-MMVHOUM4.js +0 -24
  43. package/dist/from-change-DanwjE5b.d.ts +0 -327
  44. package/dist/index-CtPJSMrc.d.ts +0 -934
  45. package/dist/relation-depth-Dg3yhl7S.d.ts +0 -36
@@ -0,0 +1,1205 @@
1
+ /**
2
+ * Parameter placeholders for the parameterized query / command definition DSL
3
+ * (issue #41, Python-bridge Phase 0a).
4
+ *
5
+ * A `Param<T>` is a **branded placeholder** standing in for a value that is not
6
+ * known at definition time but is supplied later (at execution, e.g. from
7
+ * Python). It carries:
8
+ *
9
+ * - the **TypeScript value type** `T` it represents (`string`, `number`, or a
10
+ * string-literal union), preserved through the IR and the inferred return
11
+ * types of the contract layer (`publishQuery` / `publishCommand`); and
12
+ * - a **runtime descriptor** (`kind` + optional `literals`) that the static
13
+ * planner (#42) and the code generator read to emit `operations.json`.
14
+ *
15
+ * Placeholders are created with `param.string()`, `param.number()`, and
16
+ * `param.literal(...)`. They are *only* legal at value positions inside a
17
+ * parameterized key / changes structure passed to the `define*` entry points —
18
+ * never to the live `Model.query` / `Model.putItem` runtime API, whose types remain
19
+ * uncontaminated by params.
20
+ */
21
+ /** Brand tag preventing a plain object from structurally matching a {@link Param}. */
22
+ declare const PARAM_BRAND: unique symbol;
23
+ /** Runtime discriminant for a parameter placeholder. */
24
+ type ParamKind = 'string' | 'number' | 'literal' | 'array';
25
+ /**
26
+ * A branded parameter placeholder representing a value of TypeScript type `T`
27
+ * that is bound at execution time rather than definition time.
28
+ *
29
+ * The brand (`[PARAM_BRAND]: T`) keeps `Param<string>` and `Param<number>`
30
+ * distinct and prevents a bare value from being mistaken for a placeholder.
31
+ *
32
+ * @typeParam T - The value type this placeholder stands in for.
33
+ */
34
+ interface Param<out T> {
35
+ /** @internal Type brand carrying the represented value type. */
36
+ readonly [PARAM_BRAND]: T;
37
+ /** Runtime discriminant: `'string'` | `'number'` | `'literal'` | `'array'`. */
38
+ readonly kind: ParamKind;
39
+ /**
40
+ * For `param.literal(...)`, the allowed literal values (preserved at runtime
41
+ * for the generator). `undefined` for `string` / `number`.
42
+ */
43
+ readonly literals?: readonly T[];
44
+ /**
45
+ * For `param.array({...})`, the descriptor of each element's fields. Lets the
46
+ * transaction planner (#46) type `forEach` element references and emit the
47
+ * `{item.<field>}` templates. `undefined` for scalar params.
48
+ */
49
+ readonly element?: Readonly<Record<string, Param<unknown>>>;
50
+ /**
51
+ * Optional human-readable description of the parameter (issue #154), supplied
52
+ * via `param.string({ description })` etc. Pure documentation metadata — it does
53
+ * NOT affect the runtime descriptor (`kind` / `literals`) the planner reads for
54
+ * execution. When present it is propagated to the param's {@link
55
+ * import('./ir.js').ParamDescriptor} and then to the serialized
56
+ * {@link import('../spec/types.js').ParamSpec} in `operations.json`. Absent →
57
+ * unchanged output (backward compatible).
58
+ */
59
+ readonly description?: string;
60
+ }
61
+ /** A `Param` whose represented value type is `string`. */
62
+ type StringParam = Param<string>;
63
+ /** A `Param` whose represented value type is `number`. */
64
+ type NumberParam = Param<number>;
65
+ /** A `Param` whose represented value type is the literal union `L`. */
66
+ type LiteralParam<L extends string | number> = Param<L>;
67
+ /** The element-field descriptor shape accepted by {@link param.array}. */
68
+ type ArrayElementShape = Record<string, Param<unknown>>;
69
+ /**
70
+ * The TypeScript element type implied by an {@link ArrayElementShape} `E`: each
71
+ * field carries the value type its placeholder represents.
72
+ */
73
+ type ElementOf<E extends ArrayElementShape> = {
74
+ [K in keyof E]: E[K] extends Param<infer V> ? V : never;
75
+ };
76
+ /** A `Param` standing in for an **array** whose elements have shape `E`. The
77
+ * `kind` is narrowed to the `'array'` literal so type-level dispatch on array
78
+ * params works (`ParamProxy`'s array arm matches — pre-#263 the wide
79
+ * `ParamKind` made `p.<arrayParam>` type as a scalar ref and `ElementProxy`
80
+ * collapse to `never`; runtime behavior was always correct). */
81
+ type ArrayParam<E extends ArrayElementShape> = Param<ElementOf<E>[]> & {
82
+ readonly kind: 'array';
83
+ readonly element: E;
84
+ };
85
+ /** Allowed scalar value types a placeholder may stand in for. */
86
+ type ParamValue = string | number;
87
+ /**
88
+ * Options accepted by the placeholder factories (issue #154). Currently carries
89
+ * only the optional human-readable {@link Param.description} — pure documentation
90
+ * metadata that does not affect the runtime descriptor. The object form is
91
+ * additive: `param.string()` (no options) is unchanged.
92
+ */
93
+ interface ParamOptions {
94
+ /** Optional human-readable description, propagated to `operations.json`. */
95
+ readonly description?: string;
96
+ }
97
+ /**
98
+ * Placeholder factory. Each call returns a branded {@link Param} carrying both
99
+ * the TypeScript value type and a runtime descriptor. Each scalar factory accepts
100
+ * an optional {@link ParamOptions} (issue #154) carrying a `description` — pure
101
+ * documentation propagated to `operations.json`; the no-argument call is unchanged.
102
+ */
103
+ declare const param: {
104
+ /** A placeholder for a `string` value. */
105
+ readonly string: (options?: ParamOptions) => StringParam;
106
+ /** A placeholder for a `number` value. */
107
+ readonly number: (options?: ParamOptions) => NumberParam;
108
+ /**
109
+ * A placeholder constrained to one of the given literal values. The value
110
+ * type of the resulting {@link Param} is the **union of the literals**, so it
111
+ * is preserved precisely in the IR and the inferred definition types. A final
112
+ * plain-object argument is read as {@link ParamOptions} (a `description`),
113
+ * distinguished from the `string` / `number` literal values.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * param.literal('active', 'disabled'); // Param<'active' | 'disabled'>
118
+ * param.literal('active', 'disabled', { description: 'Account state.' });
119
+ * ```
120
+ */
121
+ readonly literal: <const L extends readonly [ParamValue, ...ParamValue[]]>(...valuesAndOptions: [...L] | [...L, ParamOptions]) => LiteralParam<L[number]>;
122
+ /**
123
+ * A placeholder for an **array** parameter whose elements have the given field
124
+ * shape. Used by `defineTransaction`'s `tx.forEach(p.<arrayParam>, …)` to bind
125
+ * each element's fields to `{item.<field>}` templates.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * param.array({ userId: param.string(), role: param.string() });
130
+ * // Param<{ userId: string; role: string }[]>
131
+ * ```
132
+ */
133
+ readonly array: <const E extends ArrayElementShape>(element: E, options?: ParamOptions) => ArrayParam<E>;
134
+ };
135
+
136
+ /**
137
+ * Serializable static operation specs and manifest (issue #42, Python-bridge
138
+ * Phase 0b).
139
+ *
140
+ * Everything in this module is **JSON-serializable** by construction (only
141
+ * strings / numbers / booleans / arrays / plain objects — no functions, classes,
142
+ * `Date`, `Set`, or `undefined`-valued fields are emitted). These types mirror
143
+ * the `graphddb_manifest.json` / `graphddb_operations.json` shapes sketched in
144
+ * `docs/python-bridge.md`. The generator (#43) writes them to disk; the
145
+ * Python runtime (#44+) interprets them.
146
+ *
147
+ * ## Templates and placeholders
148
+ *
149
+ * Key-condition / range / item / change *values* are **template strings** with
150
+ * two placeholder forms:
151
+ *
152
+ * - `{paramName}` — bound from the caller-supplied params at execution time.
153
+ * - `{result.sourceField}` — bound from a field of the **prior** operation's
154
+ * result item(s), used to chain relation operations.
155
+ *
156
+ * A value with no `{...}` is a literal (e.g. a fixed sort-key discriminator
157
+ * `PROFILE`).
158
+ */
159
+
160
+ /**
161
+ * The schema version emitted in every manifest / operations document.
162
+ *
163
+ * `1.1` (issue #208, B案): the operation IR gained the **list fan-out binding
164
+ * form** ({@link SourceListSpec} on a `BatchGetItem` relation op), lifting the
165
+ * #197 `refs` loud-reject. The op vocabulary (the physical DynamoDB API surface)
166
+ * is unchanged — only the dataflow (source→key) binding grammar grew. Purely
167
+ * additive: every `1.0` document is a valid `1.1` document, and a document that
168
+ * uses no `refs` relation serializes byte-identically apart from this version.
169
+ */
170
+ declare const SPEC_VERSION: "1.1";
171
+ /**
172
+ * The schema version stamped on an operations document that **actually
173
+ * contains** an SCP Expression IR node (issue #261, Phase 3 S1): a
174
+ * `{ kind: 'scpExpr' }` write condition or a `guard` (transaction item /
175
+ * contract command method). The vocabulary is purely **additive** — every
176
+ * `1.1` document is a valid `1.2` document — and the stamp is **conditional**:
177
+ * a bundle with no SCP node keeps `1.1` and serializes byte-identically to the
178
+ * pre-#261 output. Runtimes that do not yet EVALUATE the expression vocabulary
179
+ * keep `SPEC_VERSION_SUPPORTED` at `1.1`, so an expression-bearing document is
180
+ * loud-rejected (fail-closed) everywhere until the evaluation sub-issues
181
+ * (#265/#266/#267) land and bump the supported constant with the wiring.
182
+ */
183
+ declare const SPEC_VERSION_SCP: "1.2";
184
+ /**
185
+ * The HIGHEST spec-IR minor this **TS runtime** understands and will EXECUTE
186
+ * (issue #265, Phase 3 S5). The shared `validateEnvelope` fail-closed rule is
187
+ * "major must match, minor must be ≤ supported" (envelope.ts): a bundle stamped
188
+ * at or below this version loads; a newer minor (or a bad major) is loud-rejected.
189
+ *
190
+ * S1 kept this at `1.1` so an expression-bearing `1.2` bundle was rejected
191
+ * everywhere (fail-closed) until evaluation landed. S5 wires the TS guard
192
+ * evaluator to `behavior-contracts` and moves it to `1.2`, so a guard-bearing
193
+ * `1.2` bundle is now ACCEPTED and EVALUATED on TS. A `1.2` bundle carrying an
194
+ * unknown `exprVersion` / operator still fail-closes (the expr evaluator rejects
195
+ * it). The py/rust/go runtimes bump in S6, PHP in S7 — the whole release column
196
+ * moves to `1.2` together.
197
+ */
198
+ declare const SPEC_VERSION_SUPPORTED: "1.2";
199
+ /** A spec version an operations document may carry (see {@link SPEC_VERSION_SCP}). */
200
+ type SpecVersion = typeof SPEC_VERSION | typeof SPEC_VERSION_SCP;
201
+ /** Field type as carried in the manifest (derived from the DynamoDB type). */
202
+ type ManifestFieldType = 'string' | 'number' | 'boolean' | 'binary' | 'stringSet' | 'numberSet' | 'list' | 'map';
203
+ interface ManifestField {
204
+ readonly type: ManifestFieldType;
205
+ /**
206
+ * Semantic format for `string` fields that carry a serialized temporal value.
207
+ * `datetime` → ISO 8601 instant, `date` → `YYYY-MM-DD`. Absent for plain
208
+ * fields. The Python runtime uses this to restore `datetime` on hydration,
209
+ * mirroring the TS hydrator's `format`-driven `Date` reconstruction.
210
+ */
211
+ readonly format?: 'datetime' | 'date';
212
+ /**
213
+ * Optional human-readable description of the field (issue #154), from a field
214
+ * decorator option (`@string({ description })`). Pure documentation — absent
215
+ * unless declared, so a field with no description serializes byte-identically
216
+ * to the pre-#154 manifest. Surfaces as a field comment in the generated Python.
217
+ */
218
+ readonly description?: string;
219
+ }
220
+ /** A key (PK or GSI) template descriptor in the manifest. */
221
+ interface ManifestKey {
222
+ /** Input field names the key is composed from (in declaration order). */
223
+ readonly inputFields: readonly string[];
224
+ /** Template for the partition-key value, e.g. `EMAIL#{email}`. */
225
+ readonly pkTemplate: string;
226
+ /** Template for the sort-key value, or `null` when the key has no sort key. */
227
+ readonly skTemplate: string | null;
228
+ }
229
+ interface ManifestGsi extends ManifestKey {
230
+ readonly indexName: string;
231
+ readonly unique: boolean;
232
+ /**
233
+ * Optional human-readable description of the index (issue #166, follow-up of #154),
234
+ * from `gsi(name, key, { description })`. Pure documentation — absent unless declared,
235
+ * so a GSI with no description serializes byte-identically to the pre-#166 manifest.
236
+ * The Python codegen surfaces it as the docstring of a generated query method that
237
+ * reads through this index.
238
+ */
239
+ readonly description?: string;
240
+ }
241
+ interface ManifestRelation {
242
+ readonly type: 'hasMany' | 'hasOne' | 'belongsTo' | 'refs';
243
+ /** Target entity (model class) name. */
244
+ readonly target: string;
245
+ /** target field → source field (on this entity). */
246
+ readonly keyBinding: Readonly<Record<string, string>>;
247
+ /**
248
+ * List-valued source descriptor for a `refs` relation (issue #197). Present IFF
249
+ * `type === 'refs'`: `from` is the parent LIST attribute holding the inline
250
+ * reference elements (e.g. `'tagRefs'`), `key` the field read off each element
251
+ * (e.g. `'tagId'`). Absent for every scalar-keyed relation (byte-identical to
252
+ * the pre-#197 manifest). Carried so a manifest consumer can reconstruct where a
253
+ * `refs` relation's BatchGet keys come from.
254
+ */
255
+ readonly refs?: Readonly<{
256
+ from: string;
257
+ key: string;
258
+ }>;
259
+ /**
260
+ * Optional human-readable description of the relation (issue #166, follow-up of
261
+ * #154), from `@hasMany/@belongsTo/@hasOne(..., { description })`. Pure documentation
262
+ * — absent unless declared, so a relation with no description serializes
263
+ * byte-identically to the pre-#166 manifest. The Python codegen surfaces it as a
264
+ * trailing `# …` comment on the relation's field in the generated result type.
265
+ */
266
+ readonly description?: string;
267
+ }
268
+ interface ManifestEntity {
269
+ /** Declared (logical) table name. */
270
+ readonly table: string;
271
+ /** Physical table name (after `TableMapping` resolution). */
272
+ readonly physicalName: string;
273
+ /** PK prefix, e.g. `USER#`. */
274
+ readonly prefix: string;
275
+ readonly fields: Readonly<Record<string, ManifestField>>;
276
+ /** Primary key, or `null` when the entity has none. */
277
+ readonly key: ManifestKey | null;
278
+ readonly gsis: readonly ManifestGsi[];
279
+ readonly relations: Readonly<Record<string, ManifestRelation>>;
280
+ /**
281
+ * Optional human-readable description of the entity (issue #154), from
282
+ * `@model({ description })`. Pure documentation — absent unless declared, so an
283
+ * entity with no description serializes byte-identically to the pre-#154
284
+ * manifest. Surfaces as the generated Python class docstring.
285
+ */
286
+ readonly description?: string;
287
+ /**
288
+ * The physical attribute name of the model's DynamoDB **Time-To-Live** field,
289
+ * when one is declared via `@ttl` (issue #172, Epic #167 — CFn generator C4).
290
+ * Unlike the maintenance/stream signals (a maintenance-IR concern kept OFF the
291
+ * manifest), TTL is a **physical schema** fact, and the CloudFormation emitter
292
+ * consumes the manifest — so the TTL attribute name flows here and the emitter
293
+ * renders `TimeToLiveSpecification { AttributeName: <this>, Enabled: true }`. The
294
+ * attribute is deliberately NOT added to the table's key `AttributeDefinitions`
295
+ * (that list holds ONLY key/index attributes; `TimeToLiveSpecification` legitimately
296
+ * names a non-key attribute). **Absent** when the model declares no `@ttl`, so a
297
+ * TTL-free model serializes byte-identically to the pre-#172 manifest (backward
298
+ * compatible). DynamoDB permits exactly one TTL attribute per physical table; the
299
+ * single-per-table rule is enforced at manifest build.
300
+ */
301
+ readonly ttlAttribute?: string;
302
+ }
303
+ interface ManifestTable {
304
+ readonly physicalName: string;
305
+ }
306
+ interface Manifest {
307
+ /**
308
+ * Always the base {@link SPEC_VERSION}: the manifest carries entity/schema
309
+ * metadata only — the SCP Expression IR vocabulary (issue #261) lives in the
310
+ * operations document, so the conditional `1.2` stamp never applies here and
311
+ * every manifest stays byte-identical.
312
+ */
313
+ readonly version: typeof SPEC_VERSION;
314
+ readonly tables: Readonly<Record<string, ManifestTable>>;
315
+ readonly entities: Readonly<Record<string, ManifestEntity>>;
316
+ }
317
+ interface ParamSpec {
318
+ readonly type: ParamKind;
319
+ readonly required: boolean;
320
+ /** Allowed literal values for `literal` params; omitted otherwise. */
321
+ readonly literals?: readonly (string | number)[];
322
+ /**
323
+ * For an `array` param (transaction `forEach` source), the per-element field
324
+ * descriptors (field name → element param spec). Omitted for scalar params.
325
+ */
326
+ readonly element?: Readonly<Record<string, ParamSpec>>;
327
+ /**
328
+ * Optional human-readable description of the parameter (issue #154), from a
329
+ * `param.*({ description })` placeholder. Pure documentation — absent unless
330
+ * declared, so a param with no description serializes byte-identically to the
331
+ * pre-#154 spec. The Python runtime never reads it for execution.
332
+ */
333
+ readonly description?: string;
334
+ }
335
+ /** A `begins_with` range condition on a sort key (templated value). */
336
+ interface RangeConditionSpec {
337
+ readonly operator: 'begins_with';
338
+ readonly key: string;
339
+ /** Template value, e.g. `GROUP#` or `GROUP#{result.groupId}`. */
340
+ readonly value: string;
341
+ }
342
+ /** Server-side declarative filter, carried verbatim for the runtime to compile. */
343
+ interface FilterSpec {
344
+ /** The declarative {@link FilterInput} tree (JSON-safe). */
345
+ readonly declarative: unknown;
346
+ }
347
+ type ReadOperationType = 'Query' | 'GetItem' | 'BatchGetItem';
348
+ /**
349
+ * A single static read operation. Relation chains are expressed as multiple
350
+ * operations whose `resultPath` / templated key conditions wire them together.
351
+ */
352
+ interface OperationSpec {
353
+ readonly type: ReadOperationType;
354
+ readonly tableName: string;
355
+ readonly indexName?: string;
356
+ /**
357
+ * Key condition: attribute name → template value. For a `BatchGetItem` this is
358
+ * the per-key shape (one key per resolved source item at runtime).
359
+ */
360
+ readonly keyCondition: Readonly<Record<string, string>>;
361
+ readonly rangeCondition?: RangeConditionSpec;
362
+ /** Projected fields (entity field names). */
363
+ readonly projection: readonly string[];
364
+ readonly limit?: number;
365
+ readonly filter?: FilterSpec;
366
+ /**
367
+ * Where the result of this operation is placed in the assembled result.
368
+ * `$` is the root; `$.groups.items` a relation connection's items, etc.
369
+ */
370
+ readonly resultPath: string;
371
+ /**
372
+ * For relation operations: the source field on the prior result whose value(s)
373
+ * drive this operation's `{result.*}` placeholders. Absent on the root op.
374
+ */
375
+ readonly sourceField?: string;
376
+ /**
377
+ * The **list fan-out binding form** (issue #208, B案 — the shared-IR
378
+ * generalization that lifted the #197 `refs` loud-reject). Present only on a
379
+ * `BatchGetItem` relation operation that resolves a `refs` relation: instead of
380
+ * reading ONE scalar `parent[sourceField]`, the runtime reads the parent **list
381
+ * attribute** {@link SourceListSpec.from} and binds `{result.<sourceField>}`
382
+ * once per element — `element[key]` for an object element, the element itself
383
+ * for a bare scalar — skipping null/undefined refs. All element keys across all
384
+ * parents fan into ONE deduped `BatchGetItem` (the existing chunk/retry
385
+ * machinery), and the operation's `resultPath` (`…<prop>.items`) receives a
386
+ * connection `{ items, cursor: null }` whose items are the resolved child
387
+ * bodies in **first-seen element order**, deduped, with missing bodies dropped
388
+ * — byte-matching the TS in-process `fetchRefsList` semantics. Absent on every
389
+ * scalar-bound relation op (a pre-#208 document is byte-identical).
390
+ */
391
+ readonly sourceList?: SourceListSpec;
392
+ }
393
+ /**
394
+ * The list-valued source descriptor of a fan-out `BatchGetItem` operation (issue
395
+ * #208 B案; the operation-IR mirror of the manifest's `ManifestRelation.refs`).
396
+ */
397
+ interface SourceListSpec {
398
+ /** The parent LIST attribute holding the inline reference elements (e.g. `tagRefs`). */
399
+ readonly from: string;
400
+ /**
401
+ * The field read off each element (e.g. `tagId`). Always equals the operation's
402
+ * `sourceField` (the `{result.<sourceField>}` token name); carried explicitly so
403
+ * the op is self-describing.
404
+ */
405
+ readonly key: string;
406
+ /**
407
+ * `true` when the parent list attribute was NOT selected by the query and was
408
+ * projected onto the parent operation **solely** to drive this fan-out. The
409
+ * runtime must then delete `from` from every parent node after ALL relation
410
+ * operations are applied — mirroring the TS hydrator, which projects implicit
411
+ * relation-source fields but strips them from the assembled result. Absent when
412
+ * the query's select projects the attribute itself (it stays in the result).
413
+ */
414
+ readonly implicit?: boolean;
415
+ }
416
+ /**
417
+ * The **execution plan** for a multi-operation read (issue #70a). It is the
418
+ * Single Source of Truth for *how* a query's {@link OperationSpec}[] is staged:
419
+ * which operations are independent (may run concurrently) and which must wait for
420
+ * a prior operation's result. Every runtime that honors it produces identical
421
+ * effects with identical concurrency discipline — the staging is **serialized,
422
+ * not re-derived** (cf. the contract decided-facts discipline).
423
+ *
424
+ * - `groups` is an ordered list of **stages**; each stage is a list of indices
425
+ * into the query's `operations[]`. Operations **within** a stage are mutually
426
+ * independent and may be issued concurrently; stages run **in order** because a
427
+ * later stage reads a `{result.*}` value produced by an earlier one. Stage 0 is
428
+ * always `[0]` (the root). Every operation index appears in exactly one stage,
429
+ * and the stages are a topological layering of the result-dependency graph.
430
+ * - `concurrency` is the declared in-flight bound a runtime applies **within**
431
+ * each stage (the shared {@link RELATION_TRAVERSAL_CONCURRENCY} = 16): at most
432
+ * this many operations of a stage are issued at once.
433
+ *
434
+ * ## Derivation (see `buildReadOperations` / `deriveExecutionPlan`)
435
+ *
436
+ * The planner emits `operations[]` in a deterministic pre-order: the root at
437
+ * index 0, then each relation child immediately followed by its own descendants.
438
+ * A child's key templates reference `{result.<sourceField>}` of the **operation
439
+ * whose `resultPath` is the child's parent path** — that producer is the child's
440
+ * sole dependency. The stage of an operation is therefore `1 + stage(parent)`:
441
+ * the root is stage 0; sibling relations that share a parent path land in the
442
+ * **same** stage (no inter-`{result.*}` dependency between siblings, so they are
443
+ * independent and concurrency-eligible); a grandchild that reads its parent's
444
+ * `{result.*}` lands one stage later. This mirrors exactly the level-by-level
445
+ * fan-out the TS relation runtime performs at runtime (`resolveRelations` issues
446
+ * sibling relations together under the same bound) — #70a only *records* it.
447
+ *
448
+ * Absent on a single-operation spec and on specs produced before #70a; a consumer
449
+ * without a plan falls back to one-operation-per-stage **sequential** execution
450
+ * (the pre-#70 behavior), so an absent plan never changes results.
451
+ */
452
+ interface ExecutionPlanSpec {
453
+ /** Ordered stages; each stage is indices into `operations[]` (stage 0 = `[0]`). */
454
+ readonly groups: readonly (readonly number[])[];
455
+ /** The declared in-flight bound applied within each stage (16). */
456
+ readonly concurrency: number;
457
+ }
458
+ /** A query (read) definition's full execution spec. */
459
+ interface QuerySpec {
460
+ readonly params: Readonly<Record<string, ParamSpec>>;
461
+ readonly operations: readonly OperationSpec[];
462
+ /**
463
+ * Result cardinality of the **root** (`$`) operation, derived from the
464
+ * operation kind: `'one'` for a `query` (a single entity object, with any
465
+ * relations attached directly), `'many'` for a `list` (a `{ items, cursor }`
466
+ * connection). The relation runtime (#45) uses this to shape the root result:
467
+ * a `'one'` Query root takes the first matched item rather than returning a
468
+ * connection. Absent in specs produced before #45; consumers should treat an
469
+ * absent value as `'many'` for a `Query`/`BatchGetItem` root and `'one'` for a
470
+ * `GetItem` root (the pre-#45 behavior).
471
+ */
472
+ readonly cardinality?: 'one' | 'many';
473
+ /**
474
+ * The staged execution plan (issue #70a): which {@link operations} are
475
+ * independent (concurrency-eligible) vs. result-dependent. Present only when the
476
+ * query has more than one operation (a relation chain); a single-operation read
477
+ * needs no plan. See {@link ExecutionPlanSpec} for the derivation and the
478
+ * backward-compatible (plan-absent → sequential) fallback.
479
+ */
480
+ readonly executionPlan?: ExecutionPlanSpec;
481
+ /**
482
+ * Optional human-readable description of the query (issue #154), from a
483
+ * contract method's `description` field. Pure documentation — absent unless
484
+ * declared, so a query with no description serializes byte-identically to the
485
+ * pre-#154 spec. Surfaces as the generated Python repository-method docstring.
486
+ */
487
+ readonly description?: string;
488
+ }
489
+ /**
490
+ * The Expression IR vocabulary version (behavior-contracts `expression-ir.md`
491
+ * §9). A runtime handed an unknown `exprVersion` MUST fail closed.
492
+ */
493
+ declare const EXPR_VERSION: 1;
494
+ /**
495
+ * The closed operator vocabulary of Expression IR v1 (expression-ir.md §3).
496
+ * An operator node is a **single-key** object — key = operator name, value =
497
+ * the argument array. Anything outside this set is invalid IR (fail-closed).
498
+ */
499
+ type ExpressionOperator = 'add' | 'sub' | 'mul' | 'div' | 'mod' | 'neg' | 'concat' | 'eq' | 'ne' | 'lt' | 'le' | 'gt' | 'ge' | 'and' | 'or' | 'not' | 'coalesce' | 'cond' | 'len';
500
+ /**
501
+ * A scalar literal carried as-is (expression-ir.md §2.1). `number` follows the
502
+ * §2.3 classification rule: a fractional value is a float; an integer value is
503
+ * an int and MUST be within the safe-integer range (beyond it the literal is
504
+ * carried as {@link ExpressionIntNode}). NaN / ±Infinity / undefined cannot
505
+ * exist in the IR.
506
+ */
507
+ type ExpressionScalar = string | number | boolean | null;
508
+ /** Strict member access (`a.b.c`); a null intermediate is a Failure (§2.2). */
509
+ interface ExpressionRefNode {
510
+ readonly ref: readonly string[];
511
+ }
512
+ /** Null-propagating member access (`a?.b`); a null intermediate → null (§2.2). */
513
+ interface ExpressionRefOptNode {
514
+ readonly refOpt: readonly string[];
515
+ }
516
+ /** Object construction (`{ x: <expr> }`, §2.3). Keys sort canonically. */
517
+ interface ExpressionObjNode {
518
+ readonly obj: Readonly<Record<string, ExpressionNode>>;
519
+ }
520
+ /** Array construction (`[a, b]`, §2.3). */
521
+ interface ExpressionArrNode {
522
+ readonly arr: readonly ExpressionNode[];
523
+ }
524
+ /**
525
+ * An int literal beyond the safe-integer range (±2^53−1), carried as a string
526
+ * because a raw JSON number would lose precision in TS (§2.3). Must fit i64.
527
+ */
528
+ interface ExpressionIntNode {
529
+ readonly int: string;
530
+ }
531
+ /**
532
+ * An **integer-valued** float literal (TS surface `1.0`), wrapped because JSON
533
+ * does not preserve the decimal point (§2.3). A fractional float (`1.5`) is a
534
+ * plain JSON number.
535
+ */
536
+ interface ExpressionFloatNode {
537
+ readonly float: number;
538
+ }
539
+ /**
540
+ * An operator node: a single-key object mapping one {@link ExpressionOperator}
541
+ * to its argument array (§2.1). The mapped-union form makes each member carry
542
+ * **exactly** its one operator key.
543
+ */
544
+ type ExpressionOpNode = {
545
+ [K in ExpressionOperator]: {
546
+ readonly [P in K]: readonly ExpressionNode[];
547
+ };
548
+ }[ExpressionOperator];
549
+ /**
550
+ * One Expression IR node (expression-ir.md §2): a scalar literal, a reference,
551
+ * a construction form, a wrapped int/float literal, or an operator node.
552
+ */
553
+ type ExpressionNode = ExpressionScalar | ExpressionRefNode | ExpressionRefOptNode | ExpressionObjNode | ExpressionArrNode | ExpressionIntNode | ExpressionFloatNode | ExpressionOpNode;
554
+ /**
555
+ * A serialized SCP expression (issue #261): the versioned envelope around one
556
+ * Expression IR node. This is the payload of a `{ kind: 'scpExpr' }` write
557
+ * condition and of every `guard` slot. The embedded `expr` is stored in
558
+ * **canonical form** (§2.3/§2.4: key-sorted at every level — code-point order —
559
+ * with `{int:"…"}` / `{float:n}` literal wrapping), produced by
560
+ * `canonicalizeExpressionSpec` in `src/spec/expression.ts`, so the document
561
+ * serializes deterministically through the ordinary JSON emitters.
562
+ */
563
+ interface ExpressionSpec {
564
+ readonly exprVersion: typeof EXPR_VERSION;
565
+ readonly expr: ExpressionNode;
566
+ }
567
+ type WriteOperationType = 'PutItem' | 'UpdateItem' | 'DeleteItem';
568
+ /**
569
+ * A condition expression on a write, as a JSON-serializable spec (issues #46,
570
+ * #81). The supported subset:
571
+ *
572
+ * - `{ kind: 'notExists' }` → `attribute_not_exists(PK)` (legacy whole-row guard).
573
+ * - `{ kind: 'attributeExists'; field }` → `attribute_exists(<field>)` — the named
574
+ * attribute (any field, incl. PK/SK) must be present. The foundation for
575
+ * referential-integrity derivation.
576
+ * - `{ kind: 'attributeNotExists'; field }` → `attribute_not_exists(<field>)` — the
577
+ * named attribute must be absent (field-level uniqueness / first-write guard).
578
+ * - `{ kind: 'equals'; fields }` → `#f = :v AND …` field equality (each value a
579
+ * `{param}` / literal template).
580
+ * - `{ kind: 'expr'; declarative }` → the full declarative operator tree (issue
581
+ * #114-A): comparison (`gt`/`ge`/`lt`/`le`/`ne`), `between`, `in`,
582
+ * `begins_with`/`contains`/`notContains`, `attributeType`, and the logical
583
+ * `and`/`or`/`not` groups, mirroring the read-side {@link FilterSpec}. The tree
584
+ * is JSON-safe: each leaf value is either a native literal (string / number /
585
+ * boolean) or a {@link ConditionParamLeaf} (`{ $param }`) marking a caller
586
+ * param bound at execution time. The runtime resolves the param leaves against
587
+ * the caller params, then compiles the tree to a DynamoDB `ConditionExpression`
588
+ * with the SAME mechanics the filter compiler uses (so TS and Python emit an
589
+ * identical expression / semantics).
590
+ */
591
+ type ConditionSpec = {
592
+ readonly kind: 'notExists';
593
+ } | {
594
+ readonly kind: 'attributeExists';
595
+ readonly field: string;
596
+ } | {
597
+ readonly kind: 'attributeNotExists';
598
+ readonly field: string;
599
+ } | {
600
+ readonly kind: 'equals';
601
+ readonly fields: Readonly<Record<string, string>>;
602
+ } | {
603
+ readonly kind: 'expr';
604
+ readonly declarative: unknown;
605
+ } | {
606
+ /**
607
+ * A raw DynamoDB condition produced by the `cond` escape hatch (issue
608
+ * #114-B), for write conditions that the declarative operator subset
609
+ * cannot express. It is **pre-compiled and deterministic**: the
610
+ * `expression` is a finished DynamoDB `ConditionExpression` whose name
611
+ * placeholders are stable `#cr_<field>` aliases (reused per distinct
612
+ * column) and whose value placeholders are sequential `:cr0`, `:cr1`, …
613
+ * (assigned in template order), so the serialized golden is stable. The
614
+ * names map binds each `#cr_<field>` alias to its entity field; the values
615
+ * map binds each `:crN` alias to either a native literal (an embedded
616
+ * `cond` value — in-process the concrete value) or a {@link ConditionParamLeaf}
617
+ * (`{ $param }`) marker bound from a caller param at execution time (the
618
+ * public-contract slot). The runtime substitutes the param leaves, then
619
+ * attaches `expression` / `names` / serialized `values` to the write —
620
+ * TS and Python build the identical DynamoDB expression.
621
+ */
622
+ readonly kind: 'raw';
623
+ readonly expression: string;
624
+ readonly names: Readonly<Record<string, string>>;
625
+ readonly values: Readonly<Record<string, unknown>>;
626
+ } | {
627
+ /**
628
+ * An SCP Expression IR write condition (issue #261, Phase 3 S1): the
629
+ * condition is a behavior-contracts `expression-ir.md` §2 expression,
630
+ * carried as a versioned {@link ExpressionSpec} in canonical form. A
631
+ * document containing this variant is stamped spec version
632
+ * {@link SPEC_VERSION_SCP} (`1.2`, conditional stamping), so a runtime
633
+ * that does not yet evaluate the expression vocabulary loud-rejects the
634
+ * whole document (fail-closed) instead of silently dropping the
635
+ * condition. Evaluation wiring is the Phase 3 S5/S6/S7 sub-issues.
636
+ */
637
+ readonly kind: 'scpExpr';
638
+ readonly expression: ExpressionSpec;
639
+ };
640
+ interface CommandSpec {
641
+ readonly type: WriteOperationType;
642
+ readonly tableName: string;
643
+ readonly entity: string;
644
+ readonly params: Readonly<Record<string, ParamSpec>>;
645
+ /**
646
+ * Key condition for `UpdateItem` / `DeleteItem` (attribute name → template).
647
+ * Absent for `PutItem` (the whole item is built from `item`).
648
+ */
649
+ readonly keyCondition?: Readonly<Record<string, string>>;
650
+ /** The full item template for `PutItem` (field name → template / literal). */
651
+ readonly item?: Readonly<Record<string, string>>;
652
+ /** Field-level changes for `UpdateItem` (field name → template / literal). */
653
+ readonly changes?: Readonly<Record<string, string>>;
654
+ /** Optional write condition (subset). */
655
+ readonly condition?: ConditionSpec;
656
+ /**
657
+ * Optional human-readable description of the command (issue #154), from a
658
+ * contract method's `description` field. Pure
659
+ * documentation — absent unless declared, so a command with no description
660
+ * serializes byte-identically to the pre-#154 spec. Surfaces as the generated
661
+ * Python repository-method docstring.
662
+ */
663
+ readonly description?: string;
664
+ }
665
+ /**
666
+ * A declarative `when` guard on a transaction item (issue #46). Compares a
667
+ * templated left-hand value against a templated right-hand value; the item is
668
+ * skipped when the comparison does not hold. Both values are template strings
669
+ * (`{param}` / `{item.<field>}` / literal), resolved by the runtime before the
670
+ * comparison. The runtime compares the resolved **string** values.
671
+ */
672
+ interface WhenSpec {
673
+ readonly op: 'eq' | 'ne';
674
+ /** Templated left-hand value (typically an `{item.<field>}` or `{param}`). */
675
+ readonly left: string;
676
+ /** Templated right-hand value (literal or another reference). */
677
+ readonly right: string;
678
+ }
679
+ /**
680
+ * The kind of a transaction item. The three write kinds (`Put` / `Update` /
681
+ * `Delete`) mutate an item; `ConditionCheck` (issue #81) is a **read-only
682
+ * assertion** on another item — it asserts a {@link ConditionSpec} holds for the
683
+ * keyed row without modifying it, and its failure cancels the **whole**
684
+ * `TransactWriteItems` atomically. It is the foundation for referential-integrity
685
+ * derivation (proposal: `requires <Entity> exists` → a `ConditionCheck` with
686
+ * `attribute_exists`).
687
+ */
688
+ type TransactionItemType = 'Put' | 'Update' | 'Delete' | 'ConditionCheck';
689
+ /**
690
+ * A value leaf of a transaction `item` / `changes` / `add` map (issue #245).
691
+ *
692
+ * - a **string** carries a template: a `{param}` / `{item.field}` placeholder, a
693
+ * composite (`PREFIX#{param}`), or a plain string literal — resolved by the
694
+ * runtimes' template machinery (a whole-placeholder string keeps the bound
695
+ * param's *type*, a composite / plain string resolves to a string);
696
+ * - a **number** / **boolean** carries a *typed literal* verbatim, so a numeric
697
+ * literal in a `put` item / `update` changes (`version: 0`) survives to DynamoDB
698
+ * as an `N` / `BOOL` instead of being stringified to an `S` (the pre-#245 bug).
699
+ *
700
+ * A `Date` literal is serialized to its ISO-8601 **string** at build time (a
701
+ * `@datetime` / `@date` field is stored as `S`), so it stays a string leaf.
702
+ */
703
+ type TransactionValueLeaf = string | number | boolean;
704
+ /**
705
+ * A single templated item in a transaction. When `forEach` is present, the item
706
+ * is expanded **once per element** of the named array param, with each element's
707
+ * fields bound to the item's `{item.<field>}` placeholders.
708
+ *
709
+ * Field presence by `type`:
710
+ *
711
+ * | type | item | keyCondition | changes | add | condition |
712
+ * |----------------|------|--------------|---------|-----|--------------------------|
713
+ * | `Put` | ✓ | — | — | — | optional |
714
+ * | `Update` | — | ✓ | ✓ / — | ✓ / — | optional |
715
+ * | `Delete` | — | ✓ | — | — | optional |
716
+ * | `ConditionCheck` | — | ✓ | — | — | **required** (the assert) |
717
+ *
718
+ * An `Update` carries `changes` (a `SET` of named fields) and/or `add` (an atomic
719
+ * `ADD` of named numeric fields, issue #85) — at least one of the two. The two are
720
+ * distinct DynamoDB update actions: `SET #f = :v` **overwrites**, while
721
+ * `ADD #f :delta` **atomically increments** without a read (concurrency-safe), so
722
+ * a derived counter (`User.postCount += 1`) MUST be an `add`, never a `changes`
723
+ * `SET` (which would clobber a concurrent increment).
724
+ */
725
+ interface TransactionItemSpec {
726
+ readonly type: TransactionItemType;
727
+ readonly tableName: string;
728
+ readonly entity: string;
729
+ /**
730
+ * Put: the full item template (field → template / typed literal). A string
731
+ * value is a template ({@link TransactionValueLeaf}); a `number` / `boolean` is
732
+ * a typed literal carried verbatim (issue #245).
733
+ */
734
+ readonly item?: Readonly<Record<string, TransactionValueLeaf>>;
735
+ /** Update / Delete / ConditionCheck: the key template (attribute → template). */
736
+ readonly keyCondition?: Readonly<Record<string, string>>;
737
+ /**
738
+ * Update: field-level `SET` change templates (overwrite). A string value is a
739
+ * template; a `number` / `boolean` is a typed literal carried verbatim (#245).
740
+ */
741
+ readonly changes?: Readonly<Record<string, TransactionValueLeaf>>;
742
+ /**
743
+ * Update: field-level atomic `ADD` deltas (issue #85, derived counters). Each
744
+ * value is a numeric template (`{param}` / a literal number string) or a typed
745
+ * numeric literal (issue #245); the runtime applies `ADD #field :delta`, an
746
+ * atomic increment that needs no prior read and is safe under concurrency. A
747
+ * negative delta decrements (e.g. `-1` on a remove).
748
+ */
749
+ readonly add?: Readonly<Record<string, TransactionValueLeaf>>;
750
+ /**
751
+ * The write / assertion condition (subset). Optional on `Put` / `Update` /
752
+ * `Delete`; **required** on a `ConditionCheck` (the assertion it makes).
753
+ */
754
+ readonly condition?: ConditionSpec;
755
+ /** Optional declarative guard; the item is skipped when it does not hold. */
756
+ readonly when?: WhenSpec;
757
+ /**
758
+ * Optional SCP expression guard (issue #261, Phase 3 S1): a boolean
759
+ * behavior-contracts Expression IR expression, carried beside the legacy
760
+ * {@link when} comparison. The item is skipped when the expression does not
761
+ * hold. A document carrying a `guard` is stamped {@link SPEC_VERSION_SCP}
762
+ * (`1.2`), so a runtime that does not yet evaluate the expression vocabulary
763
+ * loud-rejects the whole document rather than silently skipping the guard
764
+ * (fail-closed; evaluation wiring is Phase 3 S5/S6/S7). `when` removal is
765
+ * the 0.8.0 reorg (#251/#252).
766
+ */
767
+ readonly guard?: ExpressionSpec;
768
+ /** When present, expand this item once per element of the named array param. */
769
+ readonly forEach?: {
770
+ readonly source: string;
771
+ };
772
+ /**
773
+ * Marks a **raw marker-row** write (issue #86 uniqueness guard): the row is NOT a
774
+ * modeled entity, so its primary key is carried **literally** rather than derived
775
+ * from manifest metadata. When `true`:
776
+ *
777
+ * - a `Put` writes its `item` record **verbatim** as the stored item — the `item`
778
+ * already carries the synthetic `PK` / `SK` templates (`UNIQUE#…`), so the
779
+ * runtimes do NOT prepend a model prefix or compute GSI attributes;
780
+ * - a `Delete` uses its `keyCondition` (the `PK` / `SK` templates) as the row Key
781
+ * verbatim.
782
+ *
783
+ * The companion {@link entity} is the {@link MARKER_ROW_ENTITY} sentinel (there is
784
+ * no manifest entity to resolve). Absent / `false` on every modeled write (a base
785
+ * entity / edge / counter / ConditionCheck item), so those paths are unchanged.
786
+ */
787
+ readonly literalKey?: boolean;
788
+ /**
789
+ * A **relation-side maintenance write** (Epic #118, issue #129 — the JSON-SSoT /
790
+ * Python mirror of the TS in-process `renderMaintainWriteItem`). Present ONLY on an
791
+ * `Update` item that materializes a maintained access path: a projected
792
+ * {@link DerivedMaintainWrite} of a just-written source row into a SEPARATE owner
793
+ * (destination) row, in the SAME atomic transaction as the source write.
794
+ *
795
+ * The item's {@link keyCondition} carries the owner row's key templates (bound from
796
+ * the source payload — `{sourceInputField}`), so the same key derivation / collapse
797
+ * signature the other `Update` items use applies unchanged. This `maintain` payload
798
+ * carries the projection transform IR (`identity` / `preview`) the runtimes apply
799
+ * IDENTICALLY when rendering the `SET … = :v` (snapshot) / `list_append(…)`
800
+ * (collection) `UpdateExpression`, so the maintained row is byte-consistent across
801
+ * TS and Python. The `changes` / `add` fields are NOT used when this is present.
802
+ */
803
+ readonly maintain?: MaintainItemSpec;
804
+ }
805
+ /**
806
+ * The transform op applied to one projected maintenance attribute (Epic #118).
807
+ * Mirrors `ProjectionTransformOp` from `src/define/entity-writes.ts`: `identity`
808
+ * copies the source value through unchanged; `preview` keeps the first `n`
809
+ * characters of (the string form of) the source value. The runtimes apply this
810
+ * IDENTICALLY so the maintained row is byte-consistent.
811
+ */
812
+ type MaintainProjectionOp = 'identity' | 'preview';
813
+ /**
814
+ * One projected maintenance attribute: the source value is read from the mutation
815
+ * input field {@link inputField} (payload 同梱 — the just-written source row image),
816
+ * then run through {@link op} with {@link args} (e.g. `preview`'s length bound).
817
+ */
818
+ interface MaintainProjectionEntry {
819
+ /** The transform op applied to the source value (`identity` / `preview`). */
820
+ readonly op: MaintainProjectionOp;
821
+ /** The op's positional arguments (`[n]` for `preview`; empty for `identity`). */
822
+ readonly args: readonly unknown[];
823
+ /** The mutation-input field the source value is read from (`{inputField}`). */
824
+ readonly inputField: string;
825
+ }
826
+ /**
827
+ * The bounded-collection options a `collection` maintenance write carries. Phase 1
828
+ * is **append-only**: `maxItems` / `orderBy` are recorded for the future async trim
829
+ * (#130) but NOT applied synchronously — a single `UpdateExpression` cannot
830
+ * read-modify-write a bounded/ordered list.
831
+ */
832
+ interface MaintainCollectionSpec {
833
+ /** The target attribute that holds the maintained collection. */
834
+ readonly field: string;
835
+ /** Cap on the collection size (recorded for #130; not trimmed in Phase 1). */
836
+ readonly maxItems?: number;
837
+ /** The mutation-input field the items are ordered by (recorded for #130). */
838
+ readonly orderBy?: string;
839
+ /** The direction `orderBy` sorts by, from the relation's `read.order` (recorded for #130). */
840
+ readonly orderDir?: 'ASC' | 'DESC';
841
+ }
842
+ /**
843
+ * The maintenance payload an `Update` {@link TransactionItemSpec} carries when it
844
+ * materializes a maintained access path (Epic #118 / #129). A `snapshot` mirrors
845
+ * the projection onto the owner row via `SET`; a `collection` appends the projection
846
+ * as an item into the bounded list named by {@link collection} via `list_append`.
847
+ */
848
+ interface MaintainItemSpec {
849
+ /**
850
+ * Whether the write mirrors a single row (`snapshot`), appends a collection item
851
+ * (`collection`), or applies a scalar `ADD` counter (`counter`, Epic #118 / #141).
852
+ */
853
+ readonly kind: 'snapshot' | 'collection' | 'counter';
854
+ /** The relation property / `@aggregate` field that declared this maintenance (documentary). */
855
+ readonly relationProperty: string;
856
+ /** The trigger (`<sourceLogicalName>.<event>`) that fired this maintenance. */
857
+ readonly trigger: string;
858
+ /** target attribute → its projection transform (source field + op + args). Empty for `counter`. */
859
+ readonly projection: Readonly<Record<string, MaintainProjectionEntry>>;
860
+ /** The bounded-collection options; present only for `kind: 'collection'`. */
861
+ readonly collection?: MaintainCollectionSpec;
862
+ /**
863
+ * The scalar counter `ADD`; present only for `kind: 'counter'` (#141). The runtimes
864
+ * render `ADD #attr :delta` — an atomic, concurrency-safe increment that MERGES with
865
+ * a same-row counter ADD (#92), the maintenance-pipeline analogue of the
866
+ * self-lifecycle derived counter's `add` slot. `delta` is a numeric template string
867
+ * (the compile-time constant `+1` created / `-1` removed).
868
+ */
869
+ readonly counter?: MaintainCounterSpec;
870
+ }
871
+ /**
872
+ * The scalar counter a `counter` maintenance write applies (Epic #118 / #141): an
873
+ * atomic `ADD #attribute :delta`. `delta` is a literal numeric template string (the
874
+ * compile-time constant the trigger fixed — `"1"` created / `"-1"` removed); the
875
+ * runtimes serialize it as a number. Only `count()` is realized synchronously
876
+ * (`max(field)` is rejected for the synchronous path — #130 / Phase 2).
877
+ */
878
+ interface MaintainCounterSpec {
879
+ /** The target attribute the counter increments (e.g. `postCount`). */
880
+ readonly attribute: string;
881
+ /** The signed `ADD` delta as a numeric template string (`"1"` / `"-1"`). */
882
+ readonly delta: string;
883
+ }
884
+ /** A declarative transaction definition's full execution spec. */
885
+ interface TransactionSpec {
886
+ readonly params: Readonly<Record<string, ParamSpec>>;
887
+ readonly items: readonly TransactionItemSpec[];
888
+ /**
889
+ * A static upper bound on the expanded item count when computable (no `forEach`
890
+ * present → the exact count; with `forEach` it is left absent because the
891
+ * element count is only known at execution — the runtime then enforces the
892
+ * DynamoDB ≤25 limit after expansion).
893
+ */
894
+ readonly maxItems?: number;
895
+ }
896
+ /**
897
+ * Whether a contract is a public **read** (`'query'`) or **write** (`'command'`)
898
+ * interface. Mirrors {@link QueryModelContract} / {@link CommandModelContract}'s
899
+ * `kind` discriminant from the Contract IR (#58).
900
+ */
901
+ type ContractKind = 'query' | 'command';
902
+ /**
903
+ * The resolution kind of a contract query method, **derived** by the planner from
904
+ * the internal op (never hand-written; see proposal "N+1 Safety"):
905
+ *
906
+ * - `'point'` — target keys are known (unique-key `query` / `GetItem`); a key
907
+ * array coalesces to one `BatchGetItem`.
908
+ * - `'range'` — target key set is unknown (partition `list` / `Query`); one
909
+ * request per partition key, so it is only ever safe for a single key.
910
+ */
911
+ type ContractResolution = 'point' | 'range';
912
+ /**
913
+ * What input arity a contract method accepts, **derived** from its resolution:
914
+ *
915
+ * - `'either'` — a single key **or** an array (a `point` read / a known-key
916
+ * write; the array form is one `BatchGetItem` / batched write).
917
+ * - `'single'` — a single key only (a `range` read; an array would be an N+1
918
+ * fan-out and is rejected by construction).
919
+ * - `'array'` — an array only (reserved; not produced by the current resolvers).
920
+ */
921
+ type ContractInputArity = 'single' | 'array' | 'either';
922
+ /**
923
+ * The per-key result cardinality of a contract query method, **derived** from the
924
+ * internal op kind (proposal "Cardinality matrix"):
925
+ *
926
+ * - `'one'` — at most one item per key (a `point` read).
927
+ * - `'many'` — a connection (`{ items, cursor }`) per key (a `range` read).
928
+ *
929
+ * This is the per-key shape; the input arity (single vs. array) then decides
930
+ * whether the overall result is bare or keyed.
931
+ */
932
+ type ContractCardinality = 'one' | 'many';
933
+ /**
934
+ * The category of a contract command method's declared result, part of the
935
+ * contract (it surfaces in OpenAPI and every binding; proposal "Return values"):
936
+ *
937
+ * - `'void'` — fire-and-forget write (no body).
938
+ * - `'result'` — an outcome / status object (e.g. `{ ok, version }`).
939
+ * - `'entity'` — the updated entity (the post-write projection).
940
+ */
941
+ type ContractCommandResult = 'void' | 'result' | 'entity';
942
+ /** The Key of a contract: the field names that compose its access / join key. */
943
+ interface ContractKeySpec {
944
+ /** The key field names, in declaration order (e.g. `["articleId"]`). */
945
+ readonly fields: readonly string[];
946
+ }
947
+ /**
948
+ * One External Query (Query Composition) binding on a contract query method
949
+ * (proposal "External Query"). It is a **build-time, in-process** read dependency
950
+ * on another contract referenced by name in the same SSoT — there is no protocol
951
+ * or transport. The runtime collects every parent key produced at this level and
952
+ * resolves the referenced contract **once, batched**, for all of them.
953
+ *
954
+ * A composed child MUST be `point` (proposal "N+1 Safety"): the parent step may
955
+ * yield N records, so a `range` child would be an N+1 fan-out.
956
+ */
957
+ interface ComposeSpec {
958
+ /** The result property the composed value is attached to (e.g. `billing`). */
959
+ readonly as: string;
960
+ /** The referenced contract name (a symbol in the same SSoT). */
961
+ readonly contract: string;
962
+ /** The referenced method on that contract (e.g. `get`). */
963
+ readonly method: string;
964
+ /**
965
+ * An optional **logical** owner label (the bounded context that owns the
966
+ * referenced contract) — not a network address. Omitted when unlabeled.
967
+ */
968
+ readonly context?: string;
969
+ /**
970
+ * The child-key binding: child key field → a `from` source path on the parent
971
+ * result, e.g. `{ accountId: "$.billingAccountId" }`.
972
+ */
973
+ readonly bind: Readonly<Record<string, string>>;
974
+ /**
975
+ * The composed child's resolution. It MUST be `'point'` in a valid contract — a
976
+ * composed child coalesces to one `BatchGetItem` across all parent keys, so a
977
+ * `range` child (a partition `Query` that cannot be batched across the parent's
978
+ * keys) is an N+1 fan-out. The N+1 static checker (#60,
979
+ * {@link assertContractN1Safe}) rejects a `'range'` value on the build path; the
980
+ * field is widened to {@link ContractResolution} so the offending node can be
981
+ * carried into the assembled {@link ContractSpec} for the checker to inspect and
982
+ * reject with a clear message, rather than being silently unrepresentable.
983
+ */
984
+ readonly resolution: ContractResolution;
985
+ /** The composed child's per-key cardinality (`'one'` for a valid `point`). */
986
+ readonly cardinality: ContractCardinality;
987
+ }
988
+ /**
989
+ * The **composition execution plan** for one query contract method (issue #70a),
990
+ * the contract-layer mirror of {@link ExecutionPlanSpec}. It records how a method's
991
+ * External Query compositions (`compose[]`) are staged relative to the parent read
992
+ * and to one another, and the batching discipline each composed child obeys:
993
+ *
994
+ * - `stages` is an ordered list whose entries are indices into the method's
995
+ * `compose[]`. The parent read (the referenced `operation`) is the implicit
996
+ * stage before all of these. Every compose child binds its child key purely from
997
+ * the **parent** result (`from('$.…')` paths), so sibling compositions are
998
+ * mutually independent: they form a single stage `[0, 1, …]` and may be resolved
999
+ * concurrently. (A composed child cannot, today, bind from another composed
1000
+ * child — the #63 DSL only exposes parent `from` paths — so there is never a
1001
+ * cross-composition dependency; the field is a list of stages so the shape can
1002
+ * carry one if a future primitive introduces it.)
1003
+ * - `concurrency` is the declared in-flight bound applied **within** a stage (the
1004
+ * shared {@link RELATION_TRAVERSAL_CONCURRENCY} = 16).
1005
+ * - `batchChunkSize` is the per-request key cap for a composed child read (100,
1006
+ * the DynamoDB `BatchGetItem` limit): a composition resolves **one batched
1007
+ * call** across all parent records (chunked at this size), never an N+1 fan-out
1008
+ * (the composed child is `point`, enforced by the #60 N+1 checker).
1009
+ *
1010
+ * Emitted only when the method declares at least one composition. A method without
1011
+ * compositions carries no plan, and a runtime without one resolves any
1012
+ * compositions sequentially (the pre-#70 behavior) — so an absent plan never
1013
+ * changes results.
1014
+ */
1015
+ interface CompositionPlanSpec {
1016
+ /** Ordered stages of indices into `compose[]` (independent siblings share a stage). */
1017
+ readonly stages: readonly (readonly number[])[];
1018
+ /** The declared in-flight bound applied within each composition stage (16). */
1019
+ readonly concurrency: number;
1020
+ /** Per-request key cap for a composed child's batched read (100, BatchGetItem limit). */
1021
+ readonly batchChunkSize: number;
1022
+ }
1023
+ /**
1024
+ * The serialized spec of one **query** contract method. Carries the decided facts
1025
+ * (`resolution` / `inputArity` / `cardinality`) the planner derived in #58, a
1026
+ * reference into `queries` by name (the internal op), and any External Query
1027
+ * compositions. The decided facts are **serialized, not re-derived** — every
1028
+ * runtime honors them.
1029
+ */
1030
+ interface QueryContractMethodSpec {
1031
+ /** Derived: `'point'` (unique-key query) or `'range'` (partition list). */
1032
+ readonly resolution: ContractResolution;
1033
+ /** Derived: `'either'` for `point`, `'single'` for `range`. */
1034
+ readonly inputArity: ContractInputArity;
1035
+ /** Derived per-key result shape: `'one'` (point) or `'many'` (range). */
1036
+ readonly cardinality: ContractCardinality;
1037
+ /** The referenced read op name in `queries` (e.g. `ArticleById__get`). */
1038
+ readonly operation: string;
1039
+ /** External Query compositions on this method; omitted when there are none. */
1040
+ readonly compose?: readonly ComposeSpec[];
1041
+ /**
1042
+ * The composition staging + batch plan (issue #70a); present only when `compose`
1043
+ * is. See {@link CompositionPlanSpec}: independent compositions form one
1044
+ * concurrency-eligible stage after the parent read, each resolved as one batched
1045
+ * call (chunk ≤100). Absent → resolve compositions sequentially (pre-#70).
1046
+ */
1047
+ readonly compositionPlan?: CompositionPlanSpec;
1048
+ /**
1049
+ * Optional human-readable description of the read use case (issue #154), from the
1050
+ * descriptor's `description`. Pure documentation — absent unless declared, so a
1051
+ * method with no description serializes byte-identically to the pre-#154 spec.
1052
+ * The same string appears in the TS contract IR and (via the SSoT) in any
1053
+ * generated binding, so TS↔Python carry an identical description.
1054
+ */
1055
+ readonly description?: string;
1056
+ }
1057
+ /**
1058
+ * How a contract command method resolves a single key vs. an array of keys to the
1059
+ * underlying write surface (proposal "Consistency with the existing write
1060
+ * surface"). A single key → one write op (or one transaction); an array → a
1061
+ * batched write — a `TransactWriteItems` when atomicity / per-item conditions are
1062
+ * required, or a `BatchWriteItem` when neither is.
1063
+ */
1064
+ type CommandResolutionTarget =
1065
+ /** One write op, referenced by name in `commands`. */
1066
+ {
1067
+ readonly mode: 'op';
1068
+ readonly operation: string;
1069
+ }
1070
+ /** One transaction, referenced by name in `transactions`. */
1071
+ | {
1072
+ readonly mode: 'transaction';
1073
+ readonly transaction: string;
1074
+ }
1075
+ /**
1076
+ * A non-atomic **parallel** fan-out over the per-key write op (#101). The op
1077
+ * MAY carry a condition (guarded create / conditioned update). Unconditioned
1078
+ * `put`/`delete` ops coalesce into a `BatchWriteItem` (with `UnprocessedItems`
1079
+ * retry); conditioned/update ops issue individual conditional writes
1080
+ * concurrently. Per-op success/failure is reported (partial success); a
1081
+ * per-op failure never aborts the others. References the per-key write op in
1082
+ * `commands`.
1083
+ */
1084
+ | {
1085
+ readonly mode: 'parallel';
1086
+ readonly operation: string;
1087
+ };
1088
+ /**
1089
+ * The serialized spec of one **command** contract method. Symmetric to
1090
+ * {@link QueryContractMethodSpec}: it carries the declared `result` type and the
1091
+ * `single` / `batch` resolution targets into the existing write specs.
1092
+ */
1093
+ interface CommandContractMethodSpec {
1094
+ /** Derived input arity: writes accept `'either'` (single key or key array). */
1095
+ readonly inputArity: ContractInputArity;
1096
+ /** The declared result type (`void` | a `Result` | the updated entity). */
1097
+ readonly result: ContractCommandResult;
1098
+ /** How a single key resolves (one op / one transaction). */
1099
+ readonly single: CommandResolutionTarget;
1100
+ /**
1101
+ * How an array of keys resolves (a transaction / `BatchWriteItem`); omitted
1102
+ * when the contract does not declare a batched write form.
1103
+ */
1104
+ readonly batch?: CommandResolutionTarget;
1105
+ /**
1106
+ * The **return projection** of a `mutation`-derived command method (issue #83;
1107
+ * proposal §3, "return selection as a read projection"). A JSON-safe boolean
1108
+ * field map: after the write commits, the runtime issues a **`GetItem` with
1109
+ * `ConsistentRead`** of the written entity's primary key and applies this
1110
+ * projection via the existing read-projection machinery, returning the projected
1111
+ * item. This is the **uniform** return mechanism for both a single-op command
1112
+ * and a future transaction (a `TransactWriteItems` cannot return item images),
1113
+ * so TS and Python return an **identical** projected item.
1114
+ *
1115
+ * The consistent read-back is issued against the read op named
1116
+ * `<Contract>__<method>__readback` (a synthesized {@link QuerySpec}: a `GetItem`
1117
+ * on the written entity's primary key projecting these fields). Present only on
1118
+ * a `.plan(mutation)` method; a hand-written #64 command omits it (its
1119
+ * {@link result} stays `'void'` / `'entity'` and it returns no projected item).
1120
+ */
1121
+ readonly returnSelection?: Readonly<Record<string, boolean>>;
1122
+ /**
1123
+ * Optional SCP expression guard on the contract-method op (issue #261,
1124
+ * Phase 3 S1) — the same guard slot a {@link TransactionItemSpec} carries:
1125
+ * a boolean behavior-contracts Expression IR expression gating the method's
1126
+ * write. Vocabulary-only in S1 (populated by the #262 lowerer); a document
1127
+ * carrying it is stamped {@link SPEC_VERSION_SCP} (`1.2`) so pre-evaluation
1128
+ * runtimes loud-reject it (fail-closed).
1129
+ */
1130
+ readonly guard?: ExpressionSpec;
1131
+ /**
1132
+ * Optional human-readable description of the write use case (issue #154), from
1133
+ * the descriptor's `description`. Pure documentation — absent unless declared, so
1134
+ * a method with no description serializes byte-identically to the pre-#154 spec.
1135
+ */
1136
+ readonly description?: string;
1137
+ }
1138
+ /**
1139
+ * A serialized contract — a keyed public read (`'query'`) or write (`'command'`)
1140
+ * interface holding one or more named methods. Each method references an existing
1141
+ * operation spec by name and adds the decided contract facts. The existing
1142
+ * operation-spec shapes are unchanged, so the current runtime keeps working.
1143
+ */
1144
+ interface ContractSpec {
1145
+ /** Whether this is a read (`'query'`) or write (`'command'`) contract. */
1146
+ readonly kind: ContractKind;
1147
+ /** The contract Key (the access pattern / join / batch key). */
1148
+ readonly key: ContractKeySpec;
1149
+ /**
1150
+ * The named methods (use cases over the same Key). A query contract's methods
1151
+ * are {@link QueryContractMethodSpec}; a command contract's are
1152
+ * {@link CommandContractMethodSpec}. The map is keyed by contract `kind`.
1153
+ */
1154
+ readonly methods: Readonly<Record<string, QueryContractMethodSpec>> | Readonly<Record<string, CommandContractMethodSpec>>;
1155
+ }
1156
+ /**
1157
+ * One bounded context's membership (issue #59, "context ownership"). Lists the
1158
+ * Models and Contracts that belong to the same context, so the future boundary
1159
+ * lint (#61) can tell **own** from **foreign**: a contract may resolve its own
1160
+ * context's Models directly, but may only reach another context through that
1161
+ * context's published Contract (direct use of a foreign Model is a build error).
1162
+ *
1163
+ * This issue only **serializes / emits** this declaration; it does not enforce
1164
+ * it. Both lists are entity / contract *names* (matching `manifest.entities` keys
1165
+ * and `contracts` keys respectively).
1166
+ */
1167
+ interface ContextSpec {
1168
+ /** Model (entity) names owned by this context (sorted; manifest entity keys). */
1169
+ readonly models: readonly string[];
1170
+ /** Contract names owned by this context (sorted; `contracts` map keys). */
1171
+ readonly contracts: readonly string[];
1172
+ }
1173
+ interface OperationsDocument {
1174
+ /**
1175
+ * `1.1` unless the document actually contains an SCP Expression IR node (a
1176
+ * `scpExpr` condition or a `guard`), in which case it is stamped `1.2`
1177
+ * (issue #261, conditional stamping — see {@link SPEC_VERSION_SCP}).
1178
+ */
1179
+ readonly version: SpecVersion;
1180
+ readonly queries: Readonly<Record<string, QuerySpec>>;
1181
+ readonly commands: Readonly<Record<string, CommandSpec>>;
1182
+ /** Declarative transactions (issue #46). Absent in pre-#46 specs. */
1183
+ readonly transactions?: Readonly<Record<string, TransactionSpec>>;
1184
+ /**
1185
+ * The CQRS Contract layer (issue #59): contract name → {@link ContractSpec}.
1186
+ * Layered **on top of** the existing `queries` / `commands` / `transactions`
1187
+ * (each method references one of them by name). **Absent** when the input
1188
+ * defines no contracts — so a contract-free input produces a byte-identical
1189
+ * pre-#59 operations document (backward compatibility).
1190
+ */
1191
+ readonly contracts?: Readonly<Record<string, ContractSpec>>;
1192
+ /**
1193
+ * Context-ownership declarations (issue #59): context name →
1194
+ * {@link ContextSpec}. Used by the boundary lint (#61) to tell own from
1195
+ * foreign. **Absent** when no contexts are declared (backward compatibility).
1196
+ */
1197
+ readonly contexts?: Readonly<Record<string, ContextSpec>>;
1198
+ }
1199
+ /** The full `{ manifest, operations }` bundle produced by the static planner. */
1200
+ interface BridgeBundle {
1201
+ readonly manifest: Manifest;
1202
+ readonly operations: OperationsDocument;
1203
+ }
1204
+
1205
+ export { type LiteralParam as $, type ManifestEntity as A, type BridgeBundle as B, type ContractSpec as C, type ManifestField as D, type ExpressionSpec as E, type FilterSpec as F, type ManifestFieldType as G, type ManifestGsi as H, type ManifestKey as I, type ManifestRelation as J, type ManifestTable as K, type OperationSpec as L, type Manifest as M, type QueryContractMethodSpec as N, type OperationsDocument as O, type ParamSpec as P, type QuerySpec as Q, type RangeConditionSpec as R, SPEC_VERSION as S, type TransactionSpec as T, type ReadOperationType as U, SPEC_VERSION_SCP as V, SPEC_VERSION_SUPPORTED as W, type TransactionItemSpec as X, type TransactionItemType as Y, type WhenSpec as Z, type WriteOperationType as _, type CommandSpec as a, type NumberParam as a0, type Param as a1, type ParamKind as a2, type StringParam as a3, param as a4, type ContextSpec as b, type ConditionSpec as c, type SpecVersion as d, type CommandContractMethodSpec as e, type CommandResolutionTarget as f, type ComposeSpec as g, type CompositionPlanSpec as h, type ContractCardinality as i, type ContractCommandResult as j, type ContractInputArity as k, type ContractKeySpec as l, type ContractKind as m, type ContractResolution as n, EXPR_VERSION as o, type ExecutionPlanSpec as p, type ExpressionArrNode as q, type ExpressionFloatNode as r, type ExpressionIntNode as s, type ExpressionNode as t, type ExpressionObjNode as u, type ExpressionOpNode as v, type ExpressionOperator as w, type ExpressionRefNode as x, type ExpressionRefOptNode as y, type ExpressionScalar as z };