behavior-contracts 0.10.0 → 0.11.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 (92) hide show
  1. package/README.md +430 -115
  2. package/cli-contract.yaml +49 -51
  3. package/dist/authoring.d.ts +61 -424
  4. package/dist/authoring.d.ts.map +1 -1
  5. package/dist/authoring.js +53 -1157
  6. package/dist/authoring.js.map +1 -1
  7. package/dist/behavior.d.ts +7 -15
  8. package/dist/behavior.d.ts.map +1 -1
  9. package/dist/behavior.js.map +1 -1
  10. package/dist/builder.d.ts +4 -4
  11. package/dist/builder.d.ts.map +1 -1
  12. package/dist/builder.js +9 -11
  13. package/dist/builder.js.map +1 -1
  14. package/dist/cli.js +5 -5
  15. package/dist/cli.js.map +1 -1
  16. package/dist/commands/codegen.d.ts.map +1 -1
  17. package/dist/commands/codegen.js +12 -56
  18. package/dist/commands/codegen.js.map +1 -1
  19. package/dist/commands/ts-compile.d.ts +23 -0
  20. package/dist/commands/ts-compile.d.ts.map +1 -0
  21. package/dist/commands/ts-compile.js +724 -0
  22. package/dist/commands/ts-compile.js.map +1 -0
  23. package/dist/commands/ts-extract.d.ts +67 -1
  24. package/dist/commands/ts-extract.d.ts.map +1 -1
  25. package/dist/commands/ts-extract.js +162 -31
  26. package/dist/commands/ts-extract.js.map +1 -1
  27. package/dist/generated/contract.d.ts.map +1 -1
  28. package/dist/generated/contract.js +2 -2
  29. package/dist/generated/contract.js.map +1 -1
  30. package/dist/generated/program.js +4 -4
  31. package/dist/generated/program.js.map +1 -1
  32. package/dist/generator/core.d.ts +11 -1
  33. package/dist/generator/core.d.ts.map +1 -1
  34. package/dist/generator/core.js +5 -4
  35. package/dist/generator/core.js.map +1 -1
  36. package/dist/generator/emit-php.d.ts +0 -17
  37. package/dist/generator/emit-php.d.ts.map +1 -1
  38. package/dist/generator/emit-php.js +25 -1
  39. package/dist/generator/emit-php.js.map +1 -1
  40. package/dist/generator/emit-python.d.ts +0 -7
  41. package/dist/generator/emit-python.d.ts.map +1 -1
  42. package/dist/generator/emit-python.js +34 -1
  43. package/dist/generator/emit-python.js.map +1 -1
  44. package/dist/generator/emit-straightline-typed-typescript.js +1 -1
  45. package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
  46. package/dist/generator/emit-typed-native-go.d.ts +1 -1
  47. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  48. package/dist/generator/emit-typed-native-go.js +110 -107
  49. package/dist/generator/emit-typed-native-go.js.map +1 -1
  50. package/dist/generator/emit-typed-native-rust.d.ts +3 -2
  51. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  52. package/dist/generator/emit-typed-native-rust.js +62 -126
  53. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  54. package/dist/generator/emit-typescript-native.js +1 -1
  55. package/dist/generator/emit-typescript-native.js.map +1 -1
  56. package/dist/generator/emit-typescript.js +1 -1
  57. package/dist/generator/emit-typescript.js.map +1 -1
  58. package/dist/generator/typed.d.ts +5 -1
  59. package/dist/generator/typed.d.ts.map +1 -1
  60. package/dist/generator/typed.js +40 -9
  61. package/dist/generator/typed.js.map +1 -1
  62. package/dist/guard.d.ts +4 -0
  63. package/dist/guard.d.ts.map +1 -1
  64. package/dist/guard.js +26 -8
  65. package/dist/guard.js.map +1 -1
  66. package/dist/index.d.ts +19 -55
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +24 -87
  69. package/dist/index.js.map +1 -1
  70. package/dist/lowering.d.ts +251 -0
  71. package/dist/lowering.d.ts.map +1 -0
  72. package/dist/lowering.js +652 -0
  73. package/dist/lowering.js.map +1 -0
  74. package/dist/provenance.js +4 -4
  75. package/dist/provenance.js.map +1 -1
  76. package/dist/runtime.d.ts +52 -0
  77. package/dist/runtime.d.ts.map +1 -0
  78. package/dist/runtime.js +77 -0
  79. package/dist/runtime.js.map +1 -0
  80. package/dist/spec-versions.d.ts +25 -0
  81. package/dist/spec-versions.d.ts.map +1 -0
  82. package/dist/spec-versions.js +26 -0
  83. package/dist/spec-versions.js.map +1 -0
  84. package/dist/type-gate.d.ts +12 -0
  85. package/dist/type-gate.d.ts.map +1 -1
  86. package/dist/type-gate.js +79 -3
  87. package/dist/type-gate.js.map +1 -1
  88. package/package.json +5 -1
  89. package/dist/bind.d.ts +0 -64
  90. package/dist/bind.d.ts.map +0 -1
  91. package/dist/bind.js +0 -131
  92. package/dist/bind.js.map +0 -1
