behavior-contracts 0.9.3 → 0.10.1

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 (65) hide show
  1. package/README.md +535 -116
  2. package/cli-contract.yaml +116 -24
  3. package/dist/authoring.d.ts +18 -1
  4. package/dist/authoring.d.ts.map +1 -1
  5. package/dist/authoring.js +11 -0
  6. package/dist/authoring.js.map +1 -1
  7. package/dist/behavior.d.ts +23 -0
  8. package/dist/behavior.d.ts.map +1 -1
  9. package/dist/behavior.js.map +1 -1
  10. package/dist/bind.d.ts +25 -1
  11. package/dist/bind.d.ts.map +1 -1
  12. package/dist/bind.js +33 -9
  13. package/dist/bind.js.map +1 -1
  14. package/dist/builder.d.ts.map +1 -1
  15. package/dist/builder.js +21 -6
  16. package/dist/builder.js.map +1 -1
  17. package/dist/cli.js +65 -40
  18. package/dist/cli.js.map +1 -1
  19. package/dist/commands/codegen.d.ts +18 -12
  20. package/dist/commands/codegen.d.ts.map +1 -1
  21. package/dist/commands/codegen.js +111 -27
  22. package/dist/commands/codegen.js.map +1 -1
  23. package/dist/commands/ts-extract.d.ts +26 -0
  24. package/dist/commands/ts-extract.d.ts.map +1 -0
  25. package/dist/commands/ts-extract.js +265 -0
  26. package/dist/commands/ts-extract.js.map +1 -0
  27. package/dist/generated/commands.d.ts.map +1 -1
  28. package/dist/generated/commands.js +8 -0
  29. package/dist/generated/commands.js.map +1 -1
  30. package/dist/generated/contract.d.ts.map +1 -1
  31. package/dist/generated/contract.js +2 -2
  32. package/dist/generated/contract.js.map +1 -1
  33. package/dist/generated/program.d.ts +4 -0
  34. package/dist/generated/program.d.ts.map +1 -1
  35. package/dist/generated/program.js +7 -3
  36. package/dist/generated/program.js.map +1 -1
  37. package/dist/generated/types.d.ts +6 -2
  38. package/dist/generated/types.d.ts.map +1 -1
  39. package/dist/generator/emit-typed-native-go.d.ts +5 -7
  40. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  41. package/dist/generator/emit-typed-native-go.js +244 -404
  42. package/dist/generator/emit-typed-native-go.js.map +1 -1
  43. package/dist/generator/emit-typed-native-rust.d.ts +6 -8
  44. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  45. package/dist/generator/emit-typed-native-rust.js +241 -374
  46. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  47. package/dist/guard.d.ts +23 -0
  48. package/dist/guard.d.ts.map +1 -1
  49. package/dist/guard.js +52 -0
  50. package/dist/guard.js.map +1 -1
  51. package/dist/index.d.ts +5 -32
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +24 -5
  54. package/dist/index.js.map +1 -1
  55. package/dist/ir-handle.d.ts +30 -0
  56. package/dist/ir-handle.d.ts.map +1 -0
  57. package/dist/ir-handle.js +2 -0
  58. package/dist/ir-handle.js.map +1 -0
  59. package/dist/lower.d.ts +35 -0
  60. package/dist/lower.d.ts.map +1 -0
  61. package/dist/lower.js +118 -0
  62. package/dist/lower.js.map +1 -0
  63. package/dist/provenance.d.ts +1 -1
  64. package/dist/provenance.d.ts.map +1 -1
  65. package/package.json +9 -1
