1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
--- alc_shapes.instrument — Malli-style declarative shape instrumentation.
---
--- Wraps a module entry (e.g. `M.run`) with dev-mode shape assertions
--- driven by `M.spec.entries[entry_name].{input, result}`, replacing the
--- manual pattern:
---
--- ```lua
--- function M.run(ctx) ... ; S.assert_dev(ctx.result, "voted", "sc.run"); return ctx end
--- ```
---
--- with:
---
--- ```lua
--- function M.run(ctx) ... ; return ctx end
--- M.run = S.instrument(M, "run") -- at module tail
--- ```
---
--- ## Why a wrapper layer exists
---
--- The goal is **caller transparency**: recipe and downstream callers
--- should not need to know that shape checking exists. Three analogues
--- converge on this shape:
---
--- - **Malli `mi/instrument!`** (Clojure) — rewrites a `var` to a dev-
--- gated wrapper derived from a function schema. Production code keeps
--- calling `(my.ns/do-thing x)` unchanged; instrumentation is applied
--- at the var level so every caller gets validation for free. Source:
--- `https://github.com/metosin/malli/blob/master/docs/function-schemas.md`.
--- - **Zod v4 `z.function({ input, output }).implement(fn)`** — factory
--- returns a wrapped function. `fn` becomes the body; the wrapper
--- parses input and output on each call. Source:
--- `https://zod.dev/api#function` (v4 function API, 2025).
--- - **tRPC procedure builder** — input/output validators are declared
--- at the route; the builder wraps the handler so it only ever sees
--- validated data. Source: `https://trpc.io/docs/server/validators`.
---
--- All three enforce the boundary **once**, at the edge of the module,
--- by returning a replacement function. Caller-side wrapping (each
--- consumer inserts its own assert) is explicitly rejected as a Hyrum-
--- law hazard.
---
--- ## Relationship to spec_resolver.run
---
--- `spec_resolver.run(pkg, ctx)` is the **caller-wrap** form: consumers
--- that do not trust the pkg to self-validate route the call through
--- `SR.run` for a resolver-side pre/post check. `instrument` is the
--- **producer-wrap** form: the pkg self-decorates its entry once, and
--- every caller (`pkg.run(ctx)` direct, `SR.run(pkg, ctx)` via resolver,
--- or anything else) inherits the check for free. Both forms coexist;
--- bundled pkgs prefer `instrument` because it makes the producer the
--- single source of truth for its own contract.
---
--- ## Alc-specific adaptation
---
--- Two entry paradigms coexist. The declaration shape decides which
--- wrapper path runs.
---
--- ### (1) ctx-threading (default; `spec.entries.{e}.input`)
---
--- Every entry takes a single `ctx` table, writes `ctx.result = {...}`,
--- returns `ctx`. Applies to 90%+ of bundled pkgs.
---
--- - **Input** assertion targets the first positional argument (`ctx`).
--- Reads `M.spec.entries[entry_name].input` (string registry key or
--- inline schema; string is coerced to `T.ref` by `spec_resolver.resolve`).
--- - **Result** assertion targets `ret.result` (ctx-threading), falling
--- back to `ret` itself when the function does not return a table with
--- `.result` set. Reads `M.spec.entries[entry_name].result`.
---
--- ### (2) direct-args (library-style; `spec.entries.{e}.args`)
---
--- Pure library-style pkgs (e.g. `bft.threshold(n, f) -> number`,
--- `kemeny.aggregate(rankings) -> ranking`) take positional args and
--- return a raw value. `args` is an **array of shapes** aligned to the
--- function's positional parameters; the wrapper checks each `args[i]`
--- against the caller-supplied i-th argument.
---
--- - **Input** assertion: for each `args[i]` (non-nil slot), asserts the
--- caller's i-th argument. Slots may be `nil` to skip validation at
--- that position (useful for opaque options tables).
--- - **Result** assertion targets the **raw return value** (not
--- `ret.result`) — library functions return scalars / tables directly.
--- - **Optional args** use `T.x:is_optional()` at the corresponding slot;
--- the check handler accepts nil for optional schemas at top level.
---
--- `input` and `args` are mutually exclusive per entry. `spec_resolver`
--- raises at declaration time when both are set, so the wrapper body
--- only needs to branch on one side.
---
--- ### Shared
---
--- - **Hint** is `"<meta.name>.<entry_name>"`, e.g. `"calibrate.assess"`
--- or `"bft.threshold"`. Arg-position hints append `":arg<i>"`.
--- - **Gating** is `ALC_SHAPE_CHECK=1` (existing dev-mode env var). When
--- off, the wrapper only pays one `os.getenv` per call.
---
--- ## Override form (rare)
---
--- Most packages declare every entry under `M.spec.entries.*` so no
--- override is needed. The optional `spec` argument exists as an escape
--- hatch for callers that want to instrument an entry not declared in
--- `M.spec` (e.g. temporary test scaffolding):
---
--- ```lua
--- -- ctx-threading override:
--- M.custom = S.instrument(M, "custom", {
--- input = T.shape({ task = T.string }, { open = true }),
--- result = "voted",
--- })
---
--- -- direct-args override:
--- M.threshold = S.instrument(M, "threshold", {
--- args = { T.number, T.number },
--- result = T.number,
--- })
--- ```
---
--- `spec` takes precedence over `M.spec.entries[entry_name].*` when both
--- are given. This matches Zod's `.implement({ input, output })` which
--- lets the caller override the schemas declared on the factory.
--- Specifying `input` and `args` together (either via the spec override
--- or via `M.spec.entries.{e}.*`) is rejected at load time.
local check = require
local spec_resolver = require
local M =
--- Wrap `mod[entry_name]` with dev-mode shape assertions.
---
--- Idempotent in dev-off mode: the wrapper calls `is_dev_mode()` once
--- per invocation and short-circuits before any schema work when off.
---
--- Loud-fails at load time when:
--- • `mod.meta.name` is missing (needed for the hint),
--- • `mod[entry_name]` is not a function (must be called AFTER the
--- function is defined — typical usage is at the module tail).
---
---@param mod table Module being instrumented.
---@param entry_name string Entry function name, e.g. "run".
---@param spec? { input?: table|string|nil, result?: table|string|nil }
---@return function Replacement function with identical call signature.
return M