package/README.md CHANGED
@@ -1,36 +1,178 @@
1
1
  # behavior-contracts
2
2
 
3
- `behavior-contracts` is a library for declarative, statically-resolvable behavior/DSL
4
- contracts. A contract is compiled to a **portable, language-neutral IR** and then either
5
- compiled to **genuinely-native per-language code** (Go and Rust) that runs at
6
- hand-written-SDK-floor parity, or interpreted by a small shared multi-language runtime
7
- (TypeScript / Python / PHP / Rust / Go). The IR is deterministic and
8
- canonically-serialized, so the same contract produces byte-identical output across every
9
- consumer language.
3
+ **`behavior-contracts` (bc) is a DSL for declaring what a piece of behavior *means*.**
4
+
5
+ In most codebases, business logic, persistence, transactions, external calls, error handling and
6
+ execution order all end up tangled inside one function in one language. Responsibility boundaries
7
+ blur, the implementation and the documentation drift apart, and the order of execution gets baked
8
+ into the code.
9
+
10
+ bc separates the two questions. You declare **what the behavior means** — which components
11
+ compose into which result — as a contract. You do **not** write how it is orchestrated: execution
12
+ order is derived from the data dependencies, not written by hand. The declaration is ordinary
13
+ TypeScript, so it is simultaneously the specification *and* the running code.
14
+
15
+ ```ts
16
+ import { behavior, type Int } from "behavior-contracts";
17
+
18
+ class UserQueries {
19
+ @behavior
20
+ static findByEmail(email: string): User[] {
21
+ return Db.query(`SELECT id, email FROM users WHERE email = ?`, [email]);
22
+ }
23
+ }
24
+ ```
25
+
26
+ That method *is* the contract. `@behavior` is a marker: at runtime it does nothing — the method
27
+ runs as plain TypeScript — and at build time it marks the entry point bc reads.
28
+
29
+ ## Because the meaning is implementation-independent, it can target any language
30
+
31
+ A declaration says what the behavior means, not how one language happens to implement it. That
32
+ independence is what makes the rest possible: **one declaration compiles to Go, Rust, Python and
33
+ PHP** — Go and Rust as genuinely native code running at hand-written-SDK-floor parity, Python and
34
+ PHP as modules driven by a small shared runtime. Compilation is deterministic and canonically
35
+ serialized, so the same declaration produces byte-identical results in every language.
36
+
37
+ Multi-language codegen is a *consequence* of the design, not the point of it.
38
+
39
+ ```mermaid
40
+ flowchart TD
41
+ TS["Declaration — ordinary TypeScript<br/>(the contract AND the running code)"]
42
+ RUN["runs directly in TypeScript"]
43
+ IR["bc-internal IR"]
44
+ ML["Go · Rust · Python · PHP"]
45
+ LEAF["leaf — the one hand-written<br/>I/O function per language"]
46
+
47
+ TS --> RUN
48
+ TS -->|"bc generate (build time)"| IR
49
+ IR --> ML
50
+ LEAF -. called by .-> RUN
51
+ LEAF -. called by .-> ML
52
+ ```
53
+
54
+ The IR is bc's own internal intermediate — never hand-written or hand-handled. The only code
55
+ hand-written per language is one op-agnostic **leaf transport** per leaf (the actual I/O), and the
56
+ library that owns the behaviors ships those.
57
+
58
+ > The declaration style bc implements is **Semantic Contract Programming (SCP)** — "contract the
59
+ > meaning itself as components, and build larger meaning by combining them". The full paradigm is
60
+ > specified in [`docs/semantic-contract-programming.md`](../docs/semantic-contract-programming.md);
61
+ > you do not need to read it to use bc.
62
+
63
+ > This is the README bundled with the published npm package. It mirrors the monorepo root
64
+ > README; the repository also holds the specs, conformance vectors and examples it links to.
65
+
66
+ ## Who this is for
67
+
68
+ bc sits under a stack of three levels; the two audiences below are levels 2 and 3.
69
+
70
+ 1. **behavior-contracts (bc)** — this package: the declaration substrate and its native codegen.
71
+ 2. **A library built on bc** — a *bc consumer* (e.g. litedbmodel or graphddb), the
72
+ **library author**. Its job is to express its own domain surface (e.g. litedbmodel's
73
+ decorators) as bc declarations: its own decorators stay metadata-only collectors, and its
74
+ lowering step produces the declaration-limited TypeScript that bc reads. It also **ships the
75
+ per-language leaf transports** (Go / Rust / …). This is the audience that writes `@behavior` /
76
+ `@leaf` methods and hand-writes each leaf transport once per language. It provides everything
77
+ except the end user's model. → **Section A**.
78
+ 3. **A user of such a library** — the **end user** (the library's consumer, e.g. a
79
+ litedbmodel user). They declare their model with the *library's* own surface and run it. In
80
+ **TypeScript** they simply **call the method** — the markers are no-ops at runtime, so the
81
+ declaration is just TypeScript that runs. For **Go / Rust / Python / PHP** it is `bc generate`
82
+ (the `bc` CLI, run directly) linked to the library's shipped leaf transports, then a call to the
83
+ generated entry point. They write **no declarations for bc, no leaf transport, no IR** — just the
84
+ model and the run call. → **Section B**.
85
+
86
+ If you are **building** a library on top of bc, read **Section A**. If you are **using** a
87
+ library that was built on bc, read **Section B**.
10
88
 