package/README.md CHANGED
@@ -1,36 +1,96 @@
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 the SCP→native substrate. A behavior is authored once in
4
+ TypeScript with the **SCP authoring API**; that single definition is both a spec and an
5
+ executable function. In TypeScript it **runs directly** — `lowerBehaviors` lowers it in memory to
6
+ a native-JS-speed direct-call closure (no interpreter, no explicit codegen step, zero runtime
7
+ deps). For every other language the `bc` CLI compiles it — in one pass — either to
8
+ **genuinely-native per-language code** (Go and Rust) that runs at hand-written-SDK-floor parity,
9
+ or to a module driven by a small shared runtime (Python / PHP). Compilation is deterministic and
10
+ canonically-serialized, so the same authored behavior produces byte-identical output across every
11
+ language.
12
+
13
+ You author in **SCP** (TypeScript). The IR is bc's own internal intermediate, produced by the
14
+ public `compileBehaviors` seam and never hand-written or hand-handled. Running an authored behavior
15
+ is `lowerBehaviors` in TypeScript and `bc generate` for every other language; the only native code
16
+ hand-written downstream is one op-agnostic **leaf transport** per leaf, and the library that owns
17
+ the behaviors ships those.
18
+
19
+ ## How it fits together
20
+
21
+ ```mermaid
22
+ flowchart TD
23
+ TS["TS code — SCP behavior<br/>(a spec AND an executable function)"]
24
+ IR["codegen-internal IR"]
25
+ TSN["TS-native code<br/>(JS closure · runs at native speed)"]
26
+ ML["multi-language code<br/>(Go · Rust · Python · PHP)"]
27
+ LEAF["leaf nodes"]
28
+
29
+ TS -->|compileBehaviors| IR
30
+ IR -->|"in-memory · no explicit codegen"| TSN
31
+ IR -->|bc generate| ML
32
+ LEAF -. bound to per-language functions .-> TSN
33
+ LEAF -. bound to per-language functions .-> ML
34
+ ```
35
+
36
+ One TS behavior definition is **both the spec and an executable function**: it runs directly
37
+ in TypeScript (lowered in-memory to a JS closure — no explicit codegen) and generates the
38
+ native code for every other language. Leaf nodes bind to a per-language function (the leaf
39
+ transport).
40
+
41
+ ## Who this is for
42
+
43
+ bc sits under a stack of three levels; the two audiences below are levels 2 and 3.
44
+
45
+ 1. **behavior-contracts (bc)** — this package: the SCP→native codegen substrate.
46
+ 2. **A library built on bc** — a *bc consumer* (e.g. litedbmodel or graphddb), the
47
+ **library author**. Its job is to express its own domain surface (e.g. litedbmodel's
48
+ decorators) as bc behaviors: its own decorators are metadata-only collectors, an adapter
49
+ lowers that metadata to bc SCP via the authoring API + `compileBehaviors`, and it **ships the
50
+ per-language leaf transports** (Go / Rust / …). This is the audience that writes
51
+ `SemanticBehavior` / `@behavior` classes, `defineLeaf`, `In<T>`, and the expression builders,
52
+ and hand-writes each leaf transport once per language. It provides everything except the end
53
+ user's model. → **Section A**.
54
+ 3. **A user of such a library** — the **end user** (the library's consumer, e.g. a
55
+ litedbmodel user). They define their model with the *library's* own surface and run it. In
56
+ **TypeScript** that is `lowerBehaviors(Model)` → call the returned closure directly (native
57
+ speed, no `bc generate`). For **Go / Rust / Python / PHP** it is `bc generate` (the `bc` CLI,
58
+ run directly) linked to the library's shipped leaf transports, then a call to the generated
59
+ entry point. They write **no SCP, no leaf transport, no IR** — just the model and the run
60
+ call. → **Section B**.
61
+
62
+ If you are **building** a library on top of bc, read **Section A**. If you are **using** a
63
+ library that was built on bc, read **Section B**.
10
64
 
11
65
  ## Features
12
66
 
13
- - **Native typed-native codegen for Go and Rust.** A covered contract is emitted as
67
+ - **Native typed-native codegen for Go and Rust.** A covered behavior is emitted as
14
68
  straight-line native code — direct struct field access, concrete per-node calls, and a
15
69
  local error type — running at **SDK-floor parity** (~0–5% overhead vs. a hand-written
16
70
  SDK baseline) and **~2–3× faster than the shared interpreter**.
17
71
  - **Zero-runtime generated modules.** The generated Go/Rust modules import **no**