11
89
  ## Features
12
90
 
13
- - **Native typed-native codegen for Go and Rust.** A covered contract is emitted as
91
+ - **Native typed-native codegen for Go and Rust.** A covered behavior is emitted as
14
92
  straight-line native code — direct struct field access, concrete per-node calls, and a
15
93
  local error type — running at **SDK-floor parity** (~0–5% overhead vs. a hand-written
16
94
  SDK baseline) and **~2–3× faster than the shared interpreter**.
17
95
  - **Zero-runtime generated modules.** The generated Go/Rust modules import **no**
18
96
  `behavior-contracts` runtime at all — a property the compiler verifies (a build gate
19
97
  rejects any runtime reference or boxing primitive that leaks into the output).
20
- - **Async or sync output, selectable.** Pass `ioModel: "async"` to emit `async fn` /
21
- `.await` for async-capable targets; `"sync"` is the default.
22
- - **Fail-closed, never silently boxed.** Shapes not yet natively coverable are rejected
23
- at generation time rather than falling back to a boxed/interpreted path labelled as
24
- native.
25
- - **Portable IR, consumed identically across languages.** The same language-neutral IR
26
- runs through the shared interpreter in TypeScript, Python, PHP, Rust, and Go with
27
- identical semantics.
98
+ - **BC owns the wire type; one transport per leaf.** BC generates the concrete wire type
99
+ (`WireValue`/`WireRow`/`WireList`) and all of the strict de-box. The only hand-written
100
+ native code is a single op-agnostic leaf transport that reads its inputs from a `WireRow`
101
+ payload and returns a `WireValue` — no trait, no probe protocol, no per-role signature.
102
+ - **Fail-closed, never silently boxed.** Shapes not yet natively coverable are rejected at
103
+ generation time rather than falling back to a boxed/interpreted path labelled as native.
104
+ An ambiguous or non-canonical type is rejected **loudly at build time**.
105
+ - **In TypeScript the declaration just runs.** `@behavior` / `@leaf` are no-op markers at
106
+ runtime, so a declared method is an ordinary static method: calling it executes the leaf
107
+ implementations directly at native JS speed — no interpreter, no lowering call, no generated
108
+ file, zero runtime deps.
109
+ - **Shared interpreter for Python and PHP.** The same declaration emits an interpreter
110
+ module that runs on the shared runtime with identical semantics (a TypeScript interpreter module
111
+ is available too, when you want an emitted file rather than a direct call).
28
112
  - **Deterministic, canonical serialization.** Key-sorted, typed-value encoding with a
29
- canonical decimal float representation — the same contract always serializes to the
30
- same bytes, which is what makes cross-language conformance verifiable.
113
+ canonical decimal float representation — the same behavior always serializes to the same
114
+ bytes, which is what makes cross-language conformance verifiable.
115
+
116
+ Native de-box codegen is for **Go and Rust**. **TypeScript** needs no codegen at all — the
117
+ declaration runs as-is; Python and PHP consume the compiled behavior through the shared
118
+ interpreter.
31
119
 
32
- Native codegen is **Go and Rust only**. TypeScript, Python, and PHP consume the portable
33
- IR through the shared interpreter.
120
+ ## What you can write in a declaration
121
+
122
+ A declaration body is ordinary TypeScript, but only the subset below carries meaning across
123
+ languages. Everything in it is written as **native TypeScript syntax** — bc reads the syntax and
124
+ derives the contract. Anything outside this subset is **rejected loudly at build time** (never
125
+ silently reinterpreted).
126
+
127
+ **Values and references**
128
+
129
+ | You write | Meaning |
130
+ |---|---|
131
+ | `email` (a parameter) | an input port |
132
+ | `row.title` | a field reference |
133
+ | `row?.title` | an optional reference (missing is a value, not an error) |
134
+ | `` `A#${id}` `` / `"a" + id` | string concatenation |
135
+ | `1`, `"x"`, `true`, `null`, `[…]`, `{…}` | literals (`Int` / `Float` distinguish integer from float) |
136
+
137
+ **Operators**
138
+
139
+ | You write | Meaning |
140
+ |---|---|
141
+ | `+` `-` `*` `/` `%` `-x` | arithmetic (`add` `sub` `mul` `div` `mod` `neg`) |
142
+ | `===` `!==` `<` `<=` `>` `>=` | comparison |
143
+ | `&&` `\|\|` `!` | boolean logic (operands must be `bool` — no truthiness) |
144
+ | `??` | default when null (`coalesce`) |
145
+ | `xs.length` | length of an array |
146
+
147
+ Loose equality (`==` / `!=`) and truthy conditions are rejected — the meaning must be unambiguous
148
+ in every target language.
149
+
150
+ **Control flow**
151
+
152
+ | You write | Meaning |
153
+ |---|---|
154
+ | `cond ? a : b` | choose a value, or choose which component runs |
155
+ | `if (cond) { … }` | run a component only when the condition holds (otherwise it is skipped) |
156
+ | `xs.map(x => …)` | run a component once per element |
157
+
158
+ Execution order is **not** written: bc derives it from the data dependencies, and independent work
159
+ is scheduled concurrently.
160
+
161
+ **Components (the units of meaning)**
162
+
163
+ | You write | Meaning |
164
+ |---|---|
165
+ | `@behavior static m(a: T): R` | a declared behavior — arguments are input ports, the return type is the output |
166
+ | `@leaf static f(a: T): R` | a leaf — the boundary where real I/O happens (one hand-written transport per language) |
167
+ | `Db.query(sql, params)` | calling a leaf = one component in the graph |
168
+ | `const x: T = …` | pins the result type of a node |
169
+ | `opt(x)` | make a reference optional |
170
+ | `xs.map(f, { into, batched })` | map options: zip the result into each element / batch the calls |
171
+ | `refsConnection(…, { dedupeKey, drop, implicitSource })` | fan out over references, de-duplicating them |
172
+
173
+ `@behavior` and `@leaf` are **markers**: at runtime they do nothing, so the method is an ordinary
174
+ static method that just runs. `opt` and `refsConnection` are the only two helpers with no native
175
+ TypeScript equivalent.
34
176
 
35
177
  ## Install
36
178
 
@@ -40,117 +182,163 @@ npm install behavior-contracts
40
182
 
41
183
  - ESM-only library; TypeScript type declarations are included.
42
184
  - Requires Node.js **22+**.
43
- - No runtime dependencies.
44
-
45
- ## Usage
46
-
47
- A contract is authored as an IR (a portable component graph). You can either **generate a
48
- native module** from it, or **interpret it directly** with the shared runtime.
185
+ - No runtime dependencies. (`typescript` is a build-time-only optional peer, needed by the
186
+ CLI to codegen from a `.ts` declaration module.)
187
+ - If you **run a generated TypeScript module**, keep `behavior-contracts` as a dependency of the
188
+ project that runs it — the generated module pulls what it needs from this package itself.
49
189
 
50
- ### Generate a native module
190
+ ---
51
191
 
52
- ```ts
53
- import { generateModule } from "behavior-contracts";
54
-
55
- // `ir` is a portable component-graph IR (language-neutral).
56
- const mod = generateModule(ir, {
57
- language: "go-typed-native", // or "rust-typed-native"
58
- ioModel: "async", // "sync" (default) | "async"
59
- });
60
-
61
- console.log(mod.language); // "go"
62
- console.log(mod.filenameHint); // e.g. "behaviors.generated.go"
63
- console.log(mod.fingerprint); // IR fingerprint (build-time skew gate)
64
- // mod.code is the full, runtime-free native source — write it to a file and compile it.
65
- ```
192
+ # Section A — For library authors (building a library on bc)
66
193
 
67
- `generateModule` also emits interpreted modules for other targets — pass
68
- `language: "typescript"`, `"python"`, `"php"`, `"rust"`, or `"go"`. It is fail-closed:
69
- an unknown language, a non-portable IR, or a shape the target emitter cannot cover
70
- natively throws rather than degrading silently.
194
+ You are writing the layer that maps your library's own DSL/decorators onto bc. Your decorators stay
195
+ metadata-only collectors; your lowering step turns that metadata into **declaration-limited
196
+ TypeScript** — the `@behavior` / `@leaf` methods below — and `bc generate --from` reads that source
197
+ **statically** (it parses the AST; it never executes your module). You also **ship one op-agnostic
198
+ leaf transport per leaf, per language** — so your users only declare a model and run it (Section B).
71
199
 
72
- ### Generate from the CLI
200
+ Because the lowering step produces source, one of your decorators can expand into **several** leaves
201
+ or a composed behavior: the structure you emit is your choice, and bc reads whatever declaration
202
+ comes out.
73
203
 
74
- The package installs a `bc` binary — codegen over the same public API:
204
+ ## Declare in TypeScript
75
205
 