18
72
  `behavior-contracts` runtime at all — a property the compiler verifies (a build gate
19
73
  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.
74
+ - **BC owns the wire type; one transport per leaf.** BC generates the concrete wire type
75
+ (`WireValue`/`WireRow`/`WireList`) and all of the strict de-box. The only hand-written
76
+ native code is a single op-agnostic leaf transport that reads its inputs from a `WireRow`
77
+ payload and returns a `WireValue` — no trait, no probe protocol, no per-role signature.
78
+ - **Fail-closed, never silently boxed.** Shapes not yet natively coverable are rejected at
79
+ generation time rather than falling back to a boxed/interpreted path labelled as native.
80
+ An ambiguous or non-canonical type is rejected **loudly at authoring**.
81
+ - **Native-speed TypeScript, in memory.** `lowerBehaviors` lowers an authored behavior to a
82
+ directly-callable JS closure at native JS speed — no interpreter, no explicit codegen step, no
83
+ generated file, zero runtime deps — so a TS-defined behavior runs directly in TS.
84
+ - **Shared interpreter for Python and PHP.** The same authored behavior emits an interpreter
85
+ module that runs on the shared runtime with identical semantics (a TypeScript interpreter module
86
+ is available too, as an alternative to in-memory lowering).
28
87
  - **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.
88
+ canonical decimal float representation — the same behavior always serializes to the same
89
+ bytes, which is what makes cross-language conformance verifiable.
31
90
 
32
- Native codegen is **Go and Rust only**. TypeScript, Python, and PHP consume the portable
33
- IR through the shared interpreter.
91
+ Native de-box codegen is for **Go and Rust**. **TypeScript** runs in-memory at native JS speed via
92
+ `lowerBehaviors` (or an emitted interpreter module); Python and PHP consume the compiled behavior
93
+ through the shared interpreter.
34
94
 
35
95
  ## Install
36
96
 
@@ -40,117 +100,363 @@ npm install behavior-contracts
40
100
 
41
101
  - ESM-only library; TypeScript type declarations are included.
42
102
  - Requires Node.js **22+**.
43
- - No runtime dependencies.
44
-
45
- ## Usage
103
+ - No runtime dependencies. (`typescript` is a build-time-only optional peer, needed by the
104
+ CLI to codegen from a `.ts` authoring module.)
46
105
 
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.
106
+ ---
49
107
 
50
- ### Generate a native module
51
-
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
- ```
108
+ # Section A — For library authors (building a library on bc)
66
109
 
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.
110
+ You are writing the layer that maps your library's own DSL/decorators onto bc. Your decorators
111
+ stay metadata-only collectors; an adapter reads that metadata and lowers each domain operation to
112
+ a bc **behavior** with the SCP authoring API below, and `compileBehaviors` turns those behaviors
113
+ into bc's internal IR. You also **ship one op-agnostic leaf transport per leaf, per language** — so
114
+ your users only declare a model and run it (Section B). Everything in this section is exported from
115
+ the package root (`behavior-contracts`).
71
116
 
72
- ### Generate from the CLI
117
+ ## Author in TypeScript
73
118
 
74
- The package installs a `bc` binary — codegen over the same public API:
119
+ Behaviors are `@behavior` classes (or classes extending `SemanticBehavior`); each public
120
+ method is a root behavior. The input-port bag is the method's `$: In<T>` parameter, and `T`
121
+ is a plain TS type. Numeric precision uses the `Int` / `Float` branded aliases — plain TS
122
+ `number` is **rejected** because it is ambiguous between a 64-bit int and a 64-bit float and
123
+ BC does not infer. Leaves are declared once with `defineLeaf`; its meta carries the leaf's
124
+ **transport symbol name** (the contract name the end user implements). Types are given as TS
125
+ types and canonical PortableType notation only — there is **no `inputPorts` type-struct to
126
+ hand-write**, and a non-canonical notation (e.g. an angle-bracket string like
127
+ `"arr<obj<...>>"`) is rejected loudly at authoring.
75
128
 
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
80
-
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
129
+ ```ts
130
+ import { behavior, defineLeaf, behaviorComponents, SemanticBehavior, type In } from "behavior-contracts";
131
+
132
+ // A leaf is a typed static function. `ports`/`output` are canonical PortableType notation;
133
+ // `transport` fixes the op-agnostic symbol name the leaf transport uses (default: Leaf_<name> /
134
+ // leaf_<name>). The impl body is never touched by `bc generate` — it is the TS run path
135
+ // (interpreter and `lowerBehaviors`); the native languages call the transport of that name.
136
+ const Select = defineLeaf(
137
+ "Select",
138
+ {
139
+ cardinality: "many",
140
+ ports: { sql: "string", email: "string" },
141
+ output: { obj: { id: "int", email: "string" } },
142
+ transport: "Leaf_Select",
143
+ },
144
+ (p, ctx) => runYourQuery(p.sql, p.email),
145
+ );
146
+
147
+ const C = behaviorComponents({ Select });
148
+
149
+ @behavior
150
+ export class UserRepo extends SemanticBehavior {
151
+ findByEmail($: In<{ email: string }>) {
152
+ return C.Select({ sql: "SELECT id, email FROM users WHERE email = ?", email: $.email })
153
+ .as<{ arr: { obj: { id: "int"; email: "string" } } }>({ arr: { obj: { id: "int", email: "string" } } });
154
+ }
155
+ }
83
156
  ```
84
157
 
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
158
+ This authored module is what your library ships (or generates from its own decorator surface); it
159
+ is the `--from <authoring.ts> --behavior <Class>` the `bc` CLI compiles for Go / Rust / Python /
160
+ PHP, and the class `lowerBehaviors` runs directly in TypeScript (Section B). Expression logic inside
161
+ a behavior is built with the closed operator vocabulary
162
+ (`when` / `concat` / `add` / … / `opt` / `coalesce` / `len`); `add` and its siblings are the
163
+ authoring IR builders (distinct from the `codegenPrimitives` the generated code calls).
164
+
165
+ ## Ship the per-language leaf transports
166
+
167
+ For every language your library targets natively, you ship one op-agnostic **leaf transport** per
168
+ leaf — this is the library's job, done once for all its users, so the end user writes none of it. A
169
+ `*-typed-native` module is runtime-free and fully typed: BC owns and generates the concrete wire
170
+ type and all of the strict de-box, so the transport implements **nothing** over it. It is a single
171
+ function, with the spec-fixed name, that reads its inputs from the `WireRow` payload by field name,
172
+ does the raw I/O, and builds a BC-owned `WireValue`:
173
+
174
+ - **Go** — `func <Sym>(payload wire.WireRow) (wire.WireValue, error)`
175
+ - **Rust** — `fn <sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`
176
+
177
+ The **same one transport** serves a leaf across **all** its roles and cardinalities
178
+ (base / GSI / limited / batched / fanout) — divergent port sets are just different payload fields,
179
+ and there is no per-role signature. The generated native hot path stays fully typed; only the leaf
180
+ boundary is wire (de-box once). The default symbol name is `Leaf_<comp>` (Go) / `leaf_<comp>`
181
+ (Rust); `defineLeaf`'s `transport` fixes it, and `--leaf-transport <leaf>=<sym>` can override it.
182
+
183
+ ```go
184
+ package tx
185
+
186
+ import "example.com/app/wire"
187
+
188
+ // One op-agnostic function per leaf. Reads its inputs from the payload by name, does the raw
189
+ // I/O, and builds the BC-owned WireValue. The covered module owns all classification/de-box.
190
+ func Leaf_Select(payload wire.WireRow) (wire.WireValue, error) {
191
+ email := payload.ProbeString("email").Got // the port the covered module bound
192
+ _ = email
193
+ return wire.WireListOf([]wire.WireValue{
194
+ wire.WireRowOf([]wire.WireField{
195
+ {Key: "id", Val: wire.WireInt(1)},
196
+ {Key: "email", Val: wire.WireStr(email)},
197
+ }),
198
+ }), nil
199
+ }
97
200
  ```
98
201
 
99
- Run `bc generate --help` for the full option reference (also generated at `docs/cli-reference.md`).
202
+ `opt` fields are key-omittable (absent → `None`/null); an integer for a `float` slot is widened. A
203
+ type the emitter cannot bake, or an output type inconsistent with its node types, is a
204
+ generation-time error — never silently-broken code. See
205
+ [`docs/strict-typing-and-debox.md`](../docs/strict-typing-and-debox.md) for the full typing + de-box
206
+ contract.
100
207
 
101
- ### Interpret the IR directly
208
+ ### BC-owned wire types & the cross-package / cross-crate layout
102
209
 
103
- ```ts
104
- import { runBehavior } from "behavior-contracts";
210
+ BC generates the concrete wire types. By default they live in the covered module and the transport
211
+ references them back (legal within a single Rust crate or Go package). For a layout where the
212
+ transport lives in its own package/crate, `--shared-types-out` emits the BC-owned wire types (plus
213
+ the batched/fanout batch ports structs; Rust also the shared `BehaviorError`) into a shared
214
+ package/crate, and the covered module imports them via `--shared-types-import` — so the transport
215
+ package returns them with no import cycle (covered → transport → shared). `--leaf-transport-import`
216
+ names where the transport symbols are imported from. The library runs these emits once and ships the
217
+ result:
105
218
 
106
- // Inject boundary handlers; the interpreter walks the portable IR.
107
- const result = runBehavior(ir, handlers, { userId: "u1" }, "UserReads");
219
+ ```bash
220
+ # Go cross-package — emit ONLY the shared wire package (no --out ⇒ no covered module here):
221
+ bc generate --lang go-typed-native --from behaviors.ts --behavior UserRepo \
222
+ --shared-types-out wire/wire.go \
223
+ --shared-types-import example.com/app/wire \
224
+ --leaf-transport-import example.com/app/tx
225
+
226
+ # Rust cross-crate:
227
+ bc generate --lang rust-typed-native --from behaviors.ts --behavior UserRepo \
228
+ --shared-types-out wire/src/lib.rs \
229
+ --shared-types-import bcwire \
230
+ --leaf-transport-import bctx
108
231
  ```
109
232
 
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 |
233
+ Runnable end-to-end samples of the library side + a shared wire seam:
234
+ [`examples/building-a-library-on-bc/`](../examples/building-a-library-on-bc/) (custom decorators →
235
+ SCP + Go/Rust transports), plus the standalone cross-layout samples
236
+ [`examples/go-cross-package/`](../examples/go-cross-package/) (Go, separate transport package),
237
+ [`examples/rust-cross-crate/`](../examples/rust-cross-crate/) (Rust, separate transport crate), and
238
+ [`examples/rust-cross-module/`](../examples/rust-cross-module/) (Rust, intra-crate — no shared crate
239
+ needed).
240
+
241
+ ## Public API reference
242
+
243
+ Everything below is exported from the package root (`behavior-contracts`). Cross-language
244
+ **codegen** is CLI-only — the `bc` binary is the sole public codegen entry, so no emitter appears
245
+ here — but the **compile seam** (`compileBehaviors`, SCP→IR) and the **TS lowering** entry
246
+ (`lowerBehaviors`) are public functions and do appear below.
247
+
248
+ ### Authoring surface
249
+
250
+ The effect-agnostic authoring API. A `@behavior` / `SemanticBehavior` class lowers each
251
+ public method to one component-graph root behavior; leaves are declared with `defineLeaf`;
252
+ port and result types are given as TS types (with the `Int` / `Float` branded aliases and
253
+ canonical PortableType notation).
254
+
255
+ | Export | Kind | Purpose |
256
+ |---|---|---|
257
+ | `SemanticBehavior` | class | Base class a behavior class extends; each public method is a root behavior. |
258
+ | `behavior` | decorator | Marks a class as a behavior module (alternative to extending `SemanticBehavior`). |
259
+ | `defineLeaf` | fn | Declares a leaf: ports/output types, cardinality, and the transport symbol name the end user implements. |
260
+ | `behaviorComponents` | fn | Bundles declared leaves/components into a callable component map used inside behavior bodies. |
261
+ | `catalogComponents` | fn | Builds the component catalog consumed by the runtime/binder from declared components. |
262
+ | `catalogEntryFromLeaf` | fn | Derives a single catalog entry from a leaf definition. |
263
+ | `deriveCatalog` | fn | Derives the full catalog from a set of authored behaviors/leaves. |
264
+ | `referencedComponents` | fn | Lists the components a lowered behavior references (library-side CQRS derivation). |
265
+ | `classifyBehaviorEffect` | fn | Classifies a behavior's effect (read/write) from its lowered graph. |
266
+ | `AuthoringFailure` | error | Thrown for invalid authoring (e.g. non-canonical type, ambiguous `number`). |
267
+ | `when` | builder | Conditional/guard expression builder. |
268
+ | `concat` | builder | String concatenation expression builder. |
269
+ | `add` `sub` `mul` `div` `mod` `neg` | builder | Arithmetic expression builders. |
270
+ | `eq` `ne` `lt` `le` `gt` `ge` | builder | Comparison expression builders. |
271
+ | `and` `or` `not` | builder | Boolean expression builders. |
272
+ | `coalesce` | builder | Null-coalescing expression builder. |
273
+ | `len` | builder | Length expression builder. |
274
+ | `opt` | builder | Marks a port/value as optional (key-omittable) in the type. |
275
+ | `In` | type | Wrapper type for a behavior method's input-port bag (`$: In<T>`). |
276
+ | `Int` / `Float` | type | Branded numeric aliases that disambiguate 64-bit int vs. float (plain `number` is rejected). |
277
+ | `Recorded` | type | Marks a recorded (persisted) value in a behavior signature. |
278
+ | `BehaviorClass` | type | Type of a class usable as a behavior module. |
279
+ | `CompileBehaviorsOptions` | type | Options accepted by the compile seam the CLI drives. |
280
+ | `BehaviorEffect` | type | Effect classification result (read/write). |
281
+ | `AuthoringFailureCode` | type | Discriminant codes for `AuthoringFailure`. |
282
+ | `LeafDefinition` | type | The shape returned by `defineLeaf`. |
283
+ | `LeafMeta` | type | A leaf's declared meta (ports, output, cardinality, transport). |
284
+ | `PortableTypeToTs` / `PortsToTs` | type | Type-level maps from canonical PortableType notation to TS types. |
285
+
286
+ ### Compile & lower
287
+
288
+ The public compile seam (SCP → bc's internal IR) and the TypeScript lowering entry (compile → run
289
+ in memory at native JS speed).
290
+
291
+ | Export | Kind | Purpose |
292
+ |---|---|---|
293
+ | `compileBehaviors` | fn | Compiles a `@behavior` / `SemanticBehavior` class (SCP closures only) to bc's internal component-graph IR — the single canonical IR producer, shared by the interpreter, `lowerBehaviors`, and the `bc generate --from` CLI. Rejects raw IR / a non-behavior input (`NOT_A_BEHAVIOR_CLASS`). |
294
+ | `lowerBehaviors` | fn (async) | Lowers a behavior class in memory to directly-callable, native-JS-speed closures — no interpreter, no explicit codegen step, zero runtime deps. Leaf impls link automatically from `defineLeaf`; the only injection is `ctx`. Returns a `LoweredBehaviors`. |
295
+ | `LoweredBehaviors` | type | The result of `lowerBehaviors`: `{ sync, async }`, each a `{ method: (input) => output }` map of lowered direct-call closures (the `async` twin awaits async leaf impls). |
296
+
297
+ ### Interpreter runtime
298
+
299
+ The shared runtime that walks a compiled behavior (the TS/Python/PHP path).
300
+
301
+ | Export | Kind | Purpose |
302
+ |---|---|---|
303
+ | `runBehavior` | fn | Executes a compiled component-graph behavior with injected boundary handlers. |
304
+ | `runBehaviorAsync` | fn | Async variant of `runBehavior`. |
305
+ | `BehaviorFailure` | error | Thrown for a runtime behavior failure (carries structured detail). |
306
+ | `fanoutDedupDrop` | fn | Fan-out dedup/drop helper for fan-out result shaping. |
307
+ | `portableTypeNotation` | fn | Canonicalizes/serializes a type into portable notation. |
308
+ | `conformResultToOutType` | fn | Conforms a handler result to the declared output type. |
309
+ | `FanoutDedupDropSpec` | type | Spec for `fanoutDedupDrop`. |
310
+ | `PortSchema` | type | Declared schema of a component's ports. |
311
+ | `PortableType` / `PortableScalarType` | type | The portable type model (composite and scalar). |
312
+ | `CatalogEntry` / `CatalogOutput` / `Catalog` | type | Component catalog types consumed by the runtime. |
313
+ | `Handler` / `AsyncHandler` | type | A boundary handler (sync/async) for a component. |
314
+ | `Handlers` / `AsyncHandlers` | type | A map of handlers keyed by component. |
315
+ | `HandlerCtx` | type | The environment/context passed to a handler. |
316
+ | `BehaviorFailureCode` | type | Discriminant codes for `BehaviorFailure`. |
317
+
318
+ ### Bind
319
+
320
+ | Export | Kind | Purpose |
321
+ |---|---|---|
322
+ | `bindBehaviors` | fn | Binds registered leaf impls to a compiled catalog after a completeness gate, yielding a dispatchable set. |
323
+ | `BindFailure` | error | Thrown when binding is incomplete/invalid. |
324
+ | `BoundBehaviors` | type | The dispatchable result of `bindBehaviors`. |
325
+ | `BindFailureCode` | type | Discriminant codes for `BindFailure`. |
326
+
327
+ ### Provenance & IR handle
328
+
329
+ The runtime-side provenance gate and the branded IR handle types used by generated
330
+ interpreter modules.
331
+
332
+ | Export | Kind | Purpose |
333
+ |---|---|---|
334
+ | `assertCompiled` | fn | Asserts a value carries a valid compile-provenance token (fail-closed on tampered/stale). |
335
+ | `loadCompiledIR` | fn | Adopts a serialized `ComponentGraphIRDoc` into a branded `ComponentGraphIR` handle (used by generated `--lang typescript` modules at load). |
336
+ | `fingerprintComponentGraph` | fn | Provenance-gated canonical fingerprint of a component graph. |
337
+ | `ProvenanceError` | error | Thrown on a provenance/fingerprint mismatch. |
338
+ | `ComponentGraphIR` | type | Branded root handle for a compiled component graph. |
339
+ | `ComponentGraphIRDoc` | type | Serialized document form of a compiled component graph (embedded literal in generated interpreter modules). |
340
+
341
+ ### Plan
342
+
343
+ The portable execution-plan runtime (stage grouping, concurrency, skip propagation, error
344
+ policy).
345
+
346
+ | Export | Kind | Purpose |
347
+ |---|---|---|
348
+ | `runPlan` | fn | Executes a portable execution-plan IR. |
349
+ | `runPlanAsync` | fn | Async variant of `runPlan`. |
350
+ | `finalTree` | fn | Builds the final result tree from a plan run. |
351
+ | `PlanFailure` | error | Thrown for a plan execution failure. |
352
+ | `POLICY_KINDS` | const | Closed set of policy kinds. |
353
+ | `RELATION_KINDS` | const | Closed set of relation kinds. |
354
+ | `ELEMENT_POLICY_KINDS` | const | Closed set of per-element error-policy kinds (`error` / `skip`). |
355
+ | `ERROR_KINDS` | const | Closed set of error kinds. |
356
+ | `ExecutionPlanSpec` / `OpSpec` | type | The plan and per-op spec shapes. |
357
+ | `Exec` / `AsyncExec` | type | The executor callback types. |
358
+ | `ExecOutcome` / `RunResult` | type | Per-op outcome and overall run result. |
359
+ | `PolicyKind` / `RelationKind` / `ElementPolicyKind` / `ErrorKind` | type | Element types of the corresponding `*_KINDS` sets. |
360
+ | `ErrorDetail` | type | Structured error detail carried by a failure. |
361
+ | `PlanFailureCode` | type | Discriminant codes for `PlanFailure`. |
362
+
363
+ ### Type gate
364
+
365
+ | Export | Kind | Purpose |
366
+ |---|---|---|
367
+ | `UntypedNodeError` | error | Thrown when a node/output type is not uniquely determined (fail-closed; guarantees end-to-end typed-flat codegen). |
368
+
369
+ ### Guard / portability
370
+
371
+ | Export | Kind | Purpose |
372
+ |---|---|---|
373
+ | `assertPortable` | fn | Fail-closed structural validation that a value is portable IR. |
374
+ | `assertPortableComponentGraph` | fn | Portability guard specialized for a component graph. |
375
+ | `assertPortableTypeNotation` | fn | Validates a type notation is canonical/portable. |
376
+ | `PORTABLE_EXPR_OPERATORS` | const | The closed set of portable expression operators. |
377
+ | `PORTABLE_SCALAR_TYPES` | const | The closed set of portable scalar types. |
378
+ | `PortabilityError` | error | Thrown on a portability violation. |
379
+
380
+ ### Operator type signatures
381
+
382
+ The SSoT for the closed expression vocabulary's input/output types (read by the type gate,
383
+ never re-derived ad hoc).
384
+
385
+ | Export | Kind | Purpose |
386
+ |---|---|---|
387
+ | `OPERATOR_TYPE_SIGNATURES` | const | The declared input/output type signatures for every operator. |
388
+ | `operatorSignature` | fn | Looks up the signature for an operator. |
389
+ | `resolveOperatorResult` | fn | Resolves an operator's result type from its operand types. |
390
+ | `isValueOperator` | fn | Whether an operator produces a value (vs. a predicate). |
391
+ | `OperatorSignature` / `OperatorResultRule` / `OperandConstraint` | type | The signature model types. |
392
+
393
+ ### Expression evaluation
394
+
395
+ | Export | Kind | Purpose |
396
+ |---|---|---|
397
+ | `evaluateExpression` | fn | Evaluates the portable expression IR (regnant semantics). |
398
+ | `encodeValue` | fn | Encodes a value for the expression evaluator. |
399
+ | `cmpCodePoints` | fn | Deterministic code-point string comparison. |
400
+ | `ExprFailure` | error | Thrown for an expression evaluation failure. |
401
+ | `FORBIDDEN_OBJECT_KEY` | const | The object key forbidden in values (prototype-pollution guard). |
402
+ | `Value` / `Scope` | type | The value model and evaluation scope. |
403
+ | `ExprFailureCode` | type | Discriminant codes for `ExprFailure`. |
404
+
405
+ ### Template rendering
406
+
407
+ | Export | Kind | Purpose |
408
+ |---|---|---|
409
+ | `renderTemplate` | fn | Pure strict `{param}` string substitution. |
410
+ | `resolvePartial` | fn | Resolves a partial/nested template reference. |
411
+ | `TemplateFailure` | error | Thrown for a template rendering failure. |
412
+ | `TemplateFailureCode` | type | Discriminant codes for `TemplateFailure`. |
413
+
414
+ ### Canonical serialization
415
+
416
+ | Export | Kind | Purpose |
417
+ |---|---|---|
418
+ | `canonicalValue` | fn | Deterministic canonical value normalization (sorted keys, typed values). |
419
+ | `canonicalJson` | fn | Canonical JSON serialization (compact, canonical floats). |
420
+ | `pyFloatRepr` | fn | Canonical decimal float representation (Python-compatible). |
421
+ | `CanonicalFailure` | error | Thrown for a canonicalization failure. |
422
+ | `CanonicalFailureCode` | type | Discriminant codes for `CanonicalFailure`. |
423
+
424
+ ### Envelope
425
+
426
+ | Export | Kind | Purpose |
427
+ |---|---|---|
428
+ | `validateEnvelope` | fn | Fail-closed spec-version validation of an envelope (loud-rejects unknown versions). |
429
+ | `EnvelopeFailure` | error | Thrown for an envelope validation failure. |
430
+ | `EnvelopeFailureCode` | type | Discriminant codes for `EnvelopeFailure`. |
431
+
432
+ ### Codec (conformance adapter)
433
+
434
+ | Export | Kind | Purpose |
435
+ |---|---|---|
436
+ | `decodeValue` | fn | Decodes an encoded value (conformance runner adapter). |
437
+ | `deepEquals` | fn | Deterministic deep equality (conformance runner adapter). |
438
+
439
+ ### Codegen primitives (called by generated code)
440
+
441
+ The stable primitive surface generated code calls directly. Individual expression operators
442
+ are bundled in the `codegenPrimitives` namespace (thin wrappers delegating to
443
+ `evaluateExpression`) to avoid colliding with the same-named authoring IR builders.
444
+
445
+ | Export | Kind | Purpose |
446
+ |---|---|---|
447
+ | `codegenPrimitives` | namespace | The bundled per-operator primitive functions generated code calls. |
448
+ | `mapWithConcurrency` | fn | Bounded-concurrency map helper used by generated plans. |
449
+ | `unproducedValue` | fn | Sentinel for an unproduced value. |
450
+ | `skipSingle` / `skipConnection` | fn | Skip sentinels for single / connection results. |
451
+ | `hydrateInto` | fn | Hydration helper used by generated code. |
452
+ | `Expr` | type | The expression node type accepted by the primitives. |
453
+
454
+ ### Constants
455
+
456
+ | Export | Kind | Purpose |
457
+ |---|---|---|
458
+ | `SPEC_VERSIONS` | const | The IR/vector spec versions this package supports (independent of the library semver). |
459
+ | `ENVELOPE_SPEC_VERSION` | const | The default supported envelope spec version (`"<major>.<minor>"`). |
154
460
 