76
- ```bash
77
- # emit a module to stdout (or write it with --out <file>)
78
- bc generate --lang go-typed-native --in behaviors.ir.json > behaviors.generated.go
79
- bc generate --lang rust-typed-native --in behaviors.ir.json --out behaviors.generated.rs
206
+ A behavior is a `@behavior static` method. Its **parameters are the inputs** (natural positional
207
+ arguments — no bag object), and its **return type is the output**. A leaf is a `@leaf static`
208
+ method whose **signature is the contract** bc reads: parameters become the leaf's input ports and
209
+ the return type its output (a `T[]` return means the leaf yields many). Numeric precision uses the
210
+ `Int` / `Float` branded aliases — plain TS `number` is **rejected** because it is ambiguous between
211
+ a 64-bit int and a 64-bit float and bc does not infer.
80
212
 
81
- # drift check: non-zero exit if the committed --out differs from a fresh generation
82
- bc check --lang go-typed-native --in behaviors.ir.json --out behaviors.generated.go
213
+ ```ts
214
+ import { behavior, leaf, type Int } from "behavior-contracts";
215
+
216
+ export interface User {
217
+ id: Int;
218
+ email: string;
219
+ }
220
+
221
+ // A leaf is a typed static method. Its SIGNATURE is what bc reads (input ports `sql` / `key`,
222
+ // output `User[]`). The BODY is the TypeScript run path — it is never touched by `bc generate`;
223
+ // the native languages call the leaf transport of the corresponding name instead.
224
+ export class Db {
225
+ @leaf static Select(sql: string, key: string): User[] {
226
+ return runYourQuery(sql, key);
227
+ }
228
+ }
229
+
230
+ export class UserRepo {
231
+ @behavior static findByEmail(email: string) {
232
+ return Db.Select("SELECT id, email FROM users WHERE email = ?", email);
233
+ }
234
+ }
83
235
  ```
84
236
 
85
- The consumer's only hand-written native code is a single op-agnostic **leaf transport** per leaf
86
- that returns the BC-owned wire value; bind it (and, for a cross-package Go / cross-crate Rust
87
- layout, hoist the BC-generated wire types into a shared package/crate):
88
-
89
- ```bash
90
- bc generate --lang rust-typed-native --leaf-transport GetItem=get_item --leaf-transport-import crate::tx --in behaviors.ir.json
91
- # Go cross-package: emit the BC-OWNED wire types (+ the batched/fanout batch ports structs) into a shared
92
- # package so the transport package can return them without an import cycle (see examples/go-cross-package/)
93
- bc generate --lang go-typed-native --shared-types-import example.com/pkg/wire --leaf-transport-import example.com/pkg/tx --in behaviors.ir.json
94
- # Rust cross-crate: emit the BC-OWNED wire types (+ the shared BehaviorError + batch ports structs) into a
95
- # shared CRATE so the transport crate can return them without an import cycle (see examples/rust-cross-crate/)
96
- bc generate --lang rust-typed-native --shared-types-import bcwire --leaf-transport-import bctx --in behaviors.ir.json
237
+ That module is what your library ships (or generates from its own decorator surface); it is the
238
+ `--from <model.ts> --behavior <Class>` the `bc` CLI compiles for Go / Rust / Python / PHP, and in
239
+ TypeScript it is simply called (Section B).
240
+
241
+ Bodies are ordinary TypeScript, restricted to what carries a portable meaning: `+` / `?:` / `&&` /
242
+ `if` / `.map` / `?.` / template literals / comparisons all lower to the portable expression and
243
+ control vocabulary. Two helpers exist because native syntax cannot express them: `opt(x)` (an
244
+ optional reference — `opt(x).field`) and `refsConnection(list, cb, opts)` (a de-duplicated fan-out).
245
+ Anything outside the portable vocabulary is rejected loudly at build time rather than silently
246
+ mis-lowered.
247
+
248
+ ## Ship the per-language leaf transports
249
+
250
+ For every language your library targets natively, you ship one op-agnostic **leaf transport** per
251
+ leaf — this is the library's job, done once for all its users, so the end user writes none of it. A
252
+ `*-typed-native` module is runtime-free and fully typed: BC owns and generates the concrete wire
253
+ type and all of the strict de-box, so the transport implements **nothing** over it. It is a single
254
+ function, with the spec-fixed name, that reads its inputs from the `WireRow` payload by field name,
255
+ does the raw I/O, and builds a BC-owned `WireValue`:
256
+
257
+ - **Go** — `func <Sym>(payload wire.WireRow) (wire.WireValue, error)`
258
+ - **Rust** — `fn <sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`
259
+
260
+ The **same one transport** serves a leaf across **all** its roles and cardinalities
261
+ (base / GSI / limited / batched / fanout) — divergent port sets are just different payload fields,
262
+ and there is no per-role signature. The generated native hot path stays fully typed; only the leaf
263
+ boundary is wire (de-box once). The default symbol name is `Leaf_<comp>` (Go) / `leaf_<comp>`
264
+ (Rust), and `--leaf-transport <leaf>=<sym>` overrides it per leaf.
265
+
266
+ ```go
267
+ package tx
268
+
269
+ import "example.com/app/wire"
270
+
271
+ // One op-agnostic function per leaf. Reads its inputs from the payload by name, does the raw
272
+ // I/O, and builds the BC-owned WireValue. The covered module owns all classification/de-box.
273
+ func Leaf_Select(payload wire.WireRow) (wire.WireValue, error) {
274
+ email := payload.ProbeString("key").Got // the port the covered module bound
275
+ _ = email
276
+ return wire.WireListOf([]wire.WireValue{
277
+ wire.WireRowOf([]wire.WireField{
278
+ {Key: "id", Val: wire.WireInt(1)},
279
+ {Key: "email", Val: wire.WireStr(email)},
280
+ }),
281
+ }), nil
282
+ }
97
283
  ```