155
461
  ## Spec versions
156
462
 
@@ -169,6 +475,119 @@ library (semver) version:
169
475
  | provenance | 1 |
170
476
  | envelope | 1.1 |
171
477
 
478
+ ---
479
+
480
+ # Section B — For users of a library built on bc
481
+
482
+ You are using a library (e.g. litedbmodel or graphddb) that was built on bc. You never write bc
483
+ `@behavior` classes, leaf transports, or IR — the library already did all of that (Section A). You
484
+ **declare a model** with the library's surface, then **run it**.
485
+
486
+ ## 1. Define your model with the library's surface
487
+
488
+ You describe your model with the **library's own surface** — its decorators, its schema DSL, whatever
489
+ it exposes. bc does **not** dictate this; the library does. The library's authoring (Section A)
490
+ already turned its surface into bc behaviors, so declaring a model and naming an operation in one
491
+ behavior method is your whole domain-level job.
492
+
493
+ ## 2a. Run it in TypeScript — `lowerBehaviors`, directly
494
+
495
+ In TypeScript the model runs **in-process** at native JS speed. `lowerBehaviors(Model)` compiles the
496
+ behavior and lowers it in memory to directly-callable closures — no interpreter, no `bc generate`
497
+ step, no generated file, zero runtime deps. The library's leaf impls link automatically:
498
+
499
+ ```ts
500
+ import { lowerBehaviors } from "behavior-contracts";
501
+ import { UserRepo } from "./model.ts"; // your model, declared with the library's decorators
502
+
503
+ const repo = await lowerBehaviors(UserRepo); // lower once
504
+ const rows = repo.sync.findByEmail({ email: "a@b.c" }); // call the returned closure directly
505
+ // rows === [{ id: 1n, email: "a@b.c" }] (int is a bigint in bc's value model)
506
+ ```
507
+
508
+ `lowerBehaviors` returns `{ sync, async }` — the `async` twin awaits async leaf impls. Runnable
509
+ sample: [`examples/using-a-bc-library/run-ts.mjs`](../examples/using-a-bc-library/run-ts.mjs).
510
+
511
+ ## 2b. Run it in Go / Rust / Python / PHP — `bc generate`
512
+
513
+ For the other languages the `behavior-contracts` package installs a `bc` binary you run **yourself**
514
+ (not through the library). `bc generate --from <model.ts> --behavior <Class>` imports the module,
515
+ type-extracts each method's `$: In<T>` type via the TypeScript compiler, and compiles ts → ir →
516
+ native (Go / Rust) or a shared-runtime interpreter module (Python / PHP) in **one pass**. You wire it
517
+ to the library's shipped leaf transports + BC-owned wire types with `--leaf-transport-import` /
518
+ `--shared-types-import` — you write neither; the library ships them (Section A):
519
+
520
+ ```bash
521
+ # Go — native, wired to the library's transport + wire packages:
522
+ bc generate --lang go-typed-native --from model.ts --behavior UserRepo \
523
+ --out go/behaviors/covered.go --shared-types-import bcorm/wire --leaf-transport-import bcorm/tx
524
+
525
+ # Rust — native:
526
+ bc generate --lang rust-typed-native --from model.ts --behavior UserRepo \
527
+ --out rust/src/behaviors.rs --shared-types-import bcorm_wire --leaf-transport-import bcorm_tx
528
+
529
+ # Python / PHP — the shared-runtime interpreter module:
530
+ bc generate --lang python --from model.ts --behavior UserRepo --out behaviors_generated.py
531
+ bc generate --lang php --from model.ts --behavior UserRepo --out BehaviorsGenerated.php
532
+
533
+ # Drift gate — non-zero exit if the committed --out differs from a fresh generation:
534
+ bc check --lang go-typed-native --from model.ts --behavior UserRepo --out go/behaviors/covered.go
535
+ ```
536
+
537
+ Full flag reference: `bc generate --help` (also generated at
538
+ [`docs/cli-reference.md`](./docs/cli-reference.md)). `--in <ir-doc.json>` is an internal/advanced
539
+ input; the consumer surface is `--from`.
540
+
541
+ ## 3. Call the generated entry point
542
+
543
+ The covered module exposes a typed entry function per behavior: you pass a typed input struct and get
544
+ a typed output struct back. The transport + wire wiring is **automatic** — baked into the covered
545
+ module at generate time by the import flags — so there is no runtime injection at the call site, and
546
+ the covered module de-boxes the leaf's wire result **once** into the concrete typed output:
547
+
548
+ ```go
549
+ // go — the wiring to bcorm/tx + bcorm/wire is baked in; the call is just typed-in, typed-out.
550
+ rows, err := behaviors.RunNativeRawStruct_findByEmail(behaviors.In_findByEmail{Email: "a@b.c"})
551
+ ```
552
+ ```rust
553
+ // rust
554
+ let rows = run_native_raw_struct_findByEmail(InNRFindByEmail { email: "a@b.c".to_string() })?;
555
+ ```
556
+
557
+ A `--lang python` / `--lang php` module runs on the shared runtime with the IR embedded. A
558
+ `--lang typescript` interpreter module (an alternative to `lowerBehaviors` when you want an emitted
559
+ file) embeds the compiled IR as a `ComponentGraphIRDoc` literal and adopts it at load with
560
+ `loadCompiledIR`, then `runBehavior` walks it.
561
+
562
+ The complete, runnable end-user example — one model, with the TypeScript `lowerBehaviors` run and the
563
+ Go / Rust `bc generate` runs all printing the same row — is
564
+ [`examples/using-a-bc-library/`](../examples/using-a-bc-library/).
565
+
566
+ ---
567
+
568
+ ## Documentation
569
+
570
+ Deeper design and specification documents live alongside the package in the repository:
571
+
572
+ - [`docs/cli-reference.md`](./docs/cli-reference.md) — the full `bc generate` / `bc check`
573
+ option reference.
574
+ - [`docs/strict-typing-and-debox.md`](../docs/strict-typing-and-debox.md) — mandatory typing,
575
+ the strict de-box, the BC-owned wire type, and the leaf transport (the full contract for the
576
+ above).
577
+ - [`docs/concept.md`](../docs/concept.md) — the concept and specification overview.
578
+ - [`docs/expression-ir.md`](../docs/expression-ir.md) — the Expression IR: the closed set of
579
+ permitted operators and their evaluation semantics.
580
+ - [`docs/canonical-serialization.md`](../docs/canonical-serialization.md) — canonical
581
+ serialization rules (key sort order, typed-value encoding, canonical float representation).
582
+ - [`docs/template-rendering.md`](../docs/template-rendering.md) — template binding / rendering
583
+ rules.
584
+ - [`docs/execution-plan.md`](../docs/execution-plan.md) — execution-plan semantics (stage
585
+ groups, concurrency, skip propagation, error policy).
586
+ - [`docs/INTEGRATION.md`](../docs/INTEGRATION.md) — integration guide for consuming the runtime
587
+ across languages.
588
+ - [`examples/`](../examples/) — minimal, dependency-free, build-free runnable samples plus the
589
+ Expression IR reference evaluator and golden vectors.
590
+
172
591
  ## License
173
592
 
174
593
  MIT — see [LICENSE](./LICENSE).