98
284
 
99
- Run `bc generate --help` for the full option reference (also generated at `docs/cli-reference.md`).
285
+ `opt` fields are key-omittable (absent → `None`/null); an integer for a `float` slot is widened. A
286
+ type the emitter cannot bake, or an output type inconsistent with its node types, is a
287
+ generation-time error — never silently-broken code. See
288
+ [`docs/strict-typing-and-debox.md`](../docs/strict-typing-and-debox.md) for the full typing + de-box
289
+ contract.
100
290
 
101
- ### Interpret the IR directly
291
+ ### BC-owned wire types & the cross-package / cross-crate layout
102
292
 
103
- ```ts
104
- import { runBehavior } from "behavior-contracts";
293
+ BC generates the concrete wire types. By default they live in the covered module and the transport
294
+ references them back (legal within a single Rust crate or Go package). For a layout where the
295
+ transport lives in its own package/crate, `--shared-types-out` emits the BC-owned wire types (plus
296
+ the batched/fanout batch ports structs; Rust also the shared `BehaviorError`) into a shared
297
+ package/crate, and the covered module imports them via `--shared-types-import` — so the transport
298
+ package returns them with no import cycle (covered → transport → shared). `--leaf-transport-import`
299
+ names where the transport symbols are imported from. The library runs these emits once and ships the
300
+ result:
105
301
 
106
- // Inject boundary handlers; the interpreter walks the portable IR.
107
- const result = runBehavior(ir, handlers, { userId: "u1" }, "UserReads");
302
+ ```bash
303
+ # Go cross-package — emit ONLY the shared wire package (no --out ⇒ no covered module here):
304
+ bc generate --lang go-typed-native --from model.ts --behavior UserRepo \
305
+ --shared-types-out wire/wire.go \
306
+ --shared-types-import example.com/app/wire \
307
+ --leaf-transport-import example.com/app/tx
308
+
309
+ # Rust cross-crate:
310
+ bc generate --lang rust-typed-native --from model.ts --behavior UserRepo \
311
+ --shared-types-out wire/src/lib.rs \
312
+ --shared-types-import bcwire \
313
+ --leaf-transport-import bctx
108
314
  ```
109
315
 
110
- ## Consuming a typed-native module
111
-
112
- A `*-typed-native` module is runtime-free and fully typed. BC OWNS and GENERATES the concrete
113
- wire type (`WireValue`/`WireRow`/`WireList`) and all of the strict de-box that classifies each
114
- producer value against the declared type. The consumer implements NOTHING over the wire type —
115
- no trait, no probe protocol. The **only** hand-written native code is a single op-agnostic **leaf
116
- transport** per leaf that does the raw I/O and returns the BC-owned wire value:
117
-
118
- - **Rust** — write `fn leaf_<comp>(…) -> Result<WireValue, BehaviorError>` (or your chosen symbol
119
- via `--leaf-transport`); the covered module calls it directly and de-boxes the returned
120
- `WireValue` inline (no trait, no generics, no dynamic dispatch). By default the wire type lives in
121
- the covered module and the transport references it back (intra-crate module cycles are legal). For
122
- a **cross-crate** layout, `--shared-types-import <crate>` emits the BC-owned wire types (**and** the
123
- shared `BehaviorError` + the batched/fanout batch ports structs) into a shared crate the covered
124
- module imports (`use <crate>::*`), so the transport crate returns them without an import cycle
125
- (covered → transport → shared). See `../examples/rust-cross-crate/` and `../examples/rust-cross-module/`.
126
- - **Go** — write `func Leaf_<comp>(…) (WireValue, error)`, likewise called directly. For a
127
- cross-package layout, `--shared-types-import` emits the BC-owned wire types **and** the
128
- batched/fanout batch ports structs into a shared package, so the transport package returns them
129
- without an import cycle (covered → transport → shared). See `../examples/go-cross-package/`.
130
-
131
- `opt` fields are key-omittable (an absent optional attribute decodes to `None`/null); an
132
- integer supplied to a `float` slot is widened. A shape whose declared type the emitter
133
- cannot bake — or an IR whose `outputType` is inconsistent with its node types — is a
134
- generation-time error (`GeneratorFailure`), never silently-broken code. See
135
- [`docs/strict-typing-and-debox.md`](../docs/strict-typing-and-debox.md) for the full
136
- typing + de-box contract.
137
-
138
- ## Public primitives
139
-
140
- The shared runtime also exposes the individual COMMON primitives piecewise:
141
-
142
- | Export | Purpose |
143
- |---|---|
144
- | `validateEnvelope` | spec-version fail-closed validation (loud-rejects unknown versions) |
145
- | `evaluateExpression` | evaluate the portable expression IR |
146
- | `renderTemplate` | pure `{param}` string substitution |
147
- | `runPlan` | execute the portable execution-plan IR |
148
- | `canonicalValue` / `canonicalJson` | deterministic canonical serialization (sorted keys, compact JSON, canonical decimal floats) |
149
- | `runBehavior` | execute the portable component-graph IR (handlers injected at the boundary) |
150
- | `generateModule` | emit a native (Go/Rust typed-native) or interpreted module from the portable IR |
151
- | `assertPortable` / `assertPortableComponentGraph` | Portability Guard (fail-closed structural validation of portable IR) |
152
- | `SemanticBehavior` / `behavior` / `compileBehaviors` / `catalogComponents` / `when` + expression builders | effect-agnostic authoring surface — each public method of a marked class lowers to one component-graph root Behavior |
153
- | `referencedComponents` / `classifyBehaviorEffect` | consumer-side CQRS derivation from the lowered graph |
316
+ Runnable end-to-end samples of the library side + a shared wire seam:
317
+ [`examples/building-a-library-on-bc/`](../examples/building-a-library-on-bc/) (custom decorators →
318
+ declarations + Go/Rust transports) and
319
+ [`examples/library-lowering-patterns/`](../examples/library-lowering-patterns/) (metadata → **emitted**
320
+ declaration source, one relation declaration expanding into several leaf calls, and CQRS derived by
321
+ the library), plus the standalone cross-layout samples
322
+ [`examples/go-cross-package/`](../examples/go-cross-package/) (Go, separate transport package),
323
+ [`examples/rust-cross-crate/`](../examples/rust-cross-crate/) (Rust, separate transport crate), and
324
+ [`examples/rust-cross-module/`](../examples/rust-cross-module/) (Rust, intra-crate — no shared crate
325
+ needed).
326
+
327
+ ## Public API reference
328
+
329
+ Everything you import from `behavior-contracts` when declaring behaviors — this is the whole list.
330
+ Cross-language **codegen** is CLI-only: the `bc` binary is the sole public codegen entry, so no
331
+ emitter and no compile function appears here.
332
+
333
+ | Export | Kind | Purpose |
334
+ |---|---|---|
335
+ | `behavior` | decorator | Marks a `static` method as one root behavior. No-op at runtime; the entry point bc reads at build time. |
336
+ | `leaf` | decorator | Marks a `static` method as one leaf. Its signature is the contract (parameters → input ports, return type → output); its body is the TypeScript run path. |
337
+ | `opt` | fn | Optional reference — `opt(x).field` lowers to an absence-tolerant read. Identity at runtime. |
338
+ | `refsConnection` | fn | De-duplicated fan-out over a list (`dedupeKey`, optional `implicitSource`), returning `{ items, cursor }`. |
339
+ | `AuthoringFailure` | error | Thrown for an invalid declaration (e.g. a non-portable body, ambiguous `number`). |
340
+ | `Int` / `Float` | type | Branded numeric aliases that disambiguate 64-bit int vs. float (plain `number` is rejected). |
341
+ | `AuthoringFailureCode` | type | Discriminant codes for `AuthoringFailure`. |
154
342
 
155
343
  ## Spec versions
156
344
 
@@ -169,6 +357,133 @@ library (semver) version:
169
357
  | provenance | 1 |
170
358
  | envelope | 1.1 |
171
359
 
360
+ ---
361
+
362
+ # Section B — For users of a library built on bc
363
+
364
+ You are using a library (e.g. litedbmodel or graphddb) that was built on bc. You never write leaf
365
+ transports or IR — the library already did all of that (Section A). You **declare a model** with the
366
+ library's surface, name your operations, then **run it**.
367
+
368
+ ## 1. Declare your model with the library's surface
369
+
370
+ You describe your model with the **library's own surface** — its decorators, its schema DSL, whatever
371
+ it exposes. bc does **not** dictate this; the library does. An endpoint is a `@behavior static`
372
+ method whose body calls the library's leaf:
373
+
374
+ ```ts
375
+ import { entity, field, behavior, Db } from "your-library";
376
+
377
+ @entity("users")
378
+ class User {
379
+ @field.int id!: number;
380
+ @field.string email!: string;
381
+ }
382
+
383
+ export class UserRepo {
384
+ @behavior static findByEmail(email: string) {
385
+ return Db.Select("SELECT id, email FROM users WHERE email = ?", email);
386
+ }
387
+ }
388
+ ```
389
+
390
+ ## 2a. Run it in TypeScript — just call it
391
+
392
+ `@behavior` / `@leaf` are no-op markers at runtime, so the declaration is ordinary TypeScript:
393
+ calling the method runs the library's leaf implementation directly, at native JS speed. There is no
394
+ lowering call, no interpreter, no `bc generate`, and no generated file:
395
+
396
+ ```ts
397
+ import { UserRepo } from "./model.ts"; // your model, declared with the library's decorators
398
+
399
+ const rows = UserRepo.findByEmail("a@b.c"); // a plain static-method call
400
+ // rows === [{ id: 1n, email: "a@b.c" }] (int is a bigint in bc's value model)
401
+ ```
402
+
403
+ Runnable sample:
404
+ [`examples/using-a-bc-library/run-ts.mjs`](../examples/using-a-bc-library/run-ts.mjs).
405
+
406
+ ## 2b. Run it in Go / Rust / Python / PHP — `bc generate`
407
+
408
+ For the other languages the `behavior-contracts` package installs a `bc` binary you run **yourself**
409
+ (not through the library). `bc generate --from <model.ts> --behavior <Class>` reads your TypeScript
410
+ **source** with the TypeScript compiler — type-extracting each method's parameter and return types
411
+ and lowering its body's AST — and compiles source → ir → native (Go / Rust) or a shared-runtime
412
+ interpreter module (Python / PHP) in **one pass**. Your module is never executed. You wire it to the
413
+ library's shipped leaf transports + BC-owned wire types with `--leaf-transport-import` /
414
+ `--shared-types-import` — you write neither; the library ships them (Section A):
415
+
416
+ ```bash
417
+ # Go — native, wired to the library's transport + wire packages:
418
+ bc generate --lang go-typed-native --from model.ts --behavior UserRepo \
419
+ --out go/behaviors/covered.go --shared-types-import bcorm/wire --leaf-transport-import bcorm/tx
420
+
421
+ # Rust — native:
422
+ bc generate --lang rust-typed-native --from model.ts --behavior UserRepo \
423
+ --out rust/src/behaviors.rs --shared-types-import bcorm_wire --leaf-transport-import bcorm_tx
424
+
425
+ # Python / PHP — the shared-runtime interpreter module:
426
+ bc generate --lang python --from model.ts --behavior UserRepo --out behaviors_generated.py
427
+ bc generate --lang php --from model.ts --behavior UserRepo --out BehaviorsGenerated.php
428
+
429
+ # Drift gate — non-zero exit if the committed --out differs from a fresh generation:
430
+ bc check --lang go-typed-native --from model.ts --behavior UserRepo --out go/behaviors/covered.go
431
+ ```
432
+
433
+ Full flag reference: `bc generate --help` (also generated at
434
+ [`docs/cli-reference.md`](./docs/cli-reference.md)). `--in <ir-doc.json>` is an
435
+ internal/advanced input; the consumer surface is `--from`.
436
+
437
+ ## 3. Call the generated entry point
438
+
439
+ The covered module exposes a typed entry function per behavior: you pass a typed input struct and get
440
+ a typed output struct back. The transport + wire wiring is **automatic** — baked into the covered
441
+ module at generate time by the import flags — so there is no runtime injection at the call site, and
442
+ the covered module de-boxes the leaf's wire result **once** into the concrete typed output:
443
+
444
+ ```go
445
+ // go — the wiring to bcorm/tx + bcorm/wire is baked in; the call is just typed-in, typed-out.
446
+ rows, err := behaviors.RunNativeRawStruct_findByEmail(behaviors.In_findByEmail{Email: "a@b.c"})
447
+ ```
448
+ ```rust
449
+ // rust
450
+ let rows = run_native_raw_struct_findByEmail(InNRFindByEmail { email: "a@b.c".to_string() })?;
451
+ ```
452
+
453
+ A `--lang python` / `--lang php` module runs on the shared runtime with the IR embedded. A
454
+ `--lang typescript` interpreter module (an alternative to calling the declaration directly, when you
455
+ want an emitted file) embeds the compiled IR and walks it at run time — it wires itself up, so
456
+ there is nothing to import by hand.
457
+
458
+ The complete, runnable end-user example — one model, with the direct TypeScript run and the
459
+ Go / Rust `bc generate` runs all printing the same row — is
460
+ [`examples/using-a-bc-library/`](../examples/using-a-bc-library/).
461
+
462
+ ---
463
+
464
+ ## Documentation
465
+
466
+ Deeper design and specification documents live alongside the package:
467
+
468
+ - [`docs/cli-reference.md`](./docs/cli-reference.md) — the full `bc generate` /
469
+ `bc check` option reference.
470
+ - [`docs/strict-typing-and-debox.md`](../docs/strict-typing-and-debox.md) — mandatory typing,
471
+ the strict de-box, the BC-owned wire type, and the leaf transport (the full contract for the
472
+ above).
473
+ - [`docs/concept.md`](../docs/concept.md) — the concept and specification overview.
474
+ - [`docs/expression-ir.md`](../docs/expression-ir.md) — the Expression IR: the closed set of
475
+ permitted operators and their evaluation semantics.
476
+ - [`docs/canonical-serialization.md`](../docs/canonical-serialization.md) — canonical
477
+ serialization rules (key sort order, typed-value encoding, canonical float representation).
478
+ - [`docs/template-rendering.md`](../docs/template-rendering.md) — template binding / rendering
479
+ rules.
480
+ - [`docs/execution-plan.md`](../docs/execution-plan.md) — execution-plan semantics (stage
481
+ groups, concurrency, skip propagation, error policy).
482
+ - [`docs/INTEGRATION.md`](../docs/INTEGRATION.md) — integration guide for consuming the runtime
483
+ across languages.
484
+ - [`examples/`](../examples/) — minimal, dependency-free, build-free runnable samples plus the
485
+ Expression IR reference evaluator and golden vectors.
486
+
172
487
  ## License
173
488
 
174
489
  MIT — see [LICENSE](./LICENSE).