@lunora/codegen 1.0.0-alpha.9 → 1.0.0-alpha.90

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 (76) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/index.d.mts +2722 -931
  3. package/dist/index.d.ts +2722 -931
  4. package/dist/index.mjs +1 -29
  5. package/dist/packem_shared/AGENTS_FILENAME-BesaDYkL.mjs +1 -0
  6. package/dist/packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs +1 -0
  7. package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +1 -0
  9. package/dist/packem_shared/FLAGS_FILENAME-CHaH6obH.mjs +1 -0
  10. package/dist/packem_shared/GENERATED_HEADER-CUBdTCVk.mjs +1 -0
  11. package/dist/packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs +1 -0
  12. package/dist/packem_shared/MUTATORS_FILENAME-DY3rgWGl.mjs +1 -0
  13. package/dist/packem_shared/NOTIFY_FILENAME-CDvoTY3Y.mjs +1 -0
  14. package/dist/packem_shared/OPENRPC_VERSION-aq5eyIkd.mjs +3 -0
  15. package/dist/packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs +1 -0
  16. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-ChA6rpGP.mjs +9 -0
  17. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs +2 -0
  18. package/dist/packem_shared/SHAPES_FILENAME-BdLj5-mD.mjs +1 -0
  19. package/dist/packem_shared/SchemaSnapshotParseError-BJkhTEpi.mjs +16 -0
  20. package/dist/packem_shared/WORKFLOWS_FILENAME-ClsYRKXp.mjs +1 -0
  21. package/dist/packem_shared/buildOpenApiDocument-Bw3MChvT.mjs +3 -0
  22. package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +1 -0
  23. package/dist/packem_shared/discover-ast-CezKqEhE.mjs +1 -0
  24. package/dist/packem_shared/discover-queries-BmZeJ--u.mjs +1 -0
  25. package/dist/packem_shared/discoverAuthApiCalls-BgL6nj03.mjs +1 -0
  26. package/dist/packem_shared/discoverCrons-WJscxQFl.mjs +1 -0
  27. package/dist/packem_shared/discoverFunctions-BgGmxEqW.mjs +1 -0
  28. package/dist/packem_shared/discoverHttpRoutes-eW8RbVOr.mjs +1 -0
  29. package/dist/packem_shared/discoverInserts-BCz6zpI0.mjs +1 -0
  30. package/dist/packem_shared/discoverMaskProcedures-DLfQRsQc.mjs +1 -0
  31. package/dist/packem_shared/discoverMigrations-Cbc4W765.mjs +1 -0
  32. package/dist/packem_shared/discoverNondeterministicCalls-x9IhWxPP.mjs +1 -0
  33. package/dist/packem_shared/discoverQueries-Cf0LGoQG.mjs +1 -0
  34. package/dist/packem_shared/discoverR2sqlCalls--MSfSeDm.mjs +1 -0
  35. package/dist/packem_shared/discoverRlsMetadata-DTRS0ROc.mjs +1 -0
  36. package/dist/packem_shared/discoverSandboxUsage-BDyeyuYo.mjs +1 -0
  37. package/dist/packem_shared/discoverSchema-DSJSX4Ss.mjs +1 -0
  38. package/dist/packem_shared/discoverStorageRulesMetadata-Cic97L-2.mjs +1 -0
  39. package/dist/packem_shared/emit-DMvG162j.mjs +2310 -0
  40. package/dist/packem_shared/emitApp--dJ6EnFn.mjs +524 -0
  41. package/dist/packem_shared/formatAdvisories-BCEfzLT0.mjs +2 -0
  42. package/dist/packem_shared/module-specifiers-8FEEiUcv.mjs +1 -0
  43. package/dist/packem_shared/parse-validator-CkLxY-Mr.mjs +1 -0
  44. package/dist/packem_shared/paths-BmX5O1sG.mjs +1 -0
  45. package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +1 -0
  46. package/dist/packem_shared/redact-6jD4lAhq.mjs +1 -0
  47. package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +1 -0
  48. package/package.json +12 -7
  49. package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
  50. package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
  51. package/dist/packem_shared/GENERATED_HEADER-LceqJ_qp.mjs +0 -2688
  52. package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
  53. package/dist/packem_shared/OPENRPC_VERSION-s7lhywUr.mjs +0 -60
  54. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-Ct0NDRLY.mjs +0 -937
  55. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DzLDbWk3.mjs +0 -233
  56. package/dist/packem_shared/WORKFLOWS_FILENAME-D62dcBGg.mjs +0 -84
  57. package/dist/packem_shared/buildOpenApiDocument-DSPTssJI.mjs +0 -183
  58. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  59. package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
  60. package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
  61. package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
  62. package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
  63. package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
  64. package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
  65. package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
  66. package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
  67. package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
  68. package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
  69. package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
  70. package/dist/packem_shared/discoverSchema-BF6L4mrU.mjs +0 -795
  71. package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
  72. package/dist/packem_shared/emitApp-CDg72pVv.mjs +0 -599
  73. package/dist/packem_shared/formatAdvisories-8NIv1k0I.mjs +0 -69
  74. package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
  75. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  76. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
package/dist/index.d.ts CHANGED
@@ -1,14 +1,137 @@
1
- import { Finding } from '@lunora/advisor';
1
+ import { AdvisorExportSink, AdvisorGeoIndexUsage, AdvisorNotifyCall, AdvisorNotifyConfig, Finding, LintContext, AdvisorProcedureProtection } from '@lunora/advisor';
2
2
  export type { Finding } from '@lunora/advisor';
3
- import { Node, Project } from 'ts-morph';
4
- import { StudioFeaturesResult } from '@lunora/do';
3
+ import '@lunora/platform';
4
+ import { Project, Node } from 'ts-morph';
5
+ import { LunoraError } from '@lunora/errors';
6
+ export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolution, type SolutionRule as LunoraSolutionRule, findSolutionByMessage as findLunoraSolution } from '@lunora/errors';
7
+ import { StudioFeaturesResult } from '@lunora/shard-engine';
5
8
  import { Schema } from '@lunora/server';
6
9
  import { JsonSchema } from '@lunora/values';
7
10
  /**
8
- * AST-observable subset of a column's modifier chain (`.unique()`, `.default()`,
9
- * …). Function-valued modifiers (`.$defaultFn`/`.$onUpdateFn`) can't be
10
- * serialized, so only their *presence* is recorded.
11
- */
11
+ * The structural schema-snapshot format and its diff, shared by `@lunora/codegen`
12
+ * (which builds snapshots from the parsed schema IR and gates deploys on the
13
+ * diff) and `@lunora/studio` (which renders the same diff as a visual migration
14
+ * history).
15
+ *
16
+ * Having ONE diff is the point: the Studio's schema-history view and the
17
+ * pre-deploy drift gate must classify a change identically, or the UI will say a
18
+ * change is safe while `lunora deploy` refuses it. `@lunora/codegen` is a
19
+ * build-time package the browser bundle cannot import, and neither package sits
20
+ * below the other, so — like `shared/quote-identifier.ts` — this lives outside
21
+ * both and is bundler-inlined into each. Keep it genuinely zero-dependency
22
+ * (relative/built-in imports only) or inlining breaks. Consumers must drop
23
+ * `outDir`/`rootDir` from their `tsconfig.json` (a set `rootDir` raises TS6059
24
+ * for this out-of-package file under `tsc --noEmit`).
25
+ *
26
+ * What stays in `@lunora/codegen`: building a snapshot from `SchemaIR`, the
27
+ * `SchemaSnapshotParseError` class (it extends `LunoraError`), and the deploy
28
+ * gate's policy (`evaluateSchemaDrift`). What lives here: the format, the diff,
29
+ * the severity classification, and the content hash.
30
+ */
31
+ /** Current snapshot format version. Bumped if the structural shape below changes. */
32
+ declare const SCHEMA_SNAPSHOT_VERSION: 1;
33
+ /** A single field's structural shape: its value kind and whether it is optional. */
34
+ interface FieldSnapshot {
35
+ /** The validator kind (`string`, `number`, `id`, `object`, …) after unwrapping `v.optional`. */
36
+ kind: string;
37
+ /** True when declared `v.optional(...)` — accepts `undefined` / absent on insert. */
38
+ optional: boolean;
39
+ }
40
+ /** A single secondary index's structural shape. */
41
+ interface IndexSnapshot {
42
+ fields: ReadonlyArray<string>;
43
+ unique: boolean;
44
+ }
45
+ /** A single relation's structural shape. */
46
+ interface RelationSnapshot {
47
+ field: string;
48
+ kind: "many" | "one";
49
+ table: string;
50
+ }
51
+ /** Structural snapshot of one table. */
52
+ interface TableSnapshot {
53
+ /** Field name → {@link FieldSnapshot}, in declared order. */
54
+ fields: Record<string, FieldSnapshot>;
55
+ /** Index name → {@link IndexSnapshot}. */
56
+ indexes: Record<string, IndexSnapshot>;
57
+ /** Relation accessor name → {@link RelationSnapshot}. */
58
+ relations: Record<string, RelationSnapshot>;
59
+ /**
60
+ * `"root"` (default single-DO), `"global"` (D1-replicated), or
61
+ * `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
62
+ * stays a plain JSON-stable value.
63
+ */
64
+ shardMode: string;
65
+ }
66
+ /** A deterministic structural view of the whole schema at one point in time. */
67
+ interface SchemaSnapshot {
68
+ /**
69
+ * Cloudflare DO data-residency jurisdiction declared via `.jurisdiction("…")`,
70
+ * or absent. Tracked because changing it strands all existing Durable Object
71
+ * data (a DO name maps to a different ID per jurisdiction). Optional, so old
72
+ * baselines written before this field parse cleanly (absent ⇒ undefined).
73
+ *
74
+ * Typed as a plain `string` (not the authoring union) on purpose: this is
75
+ * STORED data that a newer Lunora may have written with a jurisdiction this
76
+ * version doesn't yet know. Preserving the raw value keeps the breaking
77
+ * `changedJurisdiction` diff correct under a downgrade — coercing an unknown
78
+ * value to `undefined` would fail OPEN and hide the most destructive change.
79
+ */
80
+ jurisdiction?: string;
81
+ /** Sorted list of every declared `defineMigration` id at capture time. */
82
+ migrationIds: ReadonlyArray<string>;
83
+ /** Table name → {@link TableSnapshot}, keys sorted for stable serialization. */
84
+ tables: Record<string, TableSnapshot>;
85
+ version: typeof SCHEMA_SNAPSHOT_VERSION;
86
+ }
87
+ /**
88
+ * Whether a change is anchored to one table's own shape, or to the schema as a
89
+ * whole.
90
+ *
91
+ * This is the signal a UI needs to decide which tables to mark as changed, and
92
+ * it lives HERE — next to the change union it classifies — rather than as a
93
+ * hand-maintained set of type names in the consumer. A set in the consumer gives
94
+ * zero compile-time pressure: adding a variant to `DriftChange["type"]` would
95
+ * silently render an affected table as untouched, which is exactly the
96
+ * UI-disagrees-with-the-deploy-gate divergence this module exists to prevent.
97
+ */
98
+ type DriftScope = "schema" | "table";
99
+ /** One classified structural change between two snapshots. */
100
+ interface DriftChange {
101
+ /**
102
+ * `"table"` means this table's own DDL moved (fields, indexes, shard mode) —
103
+ * a relation whose foreign key lives on the OTHER table stays `"schema"`, so
104
+ * the "changed" signal keeps meaning "this table's shape moved".
105
+ */
106
+ scope: DriftScope;
107
+ /** `"breaking"` changes need a data migration; `"safe"` changes are additive. */
108
+ severity: "breaking" | "safe";
109
+ /** Human-readable, actionable description (used in the gate message). */
110
+ summary: string;
111
+ /** The table this change belongs to. Always set when `scope` is `"table"`. */
112
+ table?: string;
113
+ /** A machine-readable change discriminator. */
114
+ type: "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedIndex" | "changedJurisdiction" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "removedField" | "removedIndex" | "removedRelation" | "removedTable";
115
+ }
116
+ /** The result of diffing two snapshots: every classified change. */
117
+ interface SchemaDrift {
118
+ /** Every classified change, in a stable order (added/changed per table, then removals). */
119
+ changes: ReadonlyArray<DriftChange>;
120
+ }
121
+ /** Serialize a snapshot to the exact bytes written to `lunora/.lunora-schema.json` (trailing newline). */
122
+ declare const serializeSchemaSnapshot: (snapshot: SchemaSnapshot) => string;
123
+ /**
124
+ * Diff the current snapshot against a baseline and classify every structural
125
+ * change. Pure — no I/O. When `baseline` is `undefined` (no snapshot yet) there
126
+ * is no drift to report: every table is treated as a fresh additive
127
+ * `addedTable`, so a first deploy is never blocked.
128
+ */
129
+ declare const diffSchemaSnapshots: (baseline: SchemaSnapshot | undefined, current: SchemaSnapshot) => SchemaDrift;
130
+ /**
131
+ * AST-observable subset of a column's modifier chain (`.unique()`, `.default()`,
132
+ * …). Function-valued modifiers (`.$defaultFn`/`.$onUpdateFn`) can't be
133
+ * serialized, so only their *presence* is recorded.
134
+ */
12
135
  interface ColumnMetaIR {
13
136
  /** `.default(...)` or `.$defaultFn(...)` present — field is optional on insert. */
14
137
  hasDefault?: boolean;
@@ -26,13 +149,13 @@ interface ValidatorIR {
26
149
  /** Column modifiers (`.unique()`, `.default()`, `.nullable()`, …) when present. */
27
150
  column?: ColumnMetaIR;
28
151
  /**
29
- * `true` when this validator carries a `.check(...)` refinement. The predicate
30
- * is a runtime closure the AST→IR step can't represent, so the node keeps its
31
- * base `kind` but records the refinement's presence here. The AOT args-validator
32
- * compiler declines any node with this flag (compiling it would silently skip
33
- * the predicate). `.meta(...)` is pure metadata with no parse effect and does
34
- * NOT set this.
35
- */
152
+ * `true` when this validator carries a `.check(...)` refinement. The predicate
153
+ * is a runtime closure the AST→IR step can't represent, so the node keeps its
154
+ * base `kind` but records the refinement's presence here. The AOT args-validator
155
+ * compiler declines any node with this flag (compiling it would silently skip
156
+ * the predicate). `.meta(...)` is pure metadata with no parse effect and does
157
+ * NOT set this.
158
+ */
36
159
  hasRefinement?: boolean;
37
160
  /** For `v.optional(inner)` / `v.array(inner)`. */
38
161
  inner?: ValidatorIR;
@@ -50,6 +173,14 @@ interface ValidatorIR {
50
173
  sourceText?: string;
51
174
  /** For `v.id("table")` — the table name. */
52
175
  tableName?: string;
176
+ /**
177
+ * For `v.from(externalSchema)` — the wrapped Standard Schema's inferred type,
178
+ * rendered as TS source. Recovered through the type checker from
179
+ * `~standard.types.output`, mirroring the runtime's `InferStandardOutput`.
180
+ * Absent when it could not be recovered safely, in which case the emitted
181
+ * type falls back to `unknown`.
182
+ */
183
+ tsType?: string;
53
184
  valueType?: ValidatorIR;
54
185
  }
55
186
  interface IndexIR {
@@ -58,11 +189,32 @@ interface IndexIR {
58
189
  unique?: boolean;
59
190
  }
60
191
  interface SearchIndexIR {
61
- /** Primary text-search field. */
192
+ /** Primary text-search field; a dot-separated path reads a nested field. */
62
193
  field: string;
63
194
  /** Optional filter fields surfaced alongside the FTS column. */
64
195
  filterFields?: ReadonlyArray<string>;
196
+ /** Text-analysis profile (accent folding + that language's stopwords). */
197
+ language?: string;
198
+ name: string;
199
+ /** Skip the migration-time backfill of the search companion (large tables index out-of-band). */
200
+ staged?: boolean;
201
+ /** `"native"` opts into the engine's own full-text index where it has one (Postgres). */
202
+ strategy?: string;
203
+ }
204
+ /** A `.geoIndex(name, { field, precision? })` declaration — a geohash companion over a `v.geoPoint()` column. */
205
+ interface GeoIndexIR {
206
+ /** The `v.geoPoint()` column feeding the geohash. */
207
+ field: string;
65
208
  name: string;
209
+ /** Geohash precision (characters) maintained on the companion; omitted ⇒ the runtime default. */
210
+ precision?: number;
211
+ }
212
+ /** A `.ttl(field, { after? })` declaration — declarative table-level auto-expiry. */
213
+ interface TtlIR {
214
+ /** Millisecond offset added to `field` to derive the expiry (`field + after`); omitted ⇒ `field` is the absolute expiry. */
215
+ after?: number;
216
+ /** The epoch-millisecond expiry column. */
217
+ field: string;
66
218
  }
67
219
  interface VectorIndexIR {
68
220
  dimensions?: number;
@@ -76,19 +228,19 @@ interface VectorIndexIR {
76
228
  table: string;
77
229
  }
78
230
  /**
79
- * One ordering key on a rank index's `sortBy`: the column and direction.
80
- * Mirrors the runtime `RankSortKey` (defaults `direction` to `"asc"`).
81
- */
231
+ * One ordering key on a rank index's `sortBy`: the column and direction.
232
+ * Mirrors the runtime `RankSortKey` (defaults `direction` to `"asc"`).
233
+ */
82
234
  interface RankSortKeyIR {
83
235
  direction: "asc" | "desc";
84
236
  field: string;
85
237
  }
86
238
  /**
87
- * A `.rankIndex(name, { sortBy, partitionBy?, where? })` declaration. The owning
88
- * table is always the table the index is declared on, so — unlike a vector index
89
- * — there is no separate `on`/`table` reference to carry: it rides along on its
90
- * {@link TableIR}. Only the fields needed for type emission are captured.
91
- */
239
+ * A `.rankIndex(name, { sortBy, partitionBy?, where? })` declaration. The owning
240
+ * table is always the table the index is declared on, so — unlike a vector index
241
+ * — there is no separate `on`/`table` reference to carry: it rides along on its
242
+ * {@link TableIR}. Only the fields needed for type emission are captured.
243
+ */
92
244
  interface RankIndexIR {
93
245
  name: string;
94
246
  /** Columns scoping each ranking; omitted ⇒ one global rank over the table. */
@@ -109,21 +261,79 @@ interface RelationIR {
109
261
  /** Target table name. */
110
262
  table: string;
111
263
  }
264
+ /**
265
+ * Statically-discovered `.source(...)` config (plan 077). Only the bits the
266
+ * advisor lints + DO wiring need are captured; `map`/`tenantBy` are functions and
267
+ * cannot be serialized, so their presence is recorded as `hasTenantBy` rather than
268
+ * the function itself.
269
+ */
270
+ interface ExternalSourceIR {
271
+ /** The wrangler Hyperdrive binding name. */
272
+ binding: string;
273
+ /** Whether a `columns` projection allow-list was given. */
274
+ columns?: ReadonlyArray<string>;
275
+ /** `true` when a `reconcileEveryMs` was given — one of the two incremental delete-visibility paths the `external_source_incremental_no_delete_path` lint checks. */
276
+ hasReconcile?: boolean;
277
+ /** `true` when a `softDeleteColumn` was given — the other incremental delete-visibility path. */
278
+ hasSoftDelete?: boolean;
279
+ /** `true` when a `tenantBy` mapper was given — the tenant-isolation boundary the `external_source_unscoped` lint checks. */
280
+ hasTenantBy: boolean;
281
+ /** The `idColumn` literal, when given (defaults to `"id"` at runtime). */
282
+ idColumn?: string;
283
+ /** Delete-detection mode literal, when given (`"full-pull"` today). */
284
+ mode?: string;
285
+ /** The membership query literal, when statically knowable. */
286
+ query?: string;
287
+ /**
288
+ * `true` when `.source(...)` was present but its argument was **not** a static
289
+ * object literal (e.g. `.source(buildConfig())`), so none of the fields above
290
+ * could be read. The source still exists — this flag lets `hasSourcedTables`
291
+ * (codegen) and the `external_source_*` lints treat it as a source that can't be
292
+ * verified, instead of mistaking it for no `.source()` at all.
293
+ */
294
+ unanalyzable?: boolean;
295
+ }
112
296
  interface TableIR {
113
297
  /**
114
- * `true` when the table chain carried `.externallyManaged()` its rows are
115
- * written outside Lunora's discoverable insert path (adapter/migration/
116
- * middleware), so advisor insert-path lints skip it. Optional: hand-built
117
- * IR and the runtime `fromServerSchema` path default it to `false`.
118
- */
298
+ * The `defineSchemaExtension` key that contributed this table, set when it
299
+ * arrived through `defineSchema(...).extend(...)`. Absent for a table the app
300
+ * declared itself.
301
+ *
302
+ * Drives the generated `AppTableName` union: an add-on's tables
303
+ * (`ratelimit_buckets`, …) are real tables and stay in `TableName`, but an app
304
+ * enumerating "my tables" should not have to know about them.
305
+ */
306
+ extensionKey?: string;
307
+ /**
308
+ * `true` when the table chain carried `.externallyManaged()` — its rows are
309
+ * written outside Lunora's discoverable insert path (adapter/migration/
310
+ * middleware), so advisor insert-path lints skip it. Optional: hand-built
311
+ * IR and the runtime `fromServerSchema` path default it to `false`.
312
+ */
119
313
  externallyManaged?: boolean;
120
314
  /**
121
- * Storage backend for a `.global()` table: `"d1"` (default) or
122
- * `"hyperdrive"` (a Postgres/MySQL database via Cloudflare Hyperdrive). Only
123
- * meaningful when `shardMode === "global"`; absent for sharded/root tables.
124
- */
315
+ * Set when the chain carried `.source(...)` — the table is materialized from an
316
+ * external Hyperdrive-backed database by a system poll loop (plan 077). Carries
317
+ * the statically-knowable bits the advisor lints read; the functions (`map`,
318
+ * `tenantBy`) are not serialized, only their presence (`hasTenantBy`).
319
+ */
320
+ externalSource?: ExternalSourceIR;
321
+ /**
322
+ * Storage backend for a `.global()` table: `"d1"` (default) or
323
+ * `"hyperdrive"` (a Postgres/MySQL database via Cloudflare Hyperdrive). Only
324
+ * meaningful when `shardMode === "global"`; absent for sharded/root tables.
325
+ */
326
+ /** Geospatial indexes declared inline via `.geoIndex(name, …)`. Optional so hand-built IR may omit it (discovery always sets it). */
327
+ geoIndexes?: ReadonlyArray<GeoIndexIR>;
125
328
  globalBackend?: "d1" | "hyperdrive";
126
329
  indexes: ReadonlyArray<IndexIR>;
330
+ /**
331
+ * `true` when the table chain carried `.public()` — an explicit opt-OUT of
332
+ * the schema's `.rls("required")` enforcement for this one table. Optional:
333
+ * hand-built IR and tables that never called `.public()` default it to
334
+ * `false`.
335
+ */
336
+ isPublic?: boolean;
127
337
  name: string;
128
338
  /** Rank indexes declared inline via `.rankIndex(name, …)`. */
129
339
  rankIndexes: ReadonlyArray<RankIndexIR>;
@@ -139,52 +349,107 @@ interface TableIR {
139
349
  softDelete?: {
140
350
  field: string;
141
351
  };
352
+ /** Set when the chain carried `.ttl(field, { after? })` — the declarative auto-expiry policy read by the DO alarm sweep. */
353
+ ttl?: TtlIR;
142
354
  /** Vector indexes declared inline via `.vectorize()` (DSL Shape A). */
143
355
  vectorIndexes: ReadonlyArray<VectorIndexIR>;
144
356
  }
357
+ /** The Cloudflare DO data-residency jurisdictions the schema may declare. Canonical literal set for the codegen package. */
358
+ type JurisdictionIR = "eu" | "fedramp" | "us";
145
359
  interface SchemaIR {
360
+ /**
361
+ * Cloudflare data-residency jurisdiction declared via
362
+ * `defineSchema(...).jurisdiction("…")`. Emitted into the generated worker's
363
+ * `createWorker({ jurisdiction })` (and `ctx.scheduler` / `ctx.containers`).
364
+ * Absent ⇒ un-pinned.
365
+ */
366
+ jurisdiction?: JurisdictionIR;
367
+ /**
368
+ * Set when `defineSchema(...).rls("required")` was chained onto the schema —
369
+ * every table's `ctx.db` write path is denied without an RLS-covering
370
+ * procedure unless the table itself is `.public()` (see {@link TableIR.isPublic}).
371
+ * Absent when the schema never called `.rls("required")`.
372
+ */
373
+ rlsMode?: "required";
146
374
  tables: ReadonlyArray<TableIR>;
147
375
  /** All vector indexes (inline Shape A hoisted + standalone Shape B), flattened. */
148
376
  vectorIndexes: ReadonlyArray<VectorIndexIR>;
149
377
  }
378
+ /**
379
+ * Statically-read mirror of `@lunora/server`'s `RestCacheConfig`. Every field is
380
+ * optional because discovery only records literals it could actually read off the
381
+ * `.expose({ cache: … })` object.
382
+ */
383
+ interface ExposeCacheIR {
384
+ maxAge?: number;
385
+ scope?: "private" | "public";
386
+ staleWhileRevalidate?: number;
387
+ tag?: string;
388
+ vary?: string;
389
+ }
150
390
  interface FunctionIR {
151
391
  args: Record<string, ValidatorIR>;
152
392
  exportName: string;
153
- /** Path relative to `&lt;projectRoot>/lunora/` without extension, e.g. "messages". */
393
+ /**
394
+ * Set by the `.expose({ rest: true })` builder modifier (plan 167). When
395
+ * `rest` is `true` the function is published on the public REST surface, so the
396
+ * OpenAPI emitter describes it as a real `/_lunora/rest/<namespace>/<fn>` path
397
+ * (the single source of truth the runtime router also derives from). Absent →
398
+ * RPC-only (the default; not on the REST surface).
399
+ *
400
+ * `cache` mirrors the `RestCacheConfig` the runtime turns into response
401
+ * headers, so the emitted spec can document the `Cache-Control` a caller will
402
+ * actually observe. Only statically-readable literal fields are carried; a
403
+ * computed value is simply absent (the spec under-documents rather than lies).
404
+ */
405
+ expose?: {
406
+ cache?: ExposeCacheIR;
407
+ rest?: boolean;
408
+ };
409
+ /** Path relative to `<projectRoot>/lunora/` without extension, e.g. "messages". */
154
410
  filePath: string;
155
411
  kind: "action" | "mutation" | "query" | "stream";
156
412
  /**
157
- * Set on connection-lifecycle hooks (`onConnect`/`onDisconnect`): the socket
158
- * side the hook fires on. Such a function is also an internal mutation (so it
159
- * lands in `LUNORA_FUNCTIONS` for path dispatch); emit additionally collects
160
- * it into the `LUNORA_LIFECYCLE_HOOKS` manifest keyed by this side. Absent on
161
- * ordinary functions.
162
- */
413
+ * Set on connection-lifecycle hooks (`onConnect`/`onDisconnect`): the socket
414
+ * side the hook fires on. Such a function is also an internal mutation (so it
415
+ * lands in `LUNORA_FUNCTIONS` for path dispatch); emit additionally collects
416
+ * it into the `LUNORA_LIFECYCLE_HOOKS` manifest keyed by this side. Absent on
417
+ * ordinary functions.
418
+ */
163
419
  lifecycle?: "connect" | "disconnect";
164
420
  /**
165
- * Serialized TS source for the handler's return type, with `Promise&lt;T>`
166
- * unwrapped so callers see `T` directly. Defaults to `"unknown"` when
167
- * ts-morph cannot resolve the type (typically because the consuming
168
- * project lacks a tsconfig that can reach `@lunora/server`).
169
- */
421
+ * The `.output(validator)` declaration, when the chain has one.
422
+ *
423
+ * Takes precedence over {@link FunctionIR.returnType} (the handler's
424
+ * inferred type) for the emitted `FunctionReference`. `.output()` is what
425
+ * validates at runtime and what a reader takes as the contract, so the two
426
+ * must agree — see the emit-side note for what went wrong when they did not.
427
+ */
428
+ output?: ValidatorIR;
429
+ /**
430
+ * Serialized TS source for the handler's return type, with `Promise<T>`
431
+ * unwrapped so callers see `T` directly. Defaults to `"unknown"` when
432
+ * ts-morph cannot resolve the type (typically because the consuming
433
+ * project lacks a tsconfig that can reach `@lunora/server`).
434
+ */
170
435
  returnType: string;
171
436
  /**
172
- * Call surface the function is exposed on. Absent (or `"public"`) means it
173
- * lands in the generated `api`; `"internal"` routes it to the separate
174
- * `internal` object and is rejected by the DO's external RPC path.
175
- */
437
+ * Call surface the function is exposed on. Absent (or `"public"`) means it
438
+ * lands in the generated `api`; `"internal"` routes it to the separate
439
+ * `internal` object and is rejected by the DO's external RPC path.
440
+ */
176
441
  visibility?: "internal" | "public";
177
442
  }
178
443
  /**
179
- * A `defineMigration({...})` declaration discovered in the user's lunora
180
- * sources. The emitted `LUNORA_MIGRATIONS` registry keys on {@link MigrationIR.id}; the
181
- * import wiring needs {@link MigrationIR.exportName}/{@link MigrationIR.filePath}. {@link MigrationIR.table} is
182
- * informational (the runtime object carries the authoritative value).
183
- */
444
+ * A `defineMigration({...})` declaration discovered in the user's lunora
445
+ * sources. The emitted `LUNORA_MIGRATIONS` registry keys on {@link MigrationIR.id}; the
446
+ * import wiring needs {@link MigrationIR.exportName}/{@link MigrationIR.filePath}. {@link MigrationIR.table} is
447
+ * informational (the runtime object carries the authoritative value).
448
+ */
184
449
  interface MigrationIR {
185
450
  /** Export binding name, used to reference the module member in generated imports. */
186
451
  exportName: string;
187
- /** Path relative to `&lt;projectRoot>/lunora/` without extension, e.g. "migrations". */
452
+ /** Path relative to `<projectRoot>/lunora/` without extension, e.g. "migrations". */
188
453
  filePath: string;
189
454
  /** Stable migration id — the registry key and per-shard run-state key. */
190
455
  id: string;
@@ -192,12 +457,109 @@ interface MigrationIR {
192
457
  table: string;
193
458
  }
194
459
  /**
195
- * A single cron job lifted from a `cronJobs()` builder in `lunora/crons.ts`.
196
- * Mirrors `@lunora/scheduler`'s `CronJob`: {@link CronJobIR.cron} is the compiled
197
- * standard cron expression, {@link CronJobIR.functionPath} is the target
198
- * `__lunoraRef` (`namespace:fn`), and {@link CronJobIR.args} is the static
199
- * argument object passed at registration.
200
- */
460
+ * A `defineShape({...})` declaration discovered in `lunora/shapes.ts`
461
+ * (local-first sync engine, Phase 7). The emitted `LUNORA_SHAPES` registry keys
462
+ * on {@link ShapeIR.exportName}; the generated DO's `resolveShape` override
463
+ * dispatches a `shape_subscribe` to the matching registered shape. Discovery is
464
+ * marker-driven (the `__lunoraShape` brand) — no field metadata is lifted here
465
+ * because the runtime object (`columns`/`compileWhere`) carries the authority.
466
+ */
467
+ interface ShapeIR {
468
+ /**
469
+ * The shape's `args` validator map — its partition selector. Lifted so
470
+ * `_generated/collections.ts` can type the selector a caller passes instead of
471
+ * widening it to `Record<string, unknown>`. `{}` for a parameterless shape.
472
+ */
473
+ args: Record<string, ValidatorIR>;
474
+ /** Export binding name — the shape's registry key and import member. */
475
+ exportName: string;
476
+ /** Path relative to `<projectRoot>/lunora/` without extension — always `"shapes"`. */
477
+ filePath: string;
478
+ /**
479
+ * The `table` string literal from the `defineShape({ table })` call, lifted
480
+ * only for static advisor lints (the runtime object stays authoritative).
481
+ * `undefined` when `table` is not a plain string literal — lints skip those.
482
+ */
483
+ table?: string;
484
+ }
485
+ /**
486
+ * The single `defineIdentity({...})` claim contract discovered in
487
+ * `lunora/identity.ts`. Discovery is **marker-driven** (the `__lunoraIdentity`
488
+ * brand, exactly like {@link ShapeIR}) — no claim metadata is lifted here
489
+ * because the emitted `_generated/server.ts` recovers the claim *type* from the
490
+ * declaration itself (`InferIdentity` over the contract's `typeof`), and the
491
+ * runtime object (`validate`/`onInvalid`) carries the authority at the boundary.
492
+ * Exactly one per app; absent ⇒ generated output is byte-identical to today.
493
+ */
494
+ interface IdentityIR {
495
+ /** Export binding name — the namespace member `_generated/server.ts` reads via `typeof`. */
496
+ exportName: string;
497
+ }
498
+ /**
499
+ * The single `defineEnv({...})` contract discovered in `lunora/env.ts`. Like
500
+ * {@link IdentityIR}, only the export binding is lifted — the emitted
501
+ * `_generated/server.ts` recovers the validated shape from the declaration
502
+ * itself (`ReturnType` over the accessor's `typeof`), and the generated ShardDO
503
+ * applies the same accessor to the worker `env` at ctx-build time to populate
504
+ * `ctx.env`. Exactly one per app; absent ⇒ generated output is byte-identical.
505
+ */
506
+ interface EnvIR {
507
+ /** Export binding name — the namespace member `_generated/server.ts` reads via `typeof`. */
508
+ exportName: string;
509
+ }
510
+ /**
511
+ * A `defineMutator({...})` declaration discovered in `lunora/mutators.ts`
512
+ * (local-first sync engine, Phase 7). The emitted registry registers the
513
+ * authoritative `server` impl into the DO's `LUNORA_FUNCTIONS` table (so
514
+ * `handleRpc` transaction-wraps it) and records its path in
515
+ * `LUNORA_MUTATOR_PATHS` so the DO's `isCustomMutator` override routes the
516
+ * client-watermark push protocol. The client `client` impl is split into the
517
+ * browser bundle separately — only the path crosses to the server side.
518
+ */
519
+ interface MutatorIR {
520
+ /**
521
+ * The mutator's `args` validator map, parsed exactly as a procedure's is, so
522
+ * the emitted `api.mutators.<name>` reference carries the arg type a client
523
+ * `defineMutator` infers instead of restating. `{}` for a parameterless
524
+ * mutator (or one whose `args` isn't an inline object literal).
525
+ */
526
+ args: Record<string, ValidatorIR>;
527
+ /** Export binding name — the mutator's registry key and import member. */
528
+ exportName: string;
529
+ /** Path relative to `<projectRoot>/lunora/` without extension — always `"mutators"`. */
530
+ filePath: string;
531
+ /**
532
+ * Serialized TS source for the authoritative `server` impl's return type,
533
+ * `Promise<T>` unwrapped. `"unknown"` when ts-morph can't resolve it — same
534
+ * contract as {@link FunctionIR.returnType}.
535
+ */
536
+ returnType: string;
537
+ }
538
+ /**
539
+ * A whole-row `ctx.db.replace(id, document)` write discovered inside a custom
540
+ * mutator's inline `server` impl (`lunora/mutators.ts`) — the input the
541
+ * `mutator_full_row_replace` advisor lint consumes. A `replace` overwrites the
542
+ * entire row, so a concurrent edit to a different column on a synced table is
543
+ * clobbered; `ctx.db.patch(id, { field })` merges at the column level instead.
544
+ * Structurally identical to `AdvisorMutatorWrite` so it passes straight through
545
+ * to the advisor without conversion, exactly as `InsertWriteIR` does for
546
+ * `AdvisorInsertWrite`.
547
+ */
548
+ interface MutatorWriteIR {
549
+ /** The mutator export whose `server` impl performs the replace, e.g. `renameChannel`. */
550
+ exportName: string;
551
+ /** Openable source path the replace appears in — always `lunora/mutators.ts`. */
552
+ file: string;
553
+ /** 1-based line of the `replace(...)` call. */
554
+ line: number;
555
+ }
556
+ /**
557
+ * A single cron job lifted from a `cronJobs()` builder in `lunora/crons.ts`.
558
+ * Mirrors `@lunora/scheduler`'s `CronJob`: {@link CronJobIR.cron} is the compiled
559
+ * standard cron expression, {@link CronJobIR.functionPath} is the target
560
+ * `__lunoraRef` (`namespace:fn`), and {@link CronJobIR.args} is the static
561
+ * argument object passed at registration.
562
+ */
201
563
  interface CronJobIR {
202
564
  /** Static args object (source-text JSON), defaults to `{}`. */
203
565
  args: Record<string, unknown>;
@@ -208,25 +570,25 @@ interface CronJobIR {
208
570
  /** Unique, human-readable job name. */
209
571
  name: string;
210
572
  /**
211
- * Set when the job targets a durable workflow (a `lunora/workflows.ts`
212
- * export) instead of a function: the workflow's `WORKFLOW_*` binding name
213
- * plus its export name. On each fire the worker starts a new workflow
214
- * INSTANCE (the {@link CronJobIR.args} become its `params`) rather than
215
- * dispatching a one-shot function.
216
- */
573
+ * Set when the job targets a durable workflow (a `lunora/workflows.ts`
574
+ * export) instead of a function: the workflow's `WORKFLOW_*` binding name
575
+ * plus its export name. On each fire the worker starts a new workflow
576
+ * INSTANCE (the {@link CronJobIR.args} become its `params`) rather than
577
+ * dispatching a one-shot function.
578
+ */
217
579
  workflow?: {
218
580
  binding: string;
219
581
  exportName: string;
220
582
  };
221
583
  }
222
584
  /**
223
- * A container lifted from a `defineContainer()` export in
224
- * `lunora/containers.ts`. Carries everything the emitters and the config layer
225
- * need to wire wrangler (`containers[]` + the Durable Object binding +
226
- * migration class) and the generated `_generated/containers.ts` DO class.
227
- * Names are derived via `@lunora/container`'s shared helpers so codegen and
228
- * the config layer can never disagree.
229
- */
585
+ * A container lifted from a `defineContainer()` export in
586
+ * `lunora/containers.ts`. Carries everything the emitters and the config layer
587
+ * need to wire wrangler (`containers[]` + the Durable Object binding +
588
+ * migration class) and the generated `_generated/containers.ts` DO class.
589
+ * Names are derived via `@lunora/container`'s shared helpers so codegen and
590
+ * the config layer can never disagree.
591
+ */
230
592
  interface ContainerIR {
231
593
  /** Durable Object binding name, e.g. `CONTAINER_TRANSCODER`. */
232
594
  bindingName: string;
@@ -235,18 +597,18 @@ interface ContainerIR {
235
597
  /** Generated DO class name, e.g. `TranscoderContainer`. */
236
598
  className: string;
237
599
  /**
238
- * Whether the container may open outbound internet connections, when the
239
- * value was a static literal. `undefined` means the field was omitted (the
240
- * platform default is `true`) or wasn't a literal. Lifted for the advisor.
241
- */
600
+ * Whether the container may open outbound internet connections, when the
601
+ * value was a static literal. `undefined` means the field was omitted (the
602
+ * platform default is `true`) or wasn't a literal. Lifted for the advisor.
603
+ */
242
604
  enableInternet?: boolean;
243
605
  /** The `lunora/containers.ts` export name, e.g. `transcoder`. */
244
606
  exportName: string;
245
607
  /**
246
- * Normalized image source: a local Dockerfile (`dockerfile`), a pre-built
247
- * registry reference (`registry`), or a Railpack source directory (`build`)
248
- * that the deploy step builds and pushes before wrangler runs.
249
- */
608
+ * Normalized image source: a local Dockerfile (`dockerfile`), a pre-built
609
+ * registry reference (`registry`), or a Railpack source directory (`build`)
610
+ * that the deploy step builds and pushes before wrangler runs.
611
+ */
250
612
  image: {
251
613
  buildContext: string;
252
614
  dockerfilePath: string;
@@ -274,20 +636,20 @@ interface ContainerIR {
274
636
  stepPercentage?: number;
275
637
  };
276
638
  /**
277
- * The static `sleepAfter` value, when it was a literal. `undefined` means
278
- * omitted (platform default `"10m"`) or non-literal. Lifted for the advisor.
279
- */
639
+ * The static `sleepAfter` value, when it was a literal. `undefined` means
640
+ * omitted (platform default `"10m"`) or non-literal. Lifted for the advisor.
641
+ */
280
642
  sleepAfter?: number | string;
281
643
  }
282
644
  /**
283
- * A workflow lifted from a `defineWorkflow()` export in `lunora/workflows.ts`.
284
- * Carries what the emitters and the config layer need to wire the wrangler
285
- * `workflows[]` entry and the generated `_generated/workflows.ts`
286
- * `WorkflowEntrypoint` class. Unlike containers, workflows are NOT Durable
287
- * Objects — wrangler gets only a `workflows[]` entry, never a `durable_objects`
288
- * binding or a migration class. Names are derived via `@lunora/workflow`'s
289
- * shared helpers so codegen and the config layer can never disagree.
290
- */
645
+ * A workflow lifted from a `defineWorkflow()` export in `lunora/workflows.ts`.
646
+ * Carries what the emitters and the config layer need to wire the wrangler
647
+ * `workflows[]` entry and the generated `_generated/workflows.ts`
648
+ * `WorkflowEntrypoint` class. Unlike containers, workflows are NOT Durable
649
+ * Objects — wrangler gets only a `workflows[]` entry, never a `durable_objects`
650
+ * binding or a migration class. Names are derived via `@lunora/workflow`'s
651
+ * shared helpers so codegen and the config layer can never disagree.
652
+ */
291
653
  interface WorkflowIR {
292
654
  /** The Cloudflare `Workflow` binding name, e.g. `WORKFLOW_ORDER_PIPELINE`. */
293
655
  bindingName: string;
@@ -296,25 +658,156 @@ interface WorkflowIR {
296
658
  /** The `lunora/workflows.ts` export name, e.g. `orderPipeline`. */
297
659
  exportName: string;
298
660
  /**
299
- * The stable wrangler `workflows[].name`. Defaults to the kebab-cased export
300
- * name (`orderPipeline` → `order-pipeline`); a static `name:` literal in the
301
- * definition overrides it.
302
- */
661
+ * The stable wrangler `workflows[].name`. Defaults to the kebab-cased export
662
+ * name (`orderPipeline` → `order-pipeline`); a static `name:` literal in the
663
+ * definition overrides it.
664
+ */
665
+ name: string;
666
+ /**
667
+ * Durable step labels lifted from the handler body — the first string-literal
668
+ * argument of every `ctx.step.do` / `.sleep` / `.sleepUntil` / `.waitForEvent`
669
+ * call. Feeds the duplicate-step-name lint, which flags a name used twice
670
+ * (Cloudflare memoizes by name, so the second call silently returns the
671
+ * first's cached result). Calls with a non-literal name are omitted (not
672
+ * statically comparable).
673
+ */
674
+ steps: ReadonlyArray<WorkflowStepIR>;
675
+ }
676
+ /**
677
+ * An agent lifted from a `defineAgent()` export in `lunora/agents.ts`. A
678
+ * `defineAgent` compiles its durable tool-loop onto a Cloudflare Workflow, so —
679
+ * like {@link WorkflowIR} — an agent is NOT a Durable Object: wrangler gets only
680
+ * a `workflows[]` entry, never a `durable_objects` binding or a migration class.
681
+ * Carries what the emitters and the config layer need to wire the generated
682
+ * agent `WorkflowEntrypoint` class (e.g. `SupportAgentWorkflow`), the typed
683
+ * per-agent `ctx.agents` producer, and the reconciled wrangler `workflows[]`
684
+ * entry. Names are derived via `@lunora/agent`'s shared helpers so codegen and
685
+ * the config layer can never disagree.
686
+ */
687
+ interface AgentIR {
688
+ /** The Cloudflare `Workflow` binding name, e.g. `AGENT_SUPPORT`. */
689
+ bindingName: string;
690
+ /** Generated `WorkflowEntrypoint` class name, e.g. `SupportAgentWorkflow`. */
691
+ className: string;
692
+ /** The `lunora/agents.ts` export name, e.g. `support`. */
693
+ exportName: string;
694
+ /**
695
+ * The stable wrangler `workflows[].name`. Defaults to the kebab-cased export
696
+ * name (`support` → `agent-support`); a static `name:` literal in the
697
+ * definition overrides it.
698
+ */
303
699
  name: string;
700
+ /**
701
+ * Whether the definition declares an `onEmail` mapper on
702
+ * `defineAgent({ onEmail: … })`. When `true` the emitter wires this agent
703
+ * onto the worker's top-level `email()` handler (via `@lunora/agent/inbound`)
704
+ * so inbound mail starts a durable run. Detected by AST PRESENCE — the
705
+ * closure is never evaluated — and written to IR only when present, so
706
+ * email-free agents (and agent-free projects) stay byte-identical.
707
+ */
708
+ onEmail?: boolean;
709
+ /**
710
+ * Whether the definition opted into public run-starts via
711
+ * `defineAgent({ publicRun: true })` — emitted into the `ctx.agents` wiring
712
+ * spec so the public `agents:agentRun` mutation can gate on it fail-closed.
713
+ * Absent (falsy) means server-side starts only; the field is written to IR
714
+ * only when the literal is `true`, so agent-free and non-opted-in output is
715
+ * byte-identical.
716
+ */
717
+ publicRun?: boolean;
718
+ /**
719
+ * Whether the definition opted into a real-time voice session via a `voice`
720
+ * block on `defineAgent({ voice: … })`. Unlike the durable loop (a Workflow),
721
+ * the voice path IS a Durable Object — so when this is `true` the emitter
722
+ * generates the `voiceClassName` `VoiceSessionDO` subclass and the
723
+ * `api.agents.{name}Voice` client reference, and the config layer reconciles
724
+ * a `durable_objects` binding (`voiceBindingName`) + `new_sqlite_classes`
725
+ * migration. Written to IR only when the literal is present, so voice-free
726
+ * agents (and agent-free projects) stay byte-identical.
727
+ */
728
+ voice?: boolean;
729
+ /** The voice DO's Cloudflare `DurableObjectNamespace` binding name, e.g. `VOICE_SUPPORT`. Present only when `voice`. */
730
+ voiceBindingName?: string;
731
+ /** Generated `VoiceSessionDO` subclass name, e.g. `SupportVoiceDO`. Present only when `voice`. */
732
+ voiceClassName?: string;
733
+ }
734
+ /** One durable step call lifted from a workflow handler body (the use side of {@link WorkflowIR.steps}). */
735
+ interface WorkflowStepIR {
736
+ /** 1-based line of the durable step call. */
737
+ line: number;
738
+ /** The native step method invoked: `do` / `sleep` / `sleepUntil` / `waitForEvent`. */
739
+ method: string;
740
+ /** The step's static label (the first string-literal argument). */
741
+ name: string;
742
+ }
743
+ /**
744
+ * A queue lifted from a `defineQueue()` export in `lunora/queues.ts`. Carries
745
+ * what the emitters and the config layer need to wire the typed `ctx.queues`
746
+ * producer, the generated worker `queue()` dispatch, and the wrangler
747
+ * `queues.producers[]` / `queues.consumers[]` entries. Like workflows, a queue
748
+ * is NOT a Durable Object — wrangler gets only `queues.*` entries. Names are
749
+ * derived via `@lunora/queue`'s shared helpers so codegen and the config layer
750
+ * can never disagree.
751
+ */
752
+ interface QueueIR {
753
+ /** The Cloudflare `Queue` producer binding name, e.g. `QUEUE_EMAIL`. */
754
+ bindingName: string;
755
+ /** The `lunora/queues.ts` export name, e.g. `emailQueue`. */
756
+ exportName: string;
757
+ /** How the queue is consumed: `"push"` (a worker `queue()` handler) or `"pull"` (external HTTP). */
758
+ mode: "pull" | "push";
759
+ /**
760
+ * The stable wrangler queue name (`queues.producers[].queue`). Defaults to
761
+ * the kebab-cased export name (`emailQueue` → `email-queue`); a static
762
+ * `name:` literal in the definition overrides it.
763
+ */
764
+ name: string;
765
+ /** Push-consumer batch/retry tuning, mirrored onto the wrangler `queues.consumers[]` entry. */
766
+ tuning: {
767
+ deadLetterQueue?: string;
768
+ maxBatchSize?: number;
769
+ maxBatchTimeout?: number;
770
+ maxRetries?: number;
771
+ retryDelay?: number;
772
+ };
773
+ }
774
+ /**
775
+ * The feature-flag provider declared by the default export of `lunora/flags.ts`
776
+ * (`defineFlags({ provider, … })`). Discovery is **metadata-only** — codegen
777
+ * imports the real module at runtime for the provider value; this IR exists so
778
+ * the config layer can reconcile/validate the wrangler `flagship` binding when
779
+ * the app uses Flagship in binding mode. A `custom` provider (any other
780
+ * OpenFeature factory) carries no binding to reconcile.
781
+ */
782
+ interface FlagsIR {
783
+ /**
784
+ * The wrangler `flagship[].binding` name — set **only** for a flagship
785
+ * `provider` in binding mode (`flagshipProvider({ binding: "FLAGS" })`). The
786
+ * config layer hints/validates a matching `flagship` binding from this.
787
+ */
788
+ bindingName?: string;
789
+ /**
790
+ * Flagship operating mode — `"binding"` (wrangler binding, needs a
791
+ * `flagship` entry) or `"http"` (no binding); `undefined` for a `custom`
792
+ * provider or when the mode can't be read statically.
793
+ */
794
+ mode?: "binding" | "http";
795
+ /** `"flagship"` when the provider is `flagshipProvider(...)`, else `"custom"` (any other OpenFeature provider factory). */
796
+ provider: "custom" | "flagship";
304
797
  }
305
798
  /**
306
- * A `ctx.workflows.get("name")…` call discovered in a function body — the
307
- * use-site analog of {@link WorkflowIR} (which is the declaration side). Feeds
308
- * the `workflow_unused` lint (a declared workflow with zero call sites) and the
309
- * `workflow_unknown_target` lint (a `.get("x")` whose `x` isn't declared — a
310
- * typo catcher). {@link WorkflowCallIR.workflow} is `""` when the `get(...)`
311
- * argument is not a string literal (a dynamic name — which suppresses the
312
- * unused-workflow heuristic rather than producing a false positive).
313
- */
799
+ * A `ctx.workflows.get("name")…` call discovered in a function body — the
800
+ * use-site analog of {@link WorkflowIR} (which is the declaration side). Feeds
801
+ * the `workflow_unused` lint (a declared workflow with zero call sites) and the
802
+ * `workflow_unknown_target` lint (a `.get("x")` whose `x` isn't declared — a
803
+ * typo catcher). {@link WorkflowCallIR.workflow} is `""` when the `get(...)`
804
+ * argument is not a string literal (a dynamic name — which suppresses the
805
+ * unused-workflow heuristic rather than producing a false positive).
806
+ */
314
807
  interface WorkflowCallIR {
315
808
  /** Export binding name of the function performing the call, e.g. `create`. */
316
809
  exportName: string;
317
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension (the api namespace). */
810
+ /** Source file relative to `<projectRoot>/lunora/`, without extension (the api namespace). */
318
811
  file: string;
319
812
  /** 1-based line of the `get(...)` call. */
320
813
  line: number;
@@ -322,14 +815,23 @@ interface WorkflowCallIR {
322
815
  workflow: string;
323
816
  }
324
817
  /**
325
- * A `ctx.db.query("table")…` read discovered in a function body, reduced to what
326
- * the `filter_without_index` advisor lint needs: which table, whether the chain
327
- * narrows with an index, and whether it filters. `table` is `""` when the
328
- * `query(...)` argument is not a string literal (a dynamic table — not lintable).
329
- */
818
+ * A `ctx.db.query("table")…` read discovered in a function body, reduced to what
819
+ * the `filter_without_index` advisor lint needs: which table, whether the chain
820
+ * narrows with an index, and whether it filters. `table` is `""` when the
821
+ * `query(...)` argument is not a string literal (a dynamic table — not lintable).
822
+ */
330
823
  interface QueryReadIR {
331
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
824
+ /** Exported procedure the read sits in, or `""` at module scope. */
825
+ exportName: string;
826
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
332
827
  file: string;
828
+ /**
829
+ * True when the chain's `.filter()` predicate compares `_id`
830
+ * (`(d) => d._id === args.id`) — a full scan for a row that `ctx.db.get`
831
+ * addresses directly. Optional so a feeder predating this field still
832
+ * typechecks; absent is treated as "not a primary-key filter".
833
+ */
834
+ filtersPrimaryKey?: boolean;
333
835
  /** The chain calls `.filter(...)`. */
334
836
  hasFilter: boolean;
335
837
  /** The chain narrows with `.withIndex(...)` or `.withSearchIndex(...)`. */
@@ -340,16 +842,16 @@ interface QueryReadIR {
340
842
  table: string;
341
843
  }
342
844
  /**
343
- * A `ctx.authApi.&lt;method>(...)` call discovered in a function body, attributed
344
- * to the exported function (and its file = api namespace) that performs it.
345
- * Structurally identical to `AdvisorAuthApiCall` so it passes straight through
346
- * to the advisor lint without conversion, exactly as `InsertWriteIR` does for
347
- * `AdvisorInsertWrite`.
348
- */
845
+ * A `ctx.authApi.<method>(...)` call discovered in a function body, attributed
846
+ * to the exported function (and its file = api namespace) that performs it.
847
+ * Structurally identical to `AdvisorAuthApiCall` so it passes straight through
848
+ * to the advisor lint without conversion, exactly as `InsertWriteIR` does for
849
+ * `AdvisorInsertWrite`.
850
+ */
349
851
  interface AuthApiCallIR {
350
852
  /** Export binding name of the function performing the call, e.g. "createOrg". */
351
853
  exportName: string;
352
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
854
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
353
855
  file: string;
354
856
  /** True when the call's argument object includes a `headers` property. */
355
857
  hasHeaders: boolean;
@@ -359,16 +861,16 @@ interface AuthApiCallIR {
359
861
  method: string;
360
862
  }
361
863
  /**
362
- * A `ctx.db.insert("table", …)` write discovered in a function body, attributed
363
- * to the exported function (and its file = api namespace) that performs it — the
364
- * write-side analog of {@link QueryReadIR}. Lets tooling wire a table's write
365
- * action by behavior (which function inserts into it) rather than by naming.
366
- * {@link InsertWriteIR.table} is `""` when the argument is not a string literal.
367
- */
864
+ * A `ctx.db.insert("table", …)` write discovered in a function body, attributed
865
+ * to the exported function (and its file = api namespace) that performs it — the
866
+ * write-side analog of {@link QueryReadIR}. Lets tooling wire a table's write
867
+ * action by behavior (which function inserts into it) rather than by naming.
868
+ * {@link InsertWriteIR.table} is `""` when the argument is not a string literal.
869
+ */
368
870
  interface InsertWriteIR {
369
871
  /** Export binding name of the function performing the insert, e.g. "send". */
370
872
  exportName: string;
371
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension (the api namespace). */
873
+ /** Source file relative to `<projectRoot>/lunora/`, without extension (the api namespace). */
372
874
  file: string;
373
875
  /** 1-based line of the `insert(...)` call. */
374
876
  line: number;
@@ -376,20 +878,20 @@ interface InsertWriteIR {
376
878
  table: string;
377
879
  }
378
880
  /**
379
- * A non-deterministic API call (`Date.now`, `Math.random`, `crypto.randomUUID`,
380
- * `crypto.getRandomValues`, `fetch`) discovered lexically inside a `query(...)`
381
- * or `mutation(...)` handler body — the `nondeterministic_query_mutation` lint
382
- * input. Structurally identical to `AdvisorNondeterministicCall` so values pass
383
- * straight through to the advisor without conversion, exactly as `AuthApiCallIR`
384
- * does for `AdvisorAuthApiCall`. `action(...)` handlers are never recorded —
385
- * actions are the determinism escape hatch.
386
- */
881
+ * A non-deterministic API call (`Date.now`, `Math.random`, `crypto.randomUUID`,
882
+ * `crypto.getRandomValues`, `fetch`) discovered lexically inside a `query(...)`
883
+ * or `mutation(...)` handler body — the `nondeterministic_query_mutation` lint
884
+ * input. Structurally identical to `AdvisorNondeterministicCall` so values pass
885
+ * straight through to the advisor without conversion, exactly as `AuthApiCallIR`
886
+ * does for `AdvisorAuthApiCall`. `action(...)` handlers are never recorded —
887
+ * actions are the determinism escape hatch.
888
+ */
387
889
  interface NondeterministicCallIR {
388
890
  /** The non-deterministic API invoked, e.g. `Date.now` / `Math.random` / `crypto.randomUUID` / `fetch`. */
389
891
  callee: string;
390
892
  /** Export binding name of the function performing the call, e.g. `sendMessage`. */
391
893
  exportName: string;
392
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension (the api namespace). */
894
+ /** Source file relative to `<projectRoot>/lunora/`, without extension (the api namespace). */
393
895
  file: string;
394
896
  /** Which procedure kind the call lives in — only `query`/`mutation` handlers are recorded. */
395
897
  kind: "mutation" | "query";
@@ -397,13 +899,13 @@ interface NondeterministicCallIR {
397
899
  line: number;
398
900
  }
399
901
  /**
400
- * One `ctx.r2sql` access lexically inside a `query`/`mutation` handler — the
401
- * `r2sql_outside_action` advisor lint input. Structurally identical to the
402
- * advisor's `AdvisorR2sqlCall` (same field set) so values pass straight through
403
- * `lintSchema` without conversion, exactly as `NondeterministicCallIR` does.
404
- * Only `query`/`mutation` handlers are recorded; `action(...)` is the intended
405
- * home for `ctx.r2sql` and is skipped.
406
- */
902
+ * One `ctx.r2sql` access lexically inside a `query`/`mutation` handler — the
903
+ * `r2sql_outside_action` advisor lint input. Structurally identical to the
904
+ * advisor's `AdvisorR2sqlCall` (same field set) so values pass straight through
905
+ * `lintSchema` without conversion, exactly as `NondeterministicCallIR` does.
906
+ * Only `query`/`mutation` handlers are recorded; `action(...)` is the intended
907
+ * home for `ctx.r2sql` and is skipped.
908
+ */
407
909
  interface R2sqlCallIR {
408
910
  /** The accessed `ctx.r2sql` surface, e.g. `ctx.r2sql.query` / `ctx.r2sql.from`. */
409
911
  callee: string;
@@ -417,21 +919,21 @@ interface R2sqlCallIR {
417
919
  line: number;
418
920
  }
419
921
  /**
420
- * Per-procedure RLS usage snapshot, produced by `discoverRlsProcedures` for the
421
- * `rls_uncovered_table` advisor lint. Structurally identical to
422
- * `AdvisorRlsProcedure` (they share the same field set) so values pass straight
423
- * through to the advisor without conversion, exactly as `AuthApiCallIR` does for
424
- * `AdvisorAuthApiCall`.
425
- */
922
+ * Per-procedure RLS usage snapshot, produced by `discoverRlsProcedures` for the
923
+ * `rls_uncovered_table` advisor lint. Structurally identical to
924
+ * `AdvisorRlsProcedure` (they share the same field set) so values pass straight
925
+ * through to the advisor without conversion, exactly as `AuthApiCallIR` does for
926
+ * `AdvisorAuthApiCall`.
927
+ */
426
928
  interface RlsProcedureIR {
427
929
  /** Export binding name of the procedure (e.g. `listDocuments`). */
428
930
  exportName: string;
429
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
931
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
430
932
  file: string;
431
933
  /**
432
- * Table names extracted from the `rls(policies)` array literal. Empty when the
433
- * policies argument is not a statically-readable array literal.
434
- */
934
+ * Table names extracted from the `rls(policies)` array literal. Empty when the
935
+ * policies argument is not a statically-readable array literal.
936
+ */
435
937
  rlsTables: string[];
436
938
  /** Tables read by the procedure via `ctx.db.query/findMany/findFirst/…`. */
437
939
  tablesRead: string[];
@@ -443,22 +945,22 @@ interface RlsProcedureIR {
443
945
  visibility: "internal" | "public";
444
946
  }
445
947
  /**
446
- * One procedure reduced to the facts the `mask_uncovered_pii_column` lint needs:
447
- * whether its builder chain includes `.use(mask(...))`, which `(table, column)`
448
- * pairs that mask declares, and which tables the procedure reads/writes. The
449
- * column-level analogue of {@link RlsProcedureIR}. Structurally identical to
450
- * `AdvisorMaskProcedure` so values pass straight through without conversion.
451
- */
948
+ * One procedure reduced to the facts the `mask_uncovered_pii_column` lint needs:
949
+ * whether its builder chain includes `.use(mask(...))`, which `(table, column)`
950
+ * pairs that mask declares, and which tables the procedure reads/writes. The
951
+ * column-level analogue of {@link RlsProcedureIR}. Structurally identical to
952
+ * `AdvisorMaskProcedure` so values pass straight through without conversion.
953
+ */
452
954
  interface MaskProcedureIR {
453
955
  /** Export binding name of the procedure (e.g. `listUsers`). */
454
956
  exportName: string;
455
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
957
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
456
958
  file: string;
457
959
  /**
458
- * `(table, column)` pairs this procedure's `mask(policies)` object literal
459
- * declares. Empty when the policies argument is not a statically-readable
460
- * object literal (conservative: `usesMask` is still `true`).
461
- */
960
+ * `(table, column)` pairs this procedure's `mask(policies)` object literal
961
+ * declares. Empty when the policies argument is not a statically-readable
962
+ * object literal (conservative: `usesMask` is still `true`).
963
+ */
462
964
  maskColumns: {
463
965
  column: string;
464
966
  table: string;
@@ -473,14 +975,14 @@ interface MaskProcedureIR {
473
975
  visibility: "internal" | "public";
474
976
  }
475
977
  /**
476
- * One masked column surfaced to the studio's data-browser mask preview: a
477
- * `(table, column)` pair plus the declared {@link MaskProcedureIR} strategy so
478
- * the preview can pick redact-vs-hash-vs-custom rendering. Aggregated across the
479
- * project's `.use(mask(...))` chains by `discoverMaskMetadata`; the descriptive
480
- * twin of {@link RlsPolicyIR}. `"custom"` covers any non-string strategy (a
481
- * `(value, ctx) => …` function) — its logic is an opaque closure, never read by
482
- * the UI; the preview renders a fixed sentinel for it.
483
- */
978
+ * One masked column surfaced to the studio's data-browser mask preview: a
979
+ * `(table, column)` pair plus the declared {@link MaskProcedureIR} strategy so
980
+ * the preview can pick redact-vs-hash-vs-custom rendering. Aggregated across the
981
+ * project's `.use(mask(...))` chains by `discoverMaskMetadata`; the descriptive
982
+ * twin of {@link RlsPolicyIR}. `"custom"` covers any non-string strategy (a
983
+ * `(value, ctx) => …` function) — its logic is an opaque closure, never read by
984
+ * the UI; the preview renders a fixed sentinel for it.
985
+ */
484
986
  interface MaskColumnMetadataIR {
485
987
  /** Column the mask policy redacts. */
486
988
  column: string;
@@ -490,24 +992,48 @@ interface MaskColumnMetadataIR {
490
992
  table: string;
491
993
  }
492
994
  /**
493
- * Schema-wide masking metadata the codegen emits into the generated ShardDO so
494
- * the studio's data-browser mask toggle can preview what a non-privileged caller
495
- * would see. Aggregated across every `.use(mask(...))` chain in the project —
496
- * purely descriptive (table + column + strategy), never the masking closure. The
497
- * column-level analogue of {@link RlsMetadataIR}.
498
- */
995
+ * Schema-wide masking metadata the codegen emits into the generated ShardDO so
996
+ * the studio's data-browser mask toggle can preview what a non-privileged caller
997
+ * would see. Aggregated across every `.use(mask(...))` chain in the project —
998
+ * purely descriptive (table + column + strategy), never the masking closure. The
999
+ * column-level analogue of {@link RlsMetadataIR}.
1000
+ */
499
1001
  interface MaskMetadataIR {
500
1002
  /** Every statically-discovered masked column, deduped by `(table, column)` (first declaration wins). */
501
1003
  columns: MaskColumnMetadataIR[];
502
1004
  }
503
1005
  /**
504
- * One statically-readable policy entry from an `rls([...])` array literal,
505
- * surfaced to the studio's read-only RLS inspector via the generated
506
- * `rlsPolicies()` hook. Captures the policy's `table` + `on` operation and the
507
- * procedure it guards never the `when` predicate, which is an opaque JS
508
- * closure (its logic stays in code, not the UI). Produced by
509
- * `discoverRlsProcedures` alongside the lint IR.
510
- */
1006
+ * One masked column whose `mask(policies)` strategy is a statically-known
1007
+ * literal (`"hash"` or `"redact"`) the `mask_weak_hash_strategy_on_pii` lint
1008
+ * input. Unlike {@link MaskColumnMetadataIR} (app-wide, deduped by `(table,
1009
+ * column)`, studio-preview evidence), this is per declaration site (file + line
1010
+ * + enclosing export), undeduped, so the lint can point at the exact
1011
+ * `mask(...)` call that applies a weak strategy. A `MaskFn` (custom, non-literal)
1012
+ * strategy carries no lint-relevant signal and is never recorded here.
1013
+ * Structurally identical to `AdvisorMaskStrategy`.
1014
+ */
1015
+ interface MaskStrategyIR {
1016
+ /** Masked column name. */
1017
+ column: string;
1018
+ /** Export binding name of the procedure whose `.use(mask(...))` chain declared this column, or `"<module>"` when declared at file scope. */
1019
+ exportName: string;
1020
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1021
+ file: string;
1022
+ /** 1-based line of the masked column's strategy property. */
1023
+ line: number;
1024
+ /** The statically-known strategy literal: `"hash"` or `"redact"`. */
1025
+ strategy: string;
1026
+ /** Logical table the masked column belongs to. */
1027
+ table: string;
1028
+ }
1029
+ /**
1030
+ * One statically-readable policy entry from an `rls([...])` array literal,
1031
+ * surfaced to the studio's read-only RLS inspector via the generated
1032
+ * `rlsPolicies()` hook. Captures the policy's `table` + `on` operation and the
1033
+ * procedure it guards — never the `when` predicate, which is an opaque JS
1034
+ * closure (its logic stays in code, not the UI). Produced by
1035
+ * `discoverRlsProcedures` alongside the lint IR.
1036
+ */
511
1037
  interface RlsPolicyIR {
512
1038
  /** Source file (relative to `lunora/`, without extension) the policy is declared in. */
513
1039
  file: string;
@@ -519,12 +1045,12 @@ interface RlsPolicyIR {
519
1045
  table: string;
520
1046
  }
521
1047
  /**
522
- * One statically-readable role entry from an `rls(policies, { roles: [...] })`
523
- * call, surfaced to the studio's RLS inspector. Captures the role's `name`,
524
- * optional `description`, and the names of the permissions it grants (string
525
- * literals or `definePermission("name")` calls). Produced by
526
- * `discoverRlsProcedures`.
527
- */
1048
+ * One statically-readable role entry from an `rls(policies, { roles: [...] })`
1049
+ * call, surfaced to the studio's RLS inspector. Captures the role's `name`,
1050
+ * optional `description`, and the names of the permissions it grants (string
1051
+ * literals or `definePermission("name")` calls). Produced by
1052
+ * `discoverRlsProcedures`.
1053
+ */
528
1054
  interface RlsRoleIR {
529
1055
  /** Optional human-readable description from `defineRole(name, { description })`. */
530
1056
  description?: string;
@@ -534,11 +1060,11 @@ interface RlsRoleIR {
534
1060
  permissions: string[];
535
1061
  }
536
1062
  /**
537
- * Schema-wide RLS metadata the codegen emits into the generated ShardDO so the
538
- * studio's read-only inspector can list, per table, which policies guard it and
539
- * what roles are defined. Aggregated across every `.use(rls(...))` chain in the
540
- * project — purely descriptive, never the predicate logic.
541
- */
1063
+ * Schema-wide RLS metadata the codegen emits into the generated ShardDO so the
1064
+ * studio's read-only inspector can list, per table, which policies guard it and
1065
+ * what roles are defined. Aggregated across every `.use(rls(...))` chain in the
1066
+ * project — purely descriptive, never the predicate logic.
1067
+ */
542
1068
  interface RlsMetadataIR {
543
1069
  /** Every statically-discovered policy `(table, on, procedure)` entry. */
544
1070
  policies: RlsPolicyIR[];
@@ -557,27 +1083,36 @@ interface StorageRuleIR {
557
1083
  procedure: string;
558
1084
  }
559
1085
  /**
560
- * Schema-wide storage-access-rule metadata emitted into the generated ShardDO so
561
- * the studio's read-only inspector can list, per bucket, which operations are
562
- * gated and under what key prefix. Aggregated across every
563
- * `.use(storageRules(...))` chain — descriptive only, never the predicate logic.
564
- */
1086
+ * Schema-wide storage-access-rule metadata emitted into the generated ShardDO so
1087
+ * the studio's read-only inspector can list, per bucket, which operations are
1088
+ * gated and under what key prefix. Aggregated across every
1089
+ * `.use(storageRules(...))` chain — descriptive only, never the predicate logic.
1090
+ */
565
1091
  interface StorageRulesMetadataIR {
566
1092
  rules: StorageRuleIR[];
567
1093
  }
568
1094
  /**
569
- * A typed REST route declared with the `httpRoute.&lt;verb>("/path")…` builder in
570
- * `@lunora/server` and mounted on `httpRouter()`. Captured statically from the
571
- * builder chain so the OpenAPI emitter can render a real `paths` entry: the verb
572
- * + path become the operation's method + URL, and the accumulated validator maps
573
- * become its query parameters, path parameters, and request body.
574
- */
1095
+ * A typed REST route declared with the `httpRoute.<verb>("/path")…` builder in
1096
+ * `@lunora/server` and mounted on `httpRouter()`. Captured statically from the
1097
+ * builder chain so the OpenAPI emitter can render a real `paths` entry: the verb
1098
+ * + path become the operation's method + URL, and the accumulated validator maps
1099
+ * become its query parameters, path parameters, and request body.
1100
+ */
575
1101
  interface HttpRouteIR {
576
1102
  /** `v.*` validators decoding the JSON request body (`.body({...})`), keyed by field. */
577
1103
  body: Record<string, ValidatorIR>;
1104
+ /**
1105
+ * Rendered TS type of one SSE chunk — the `R` the `.stream(handler)`
1106
+ * handler yields — inferred from the handler via the type checker. Present
1107
+ * only when {@link HttpRouteIR.stream} is `true`; `"unknown"` when the
1108
+ * checker can't resolve enough context. Feeds the emitted
1109
+ * `HttpStreamRef<Chunk, …>` so the chunk type flows to the client.
1110
+ * @experimental Part of the HTTP-SSE stream surface (the `httpStreams.*` emission).
1111
+ */
1112
+ chunkType?: string;
578
1113
  /** Export binding name of the route handler (used only for diagnostics / dedupe). */
579
1114
  exportName: string;
580
- /** Path relative to `&lt;projectRoot>/lunora/` without extension, e.g. "http". */
1115
+ /** Path relative to `<projectRoot>/lunora/` without extension, e.g. "http". */
581
1116
  filePath: string;
582
1117
  /** HTTP verb the route binds to (uppercased), e.g. `"GET"`. */
583
1118
  method: string;
@@ -585,7 +1120,7 @@ interface HttpRouteIR {
585
1120
  output?: ValidatorIR;
586
1121
  /** `v.*` validators decoding the hono path params (`.params({...})`), keyed by `:name`. */
587
1122
  params: Record<string, ValidatorIR>;
588
- /** The route path passed to `httpRoute.&lt;verb>(path)`, e.g. `/api/todos/:id`. */
1123
+ /** The route path passed to `httpRoute.<verb>(path)`, e.g. `/api/todos/:id`. */
589
1124
  path: string;
590
1125
  /** `v.*` validators decoding the URL query string (`.searchParams({...})`), keyed by name. */
591
1126
  searchParams: Record<string, ValidatorIR>;
@@ -593,28 +1128,69 @@ interface HttpRouteIR {
593
1128
  stream: boolean;
594
1129
  }
595
1130
  /**
596
- * Per-procedure protective-middleware snapshot, produced by
597
- * `discoverProcedureMiddleware` for the security lints
598
- * (`public_mutation_without_ratelimit`, `user_creating_mutation_without_captcha`).
599
- * Records which `.use(...)` guards a procedure's builder chain carries plus the
600
- * behavioural facts that decide whether a guard is *expected* (does it write a
601
- * user/session table, does it send mail). `protectPublic({ rateLimit, captcha })`
602
- * is unwrapped: the bundle's object-literal keys set `usesRateLimit`/`usesCaptcha`
603
- * exactly as the individual `.use(rateLimit(...))` / `.use(verifyTurnstile(...))`
604
- * steps would. Structurally identical to `AdvisorProcedureProtection` so values
605
- * pass straight through to the advisor without conversion.
606
- */
1131
+ * Per-procedure protective-middleware snapshot, produced by
1132
+ * `discoverProcedureMiddleware` for the security lints
1133
+ * (`public_mutation_without_ratelimit`, `user_creating_mutation_without_captcha`).
1134
+ * Records which `.use(...)` guards a procedure's builder chain carries plus the
1135
+ * behavioural facts that decide whether a guard is *expected* (does it write a
1136
+ * user/session table, does it send mail). `protectPublic({ rateLimit, captcha })`
1137
+ * is unwrapped: the bundle's object-literal keys set `usesRateLimit`/`usesCaptcha`
1138
+ * exactly as the individual `.use(rateLimit(...))` / `.use(verifyTurnstile(...))`
1139
+ * steps would. Structurally identical to `AdvisorProcedureProtection` so values
1140
+ * pass straight through to the advisor without conversion.
1141
+ */
607
1142
  interface ProcedureMiddlewareIR {
608
- /** `true` when the handler (or a helper inside it) references `ctx.mail` / `ctx.email`. */
609
- callsMail: boolean;
1143
+ /**
1144
+ * `true` when the handler body could be read statically — an inline function
1145
+ * expression/arrow, or a same-file identifier resolved to one. `false` for a
1146
+ * genuinely cross-file handler (an imported function, or an identifier that
1147
+ * doesn't resolve in this file), in which case every behavioural fact below
1148
+ * is `undefined` rather than a false "not observed" — the feeder never saw
1149
+ * the body, so it has nothing to report.
1150
+ */
1151
+ analyzableBody: boolean;
1152
+ /** `true` when the handler (or a helper inside it) references `ctx.mail` / `ctx.email`. `undefined` when `analyzableBody` is `false`. */
1153
+ callsMail?: boolean;
1154
+ /** `true` when the handler emits a structured observability event (`ctx.log` / `ctx.span` / `ctx.trace`). */
1155
+ emitsEvent?: boolean;
1156
+ /** `true` when a `// lunora-advisor-exempt` directive sits above the export. */
1157
+ exempt: boolean;
1158
+ /** The `-- reason` from that directive, or `""`. */
1159
+ exemptReason: string;
610
1160
  /** Export binding name of the procedure (e.g. `signUp`). */
611
1161
  exportName: string;
612
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1162
+ /** `true` when the handler fans work out to a privileged, cost-bearing dispatch surface (scheduler `runAfter`/`runAt`, a queue producer send, or a workflow create). Feeds the privileged-fanout lint. `undefined` when `analyzableBody` is `false`. */
1163
+ fanOut?: boolean;
1164
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
613
1165
  file: string;
614
- /** Registration kind only `mutation`/`action` are write-shaped; `query` is read-only. */
1166
+ /** `true` when the handler wraps work in `try`/`catch`. */
1167
+ handlesErrors?: boolean;
1168
+ /**
1169
+ * `true` when the procedure declares an email-shaped argument (`email`,
1170
+ * `emailAddress`, `userEmail`, …), `false` when it provably declares none,
1171
+ * and **absent** when the argument list can't be read statically (a
1172
+ * `.input(sharedSchema)`, a spread, or a factory whose `args` comes from a
1173
+ * variable). Feeds `signup_mutation_without_disposable_gating`, which can
1174
+ * only be actioned when there is an address to gate — so "unreadable" must
1175
+ * stay distinguishable from "none", or the lint would clear itself on a
1176
+ * registration that may well expose one.
1177
+ */
1178
+ hasEmailArg?: boolean;
615
1179
  kind: "action" | "mutation" | "query";
1180
+ /** `true` when the handler reaches an outbound surface (`ctx.fetch`, mail, queues, storage, sql, ai, …) that can fail. */
1181
+ reachesOutbound?: boolean;
1182
+ /** `true` when the handler runs any AI generation, bounded or not. */
1183
+ runsAiGeneration?: boolean;
1184
+ /** `true` when the handler throws a bare `new Error(...)` rather than a coded `LunoraError`. */
1185
+ throwsBareError?: boolean;
1186
+ /** `true` when the handler runs an AI generation (`generateText`/`streamText`/`generateObject`/`streamObject`) with no `maxOutputTokens` bound in its config literal. Feeds the `ai_unbounded_generation_public` lint. `undefined` when `analyzableBody` is `false`. */
1187
+ unboundedAiGeneration?: boolean;
616
1188
  /** `true` when the chain carries `.use(verifyTurnstile(...))` or a `protectPublic({ captcha })` bundle. */
617
1189
  usesCaptcha: boolean;
1190
+ /** `true` when the chain carries `.use(emailGateMiddleware(...))` (`@lunora/auth`). Feeds the `signup_mutation_without_disposable_gating` lint. */
1191
+ usesEmailGate: boolean;
1192
+ /** `true` when the handler calls `ctx.db.insertManyUnsafe(...)`, bypassing validators and triggers. Feeds the `insert_many_unsafe_user_data` lint. `undefined` when `analyzableBody` is `false`. */
1193
+ usesInsertManyUnsafe?: boolean;
618
1194
  /** `true` when the chain carries `.use(mask(...))`. */
619
1195
  usesMask: boolean;
620
1196
  /** `true` when the chain carries `.use(rateLimit(...))` or a `protectPublic({ rateLimit })` bundle. */
@@ -623,23 +1199,23 @@ interface ProcedureMiddlewareIR {
623
1199
  usesRls: boolean;
624
1200
  /** `"internal"` for `internalQuery` / `internalMutation` / `internalAction`. */
625
1201
  visibility: "internal" | "public";
626
- /** `true` when the handler inserts into a user/session/account-shaped table. */
627
- writesUserTable: boolean;
1202
+ /** `true` when the handler inserts into a user/session/account-shaped table. `undefined` when `analyzableBody` is `false`. */
1203
+ writesUserTable?: boolean;
628
1204
  }
629
1205
  /**
630
- * Per-procedure argument-validator snapshot, produced by the
631
- * argument-validator discoverer for the input-hardening lints
632
- * (`public_arg_uses_any`, `unbounded_string_arg`). Only public procedures are
633
- * recorded — internal functions take server-trusted input. Structurally identical
634
- * to `AdvisorArgumentValidator` so it passes straight through to the advisor
635
- * without conversion.
636
- */
1206
+ * Per-procedure argument-validator snapshot, produced by the
1207
+ * argument-validator discoverer for the input-hardening lints
1208
+ * (`public_arg_uses_any`, `unbounded_string_arg`). Only public procedures are
1209
+ * recorded — internal functions take server-trusted input. Structurally identical
1210
+ * to `AdvisorArgumentValidator` so it passes straight through to the advisor
1211
+ * without conversion.
1212
+ */
637
1213
  interface ArgumentValidatorIR {
638
1214
  /** Arg names declared as `v.any()` (unvalidated, untyped input). */
639
1215
  anyArgs: string[];
640
1216
  /** Export binding name of the procedure (e.g. `updateProfile`). */
641
1217
  exportName: string;
642
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1218
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
643
1219
  file: string;
644
1220
  /** 1-based line of the registration call, or `0` when unknown. */
645
1221
  line: number;
@@ -647,13 +1223,34 @@ interface ArgumentValidatorIR {
647
1223
  unboundedStringArgs: string[];
648
1224
  }
649
1225
  /**
650
- * One secret-shaped string literal discovered in `lunora/` source the
651
- * `hardcoded_secret` lint input. Complements the pre-commit `vis secrets` scan by
652
- * surfacing the same class of finding in-IDE via the studio Advisors table.
653
- * Structurally identical to `AdvisorSecretLiteral`.
654
- */
1226
+ * One factory/constructor call in `lunora/` whose config object literal a
1227
+ * security lint inspects for a present-or-absent key the shared input for the
1228
+ * config-call security lints (payment authorize, inbound-mail verify, rate-limit
1229
+ * store, browser private-targets). Structurally identical to `AdvisorConfigCall`
1230
+ * so it passes straight through to the advisor without conversion.
1231
+ */
1232
+ interface ConfigCallIR {
1233
+ /** `true` when the config argument was a static object literal the feeder could read. */
1234
+ analyzable: boolean;
1235
+ /** The factory function or constructor name at the call site, e.g. `createPayment` / `RateLimiter`. */
1236
+ callee: string;
1237
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1238
+ file: string;
1239
+ /** 1-based line of the call site, or `0` when unknown. */
1240
+ line: number;
1241
+ /** Keys present in the config object literal (empty when not `analyzable`). */
1242
+ presentKeys: string[];
1243
+ /** Keys in the config object literal explicitly assigned the literal `true`. */
1244
+ trueKeys: string[];
1245
+ }
1246
+ /**
1247
+ * One secret-shaped string literal discovered in `lunora/` source — the
1248
+ * `hardcoded_secret` lint input. Complements the pre-commit `vis secrets` scan by
1249
+ * surfacing the same class of finding in-IDE via the studio Advisors table.
1250
+ * Structurally identical to `AdvisorSecretLiteral`.
1251
+ */
655
1252
  interface SecretLiteralIR {
656
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1253
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
657
1254
  file: string;
658
1255
  /** Heuristic that matched, e.g. `stripe_live_key` / `aws_access_key` / `pem_private_key` / `high_entropy`. */
659
1256
  kind: string;
@@ -663,431 +1260,1824 @@ interface SecretLiteralIR {
663
1260
  preview: string;
664
1261
  }
665
1262
  /**
666
- * One `ctx.sql.query(text, …)` / `ctx.sql.unsafe(text, …)` call whose `text`
667
- * argument is built in place rather than passed as a fixed statement — the
668
- * `sql_injection_risk` lint input. The Hyperdrive driver binds ONLY the `params`
669
- * array; the `text` string is spliced verbatim into the SQL, so a `text` assembled
670
- * from a string concatenation or a substitution template literal is an injection
671
- * vector. A fixed string literal / no-substitution template is safe. Structurally
672
- * identical to `AdvisorSqlInterpolation`.
673
- */
1263
+ * One `ctx.sql.query(text, …)` / `ctx.sql.unsafe(text, …)` call whose `text`
1264
+ * argument is built in place rather than passed as a fixed statement — the
1265
+ * `sql_injection_risk` lint input. The Hyperdrive driver binds ONLY the `params`
1266
+ * array; the `text` string is spliced verbatim into the SQL, so a `text` assembled
1267
+ * from a string concatenation or a substitution template literal is an injection
1268
+ * vector. A fixed string literal / no-substitution template is safe. Structurally
1269
+ * identical to `AdvisorSqlInterpolation`.
1270
+ */
674
1271
  interface SqlInterpolationIR {
675
1272
  /** Export binding name of the procedure performing the `ctx.sql` call. */
676
1273
  exportName: string;
677
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1274
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
678
1275
  file: string;
679
1276
  /** 1-based line of the interpolation, or `0` when unknown. */
680
1277
  line: number;
681
1278
  }
682
1279
  /**
683
- * One discovered `httpRoute.&lt;verb>("/admin/…")` route on an admin/privileged-looking
684
- * path, with whether its builder chain references an auth/admin guard — the
685
- * `admin_route_without_guard` lint input. Structurally identical to
686
- * `AdvisorAdminRoute`.
687
- */
688
- interface AdminRouteIR {
689
- /** Export binding name of the route handler. */
1280
+ * One `ctx.fetch(url, …)` call inside an action whose URL argument is derived
1281
+ * from the handler's `args` the `action_fetch_ssrf` lint input. `ctx.fetch` is
1282
+ * the action-only outbound-request escape hatch with no host allowlist, so a URL
1283
+ * assembled from request input is a server-side request forgery vector (cloud
1284
+ * metadata endpoints, internal services). Only arg-derived URLs reach here; a
1285
+ * fixed literal or a URL built from config/`ctx.*` is not recorded. Structurally
1286
+ * identical to `AdvisorArgumentDerivedFetch`.
1287
+ */
1288
+ interface ArgumentDerivedFetchIR {
1289
+ /** Export binding name of the action performing the `ctx.fetch` call. */
690
1290
  exportName: string;
691
- /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1291
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
692
1292
  file: string;
693
- /** HTTP verb the route binds to (uppercased), e.g. `"POST"`. */
694
- method: string;
695
- /** The route path, e.g. `/admin/users`. */
696
- path: string;
697
- /** `true` when the handler body references an auth/session/admin guard (`ctx.auth`, `getSession`, `requireAdmin`, …). */
698
- usesGuard: boolean;
699
- }
700
- interface ProjectIR {
701
- crons: ReadonlyArray<CronJobIR>;
702
- functions: ReadonlyArray<FunctionIR>;
703
- /** Typed REST routes discovered from `httpRoute.&lt;verb>(...)` builder chains. */
704
- httpRoutes: ReadonlyArray<HttpRouteIR>;
705
- migrations: ReadonlyArray<MigrationIR>;
706
- schema: SchemaIR;
1293
+ /** 1-based line of the `ctx.fetch` call, or `0` when unknown. */
1294
+ line: number;
707
1295
  }
708
1296
  /**
709
- * Run the static lints against a discovered {@link SchemaIR} and the reads/writes/calls
710
- * found in function bodies: query reads feed `filter_without_index`, insert writes
711
- * feed `table_without_insert`, authApi calls feed `auth_api_call_without_headers`,
712
- * rls procedure snapshots feed `rls_uncovered_table`, and mask procedure
713
- * snapshots feed `mask_uncovered_pii_column`; declared containers
714
- * feed the `container_*` lints; declared workflows + `ctx.workflows.get(...)` call
715
- * sites feed the `workflow_unused` / `workflow_unknown_target` lints; non-deterministic
716
- * calls inside query/mutation handlers feed the `nondeterministic_query_mutation` lint
717
- * (all default empty for callers that don't analyze functions/containers/workflows).
718
- * The IR types are structurally identical to the advisor's evidence types so they
719
- * pass straight through without conversion. Returns the findings; surfacing them
720
- * (console, error overlay, studio Advisors table) is the caller's choice.
721
- */
722
- declare const lintSchema: (schema: SchemaIR, queries?: ReadonlyArray<QueryReadIR>, inserts?: ReadonlyArray<InsertWriteIR>, authApiCalls?: ReadonlyArray<AuthApiCallIR>, rlsProcedures?: ReadonlyArray<RlsProcedureIR>, containers?: ReadonlyArray<ContainerIR>, workflows?: ReadonlyArray<WorkflowIR>, workflowCalls?: ReadonlyArray<WorkflowCallIR>, maskProcedures?: ReadonlyArray<MaskProcedureIR>, nondeterministicCalls?: ReadonlyArray<NondeterministicCallIR>, procedureProtections?: ReadonlyArray<ProcedureMiddlewareIR>, argumentValidators?: ReadonlyArray<ArgumentValidatorIR>, secretLiterals?: ReadonlyArray<SecretLiteralIR>, sqlInterpolations?: ReadonlyArray<SqlInterpolationIR>, adminRoutes?: ReadonlyArray<AdminRouteIR>, r2sqlCalls?: ReadonlyArray<R2sqlCallIR>) => Finding[];
723
- /**
724
- * Render advisor findings as a single multi-line string for console surfacing:
725
- * a one-line summary header followed by one `[LEVEL] name: detail` line per
726
- * finding. Returns `""` when there are no findings.
727
- */
728
- declare const formatAdvisories: (findings: ReadonlyArray<Finding>) => string;
729
- /**
730
- * An error thrown by codegen discovery when the user's schema or function
731
- * source has a structural problem that can be pinpointed to a specific source
732
- * location. The `file`, `line`, and `column` properties mirror what Vite's
733
- * error-overlay `loc` field expects so the browser can display the exact spot.
734
- */
735
- declare class CodegenDiagnosticError extends Error {
736
- readonly column: number;
737
- readonly file: string;
738
- readonly line: number;
739
- constructor(message: string, file: string, line: number, column: number);
1297
+ * One `ctx.kv.<method>(key, …)` call whose namespace key is derived from the
1298
+ * handler's `args` with no server-side scoping the `kv_unscoped_user_key_idor`
1299
+ * lint input. Workers KV is a single flat namespace, so a key taken straight from
1300
+ * request input lets any caller read, overwrite, or delete another user's entry
1301
+ * (IDOR). Only arg-derived, unscoped keys reach here; a fixed literal, or a key
1302
+ * prefixed with a server-trusted identity (`${ctx.auth.userId}:…` — references
1303
+ * `ctx`, so treated as scoped), is not recorded. `list` is excluded (it takes a
1304
+ * prefix, not a per-entry key). Structurally identical to `AdvisorKvKeyAccess`.
1305
+ */
1306
+ interface KvKeyAccessIR {
1307
+ /** Export binding name of the procedure performing the `ctx.kv` access. */
1308
+ exportName: string;
1309
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1310
+ file: string;
1311
+ /** 1-based line of the `ctx.kv` call, or `0` when unknown. */
1312
+ line: number;
1313
+ /** The `ctx.kv` method invoked: `get` / `getRaw` / `getWithMetadata` / `put` / `delete`. */
1314
+ method: string;
740
1315
  }
741
1316
  /**
742
- * Build a {@link CodegenDiagnosticError} whose message includes the source
743
- * location and whose `file`/`line`/`column` properties are set from the
744
- * ts-morph `Node`'s position in its source file.
745
- *
746
- * Message format: `@lunora/codegen: &lt;detail> (&lt;file>:&lt;line>:&lt;column>)`
747
- *
748
- * `meta` is merged onto the returned error for callers that also carry the
749
- * project-wide `LunoraError` envelope (`code`/`name`/`status`) it never
750
- * touches `file`/`line`/`column`, and the error stays an instance of
751
- * {@link CodegenDiagnosticError} so the Vite overlay's `instanceof` location
752
- * lookup is unaffected.
753
- */
754
- declare const diagnosticAt: (node: Node, detail: string, meta?: Record<string, unknown>) => CodegenDiagnosticError;
755
- /**
756
- * Discover `ctx.authApi.&lt;method>(...)` (and bare `authApi.&lt;method>(...)`) calls
757
- * under the lunora source directory and attribute each to the exported function
758
- * (and file) performing it. Calls outside an exported declaration are dropped.
759
- */
760
- declare const discoverAuthApiCalls: (project: Project, lunoraDirectory: string) => AuthApiCallIR[];
761
- /** The only file containers may be declared in — mirrors `lunora/crons.ts`. */
762
- declare const CONTAINERS_FILENAME = "containers.ts";
1317
+ * One `ctx.db` write (`insert` / `replace` / `patch` / `insertManyUnsafe`) that sets
1318
+ * an ownership / identity column`userId`, `ownerId`, `tenantId`, and the like —
1319
+ * from the handler's `args` instead of the server-trusted identity. The
1320
+ * `owner_field_from_args_not_auth` lint input: the ownership column decides who a
1321
+ * row belongs to, so a value taken from request input lets any caller write rows
1322
+ * owned by another user or tenant (the act-as-any-user / cross-tenant IDOR vector).
1323
+ * A column stamped from `ctx.*`, or set to a fixed literal, is not recorded; only an
1324
+ * arg-derived identity write reaches here. Structurally identical to
1325
+ * `AdvisorOwnerFieldWrite`.
1326
+ */
1327
+ /**
1328
+ * One branching `defineShape({ where })` / `definePolicy({ when })` predicate arm
1329
+ * that returns an unrestricted predicate the `unrestricted_where_branch` lint
1330
+ * input. A denial arm must match NO rows (`deny()` / `{ OR: [] }`); `{}` matches
1331
+ * every row, so the near-miss silently replicates the whole table.
1332
+ */
1333
+ interface UnrestrictedWhereBranchIR {
1334
+ /** Export binding name of the shape / policy the predicate belongs to. */
1335
+ exportName: string;
1336
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1337
+ file: string;
1338
+ /** Which unrestricted form was returned. */
1339
+ form: "empty-object" | "undefined";
1340
+ /** The config key carrying the predicate (`where` for a shape, `when` for a policy). */
1341
+ key: string;
1342
+ /** 1-based line of the offending returned expression. */
1343
+ line: number;
1344
+ /** The declaring call (`defineShape` / `definePolicy`). */
1345
+ owner: string;
1346
+ }
1347
+ interface OwnerFieldWriteIR {
1348
+ /** Export binding name of the procedure performing the write. */
1349
+ exportName: string;
1350
+ /** The identity column being written from `args` (e.g. `userId`). */
1351
+ field: string;
1352
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1353
+ file: string;
1354
+ /** 1-based line of the `ctx.db` write call, or `0` when unknown. */
1355
+ line: number;
1356
+ /** The `ctx.db` write method (`insert` / `replace` / `patch` / `insertManyUnsafe`). */
1357
+ method: string;
1358
+ /**
1359
+ * Visibility of the enclosing procedure. `internal` procedures are not
1360
+ * reachable by a caller, so the lint's premise ("any caller can write rows
1361
+ * owned by another user") does not hold there — see
1362
+ * `owner_field_from_args_not_auth`. `undefined` when the write sits outside
1363
+ * any recognised procedure (a bare helper).
1364
+ */
1365
+ visibility?: "internal" | "public";
1366
+ }
763
1367
  /**
764
- * Discover every container the project declares: exported `defineContainer()`
765
- * calls in `lunora/containers.ts`. Returns `[]` when the file doesn't exist.
766
- * Wrangler-relevant fields (`image`, `instanceType`, `maxInstances`, `name`)
767
- * must be static literals; runtime-only fields (`env`, `sleepAfter`, …) may be
768
- * any expression since the generated class imports the definition object.
769
- */
770
- declare const discoverContainers: (project: Project, lunoraDirectory: string) => ContainerIR[];
1368
+ * One `ctx.storage.<bucket>.<method>(key, …)` call whose R2 object key is derived
1369
+ * from the handler's `args` with no server-side scoping — the
1370
+ * `storage_key_from_user_args` lint input. The bucket read/write/URL/delete methods
1371
+ * key by their first argument, so an object key taken straight from request input is
1372
+ * object-level IDOR (read/overwrite/delete anyone's object). A key referencing a
1373
+ * server-trusted `ctx.*` value (e.g. `${ctx.auth.userId}/…`) is treated as scoped
1374
+ * and is not recorded; only an arg-derived, `ctx`-free key reaches here.
1375
+ * Structurally identical to `AdvisorStorageKeyAccess`.
1376
+ */
1377
+ interface StorageKeyAccessIR {
1378
+ /** Export binding name of the procedure performing the storage call. */
1379
+ exportName: string;
1380
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1381
+ file: string;
1382
+ /** 1-based line of the storage call, or `0` when unknown. */
1383
+ line: number;
1384
+ /** The bucket method invoked with the arg-derived key, e.g. `get` / `put` / `delete` / `download`. */
1385
+ method: string;
1386
+ /**
1387
+ * Visibility of the enclosing procedure. `internal` procedures have no
1388
+ * untrusted caller by construction — see `owner_field_from_args_not_auth`'s
1389
+ * identical split — so `storage_key_from_user_args` drops the finding to
1390
+ * INFO rather than ERROR there. `undefined` when the access sits outside any
1391
+ * registered procedure the feeder could attribute it to.
1392
+ */
1393
+ visibility?: "internal" | "public";
1394
+ }
771
1395
  /**
772
- * Scan every `.ts` file under `lunoraDir` for `cronJobs()` builder registrations
773
- * (`crons.interval(...)`, `crons.daily(...)`, `crons.cron(...)`, …) and lift them
774
- * into {@link CronJobIR}. Schedules are compiled to standard cron expressions;
775
- * function references are resolved to their `namespace:fn` dispatch path, while a
776
- * bare identifier naming a declared workflow (`workflows`) resolves to a durable
777
- * workflow start. Names must be unique across the project.
778
- */
779
- declare const discoverCrons: (project: Project, lunoraDirectory: string, workflows?: ReadonlyArray<WorkflowIR>) => CronJobIR[];
780
- /**
781
- * Scan all .ts files under `lunoraDir` (skipping `_generated/` and `schema.ts`)
782
- * for top-level `export const x = query/mutation/action({...})` registrations.
783
- */
784
- declare const discoverFunctions: (project: Project, lunoraDirectory: string) => FunctionIR[];
1396
+ * One `ctx.containers.<exportName>.get(name, …)` call whose instance key is derived
1397
+ * from the handler's `args` with no server-side scoping — the
1398
+ * `container_instance_key_from_user_input` lint input. Each container definition's
1399
+ * `.get(name)` accessor routes to one instance per `name`, so a key taken straight from
1400
+ * request input lets any caller reach another tenant's container (a cross-tenant IDOR). A
1401
+ * fixed literal key, or one derived from a server-trusted identity (`${ctx.auth.userId}` —
1402
+ * references `ctx`, so treated as scoped), is not recorded; only an arg-derived, unscoped
1403
+ * key reaches here. `.any()`/`.pool()` take no key and are not sinks. Structurally
1404
+ * identical to `AdvisorContainerKeyAccess`.
1405
+ */
1406
+ interface ContainerKeyAccessIR {
1407
+ /** Export binding name of the procedure performing the `ctx.containers` access. */
1408
+ exportName: string;
1409
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1410
+ file: string;
1411
+ /** 1-based line of the `ctx.containers.*.get` call, or `0` when unknown. */
1412
+ line: number;
1413
+ /** The container accessor method invoked — always `get`. */
1414
+ method: string;
1415
+ }
785
1416
  /**
786
- * Scan all `.ts` files under `lunoraDir` (skipping `_generated/` and `schema.ts`)
787
- * for `export const x = httpRoute.&lt;verb>(...)…handler(...)` typed REST routes.
788
- * These are the headline OpenAPI target: each becomes a real `paths` entry.
789
- */
790
- declare const discoverHttpRoutes: (project: Project, lunoraDirectory: string) => HttpRouteIR[];
1417
+ * One `ctx.ai.run(model, …)` call whose model-id argument is derived from the handler's
1418
+ * `args` with no server-side scoping — the `ai_raw_run_escape_hatch` lint input.
1419
+ * `ctx.ai.run` is the raw Workers AI binding passthrough, bypassing the typed
1420
+ * `ctx.ai.model(...)` + AI-SDK layer (`generateText`/`streamText`/…) that caps output and
1421
+ * enforces a schema, so an arg-derived model id lets any caller select an arbitrary model.
1422
+ * A fixed literal model, or one scoped by a server-trusted `ctx.*` value, is not recorded;
1423
+ * only an arg-derived, unscoped model id reaches here (an arg-derived `inputs` argument is
1424
+ * normal usage and is never inspected). Structurally identical to `AdvisorAiRawRun`.
1425
+ */
1426
+ interface AiRawRunIR {
1427
+ /** Export binding name of the procedure performing the `ctx.ai.run` call. */
1428
+ exportName: string;
1429
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1430
+ file: string;
1431
+ /** 1-based line of the `ctx.ai.run` call, or `0` when unknown. */
1432
+ line: number;
1433
+ }
791
1434
  /**
792
- * Discover `ctx.db.insert("table", )` writes under the lunora source directory
793
- * and attribute each to the exported function (and file) performing it. Calls
794
- * with a non-literal table argument, or outside an exported declaration, are
795
- * dropped (`table === ""` / no enclosing export).
796
- */
797
- declare const discoverInserts: (project: Project, lunoraDirectory: string) => InsertWriteIR[];
1435
+ * One `ctx.vectors.<method>(indexName, input)` call whose `input.namespace` is derived
1436
+ * from the handler's `args` with no server-side scoping the
1437
+ * `vectors_namespace_from_user_input` lint input. A Vectorize namespace partitions one
1438
+ * index into isolated sub-collections, so a namespace taken straight from request input
1439
+ * lets any caller read or poison another tenant's vectors. A fixed literal namespace, or
1440
+ * one prefixed with a server-trusted identity (`${ctx.auth.orgId}` references `ctx`, so
1441
+ * treated as scoped), is not recorded; only an arg-derived, unscoped namespace reaches
1442
+ * here. Structurally identical to `AdvisorVectorNamespaceAccess`.
1443
+ */
1444
+ interface VectorNamespaceAccessIR {
1445
+ /** Export binding name of the procedure performing the `ctx.vectors` access. */
1446
+ exportName: string;
1447
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1448
+ file: string;
1449
+ /** 1-based line of the `ctx.vectors` call, or `0` when unknown. */
1450
+ line: number;
1451
+ /** The `ctx.vectors` method invoked: `query` / `upsert` / `upsertMany`. */
1452
+ method: string;
1453
+ }
798
1454
  /**
799
- * Discover masking usage for every exported Lunora procedure under the lunora
800
- * source directory the column-level twin of `discoverRlsProcedures`. For each
801
- * procedure, records whether its builder chain includes `.use(mask(...))`, which
802
- * `(table, column)` pairs that mask declares, and which tables it reads/writes
803
- * through `ctx.db`. Feeds the `mask_uncovered_pii_column` advisor lint.
804
- */
805
- declare const discoverMaskProcedures: (project: Project, lunoraDirectory: string) => MaskProcedureIR[];
1455
+ * One `ctx.mail`/`ctx.email` `send`/`queue` call whose recipient field (`to`/`cc`/`bcc`)
1456
+ * is derived from the handler's `args` with no server-side scoping — the
1457
+ * `mail_recipient_from_request_input` lint input. A recipient taken straight from request
1458
+ * input turns the deployment into an open relay / spam amplifier (any caller can direct
1459
+ * mail to an arbitrary address). A fixed literal recipient, or one scoped by a
1460
+ * server-trusted `ctx.*` value (e.g. `ctx.auth.user.email`), is not recorded; only an
1461
+ * arg-derived, unscoped recipient reaches here. Structurally identical to
1462
+ * `AdvisorMailRecipientAccess`.
1463
+ */
1464
+ interface MailRecipientAccessIR {
1465
+ /** Export binding name of the procedure performing the `ctx.mail`/`ctx.email` call. */
1466
+ exportName: string;
1467
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1468
+ file: string;
1469
+ /** 1-based line of the `ctx.mail`/`ctx.email` call, or `0` when unknown. */
1470
+ line: number;
1471
+ /** The mailer method invoked: `send` / `queue`. */
1472
+ method: string;
1473
+ }
806
1474
  /**
807
- * Aggregate the schema-wide masking metadata the studio's data-browser mask
808
- * toggle reads: every statically-discovered `(table, column, strategy)` masked
809
- * column across the project's `.use(mask(...))` chains. Walks the same builder
810
- * chains as {@link discoverMaskProcedures} but carries the strategy the preview
811
- * needs to choose redact-vs-hash-vs-custom rendering. Deduped by `(table,
812
- * column)` with the first declaration winning, so a column masked by several
813
- * procedures lists once — the same evidence the advisor lint uses.
814
- */
815
- /**
816
- * Scan all `.ts` files under `lunoraDir` for top-level
817
- * `export const x = defineMigration({...})` declarations and lift them into
818
- * {@link MigrationIR}. `id` must be a static string literal (it's the registry
819
- * key); `table` is best-effort and left `""` when not a literal.
820
- */
821
- declare const discoverMigrations: (project: Project, lunoraDirectory: string) => MigrationIR[];
1475
+ * One `ctx.browser.<method>(url, …)` call whose navigation URL (`arguments[0]`)
1476
+ * is derived from the handler's `args` with no server-side scoping — the
1477
+ * `browser_user_url_without_allowlist` lint input. The lint additionally
1478
+ * cross-references `createBrowser` config-call evidence to suppress findings
1479
+ * when the browser is hardened with an `allowedHosts` allowlist or
1480
+ * `resolveDns`. Structurally identical to `AdvisorBrowserUrlAccess`.
1481
+ */
1482
+ interface BrowserUrlAccessIR {
1483
+ /** Export binding name of the procedure performing the `ctx.browser` call. */
1484
+ exportName: string;
1485
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1486
+ file: string;
1487
+ /** 1-based line of the `ctx.browser` call, or `0` when unknown. */
1488
+ line: number;
1489
+ /** The browser method invoked: `content` / `pdf` / `scrape` / `screenshot`. */
1490
+ method: string;
1491
+ }
822
1492
  /**
823
- * Discover non-deterministic API calls (`Date.now`, `new Date()`, `Date()`,
824
- * `Math.random`, `crypto.randomUUID`, `crypto.getRandomValues` including
825
- * `globalThis`/`self`/`window`-prefixed receivers and `fetch`) lexically inside
826
- * the handler body of every exported `query(...)` / `mutation(...)` registration
827
- * under the lunora source directory the `nondeterministic_query_mutation` lint
828
- * input. `action(...)` (and `stream(...)`) registrations are intentionally
829
- * skipped: actions run exactly once and may use ambient APIs freely.
830
- *
831
- * Traversal is scoped to the handler node (not the whole declaration), mirroring
832
- * how the auth-api / insert feeders attribute calls — so a call in a sibling
833
- * helper outside the handler, or in a nested `action(...)` passed elsewhere, is
834
- * not attributed to the query/mutation. One {@link NondeterministicCallIR} is
835
- * produced per call site.
836
- */
837
- declare const discoverNondeterministicCalls: (project: Project, lunoraDirectory: string) => NondeterministicCallIR[];
1493
+ * One runtime container-override call: a `<handle>.start({ enableInternet: true, … })`
1494
+ * launch override, or a `<handle>.egress.<method>(...)` runtime firewall mutation
1495
+ * (`allow` / `deny` / `setAllowed`) the `container_start_enable_internet_override`
1496
+ * and `container_runtime_egress_relaxation` lint input. Both shapes re-open network
1497
+ * access the static `defineContainer` declaration (and its `container_public_internet`
1498
+ * lint) assumes is locked down. Matched structurally by call shape, independent of the
1499
+ * receiver's resolved type. Structurally identical to `AdvisorContainerOverride`.
1500
+ */
1501
+ interface ContainerOverrideIR {
1502
+ /** e.g. the egress method name, or `"enableInternet: true"`. */
1503
+ detail: string;
1504
+ /** Export binding name of the procedure performing the call. */
1505
+ exportName: string;
1506
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1507
+ file: string;
1508
+ /** Which override shape matched. */
1509
+ kind: "egress_relaxation" | "enable_internet";
1510
+ /** 1-based line of the call, or `0` when unknown. */
1511
+ line: number;
1512
+ }
838
1513
  /**
839
- * Discover `ctx.db.query("table")…` reads under the lunora source directory and
840
- * reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
841
- * returnedan unfiltered read is never a `filter_without_index` candidate, so
842
- * dropping the rest keeps the lint input small.
843
- */
844
- declare const discoverQueries: (project: Project, lunoraDirectory: string) => QueryReadIR[];
1514
+ * One `buildImageDeliveryUrl({ key, })` call (`@lunora/bindings/images`) whose
1515
+ * `key` the CDN transform's source image, an absolute URL or an
1516
+ * origin-relative key is derived from the handler's `args` with no
1517
+ * server-side scoping the `images_url_source_from_user_input` lint input.
1518
+ * `ctx.images.transform`/`info` take image *bytes*, never a URL, so they are not
1519
+ * sinks; only the `key` of `buildImageDeliveryUrl` accepts a URL-or-key source
1520
+ * and is inspected. An arg-derived `key` lets any caller point the CDN's
1521
+ * `/cdn-cgi/image/` transform at an attacker-chosen origin (SSRF / open proxy)
1522
+ * or at an arbitrary key under the account's own store. A fixed literal, or a
1523
+ * key scoped by a server-trusted `ctx.*` value, is not recorded. Structurally
1524
+ * identical to `AdvisorImageDeliveryUrlAccess`.
1525
+ */
1526
+ interface ImageDeliveryUrlAccessIR {
1527
+ /** Export binding name of the procedure performing the `buildImageDeliveryUrl` call. */
1528
+ exportName: string;
1529
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1530
+ file: string;
1531
+ /** 1-based line of the `buildImageDeliveryUrl` call, or `0` when unknown. */
1532
+ line: number;
1533
+ }
845
1534
  /**
846
- * Discover `ctx.r2sql` accesses lexically inside the handler body of every
847
- * exported `query(...)` / `mutation(...)` registration under the lunora source
848
- * directory the `r2sql_outside_action` lint input. `action(...)` (and
849
- * `stream(...)`) registrations are intentionally skipped: R2 SQL is the
850
- * external, non-reactive surface that belongs in actions.
851
- *
852
- * Traversal is scoped to the handler node (not the whole declaration), mirroring
853
- * `discoverNondeterministicCalls` so a `ctx.r2sql` touch in a sibling helper
854
- * outside the handler is not attributed to the query/mutation. One
855
- * {@link R2sqlCallIR} is produced per access site.
856
- */
857
- declare const discoverR2sqlCalls: (project: Project, lunoraDirectory: string) => R2sqlCallIR[];
858
- declare const discoverRlsProcedures: (project: Project, lunoraDirectory: string) => RlsProcedureIR[];
1535
+ * One `createAuth({...})` call's configuration snapshot the shared input for
1536
+ * the five `auth_*` security lints (trusted-origins wildcard, CSRF check
1537
+ * disabled, secure cookies disabled, email verification disabled, session
1538
+ * freshAge zero). Matched by callee NAME (an `import`-agnostic, fail-closed
1539
+ * convention the other feeders share), so a re-export or alias still resolves.
1540
+ * When the config argument isn't a statically-analyzable object literal (a
1541
+ * top-level spread, or not an object literal at all), `analyzable` is `false`
1542
+ * and every boolean fact defaults to its SAFE (not-flagged) value — an opaque
1543
+ * config can't be relied on either way. Structurally identical to
1544
+ * `AdvisorAuthConfig`.
1545
+ */
1546
+ interface AuthConfigIR {
1547
+ /** `true` when the call's config argument was a static object literal the feeder could read. */
1548
+ analyzable: boolean;
1549
+ /** `advanced.disableCSRFCheck === true`. */
1550
+ disableCsrfCheck: boolean;
1551
+ /** `emailAndPassword.enabled === true`. */
1552
+ emailPasswordEnabled: boolean;
1553
+ /** Export binding name enclosing the `createAuth(...)` call. */
1554
+ exportName: string;
1555
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1556
+ file: string;
1557
+ /** 1-based line of the `createAuth(...)` call, or `0` when unknown. */
1558
+ line: number;
1559
+ /** `emailAndPassword.requireEmailVerification === true` present. */
1560
+ requireEmailVerification: boolean;
1561
+ /** `trustedOrigins` array literal contains a `"*"` element. */
1562
+ /** `plugins` includes `scim(...)` while `database` is a non-transactional Lunora adapter — a combination that throws at runtime. */
1563
+ scimOnNonTransactionalAdapter: boolean;
1564
+ /** `advanced.useSecureCookies === false`. */
1565
+ secureCookiesDisabled: boolean;
1566
+ /** `session.freshAge === 0` (explicit literal). */
1567
+ sessionFreshAgeZero: boolean;
1568
+ trustedOriginsWildcard: boolean;
1569
+ }
859
1570
  /**
860
- * Aggregate the schema-wide RLS metadata the studio's read-only inspector reads:
861
- * every statically-discovered `(table, on, procedure)` policy entry plus every
862
- * role declared via `rls(policies, { roles })`. Walks the same builder chains as
863
- * {@link discoverRlsProcedures} but extracts the richer `{ on }` operation +
864
- * role/permission shape rather than the lint's table-name set.
865
- *
866
- * Only the **builder** form (`c.use(rls(...)).query(...)`) can declare policies,
867
- * so bare-factory procedures contribute nothing. The `when` predicate is never
868
- * read it's an opaque JS closure whose logic belongs in code, not the UI.
869
- * Roles are deduped by name (first declaration wins) so a role registered on
870
- * several procedures lists once.
871
- */
872
- declare const discoverRlsMetadata: (project: Project, lunoraDirectory: string) => RlsMetadataIR;
1571
+ * One `rateLimit`/`dbRateLimit` middleware call (`@lunora/ratelimit`) whose
1572
+ * `key` selector — the per-caller rate-limit sub-key, `(ctx) => string |
1573
+ * undefined` is derived from the handler's `args` with no server-side
1574
+ * scoping (no reference to the trusted `ctx` binding anywhere in the selector)
1575
+ * the `ratelimit_key_spoofable_or_global` lint input. A key an attacker
1576
+ * controls lets them rotate it per request and bypass the limit entirely,
1577
+ * defeating its purpose. A selector scoped by `ctx` (e.g. `ctx.auth.userId`,
1578
+ * `ctx.ip`), or one with no `args` reference at all (a fixed/global bucket —
1579
+ * the "no key" case this lint deliberately does not flag, to keep it low-FP),
1580
+ * is not recorded. Structurally identical to `AdvisorRatelimitKeySelector`.
1581
+ */
1582
+ interface RatelimitKeySelectorIR {
1583
+ /** The `rateLimit`/`dbRateLimit` callee invoked. */
1584
+ callee: string;
1585
+ /** Export binding name of the procedure whose `.use(...)` chain carries the call. */
1586
+ exportName: string;
1587
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1588
+ file: string;
1589
+ /** The rate limit's `name` argument (the second positional argument), or `""` when not a string literal. */
1590
+ limitName: string;
1591
+ /** 1-based line of the `rateLimit`/`dbRateLimit` call, or `0` when unknown. */
1592
+ line: number;
1593
+ }
873
1594
  /**
874
- * Load `&lt;projectRoot>/lunora/schema.ts`, find `defineSchema({...})`, and
875
- * return a structural IR. Throws if the file or call cannot be found.
876
- */
877
- declare const discoverSchema: (project: Project, schemaPath: string, projectRoot?: string) => SchemaIR;
1595
+ * One payload-derived privileged dispatch — a `ctx.run`/`context.run` back into a
1596
+ * Lunora function from inside a `defineQueue` push handler or a `defineWorkflow`
1597
+ * handler, whose args reference the handler's untrusted payload (`context.params`
1598
+ * for a workflow, a `for (… of batch.messages)` body for a queue) — the
1599
+ * `privileged_dispatch_unvalidated_payload` lint input. Both handler kinds run
1600
+ * under the **system identity** (RLS disabled), so forwarding attacker-influenced
1601
+ * payload into the dispatch bypasses the target's row policy. The resolved
1602
+ * `targetFile`/`targetExport` let the lint join RLS-procedure evidence and fire
1603
+ * only for RLS-gated targets. Structurally identical to `AdvisorPrivilegedDispatch`.
1604
+ */
1605
+ interface PrivilegedDispatchIR {
1606
+ /** `"queue"` for a `defineQueue` handler, `"workflow"` for a `defineWorkflow` handler. */
1607
+ dispatchKind: "queue" | "workflow";
1608
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1609
+ file: string;
1610
+ /** Export binding name of the handler performing the dispatch. */
1611
+ handlerExport: string;
1612
+ /** 1-based line of the dispatch call, or `0` when unknown. */
1613
+ line: number;
1614
+ /** Export name of the dispatched target (`send` in `api.messages.send`). */
1615
+ targetExport: string;
1616
+ /** File path of the dispatched target relative to `lunora/` (`messages` in `api.messages.send`). */
1617
+ targetFile: string;
1618
+ }
878
1619
  /**
879
- * Aggregate the schema-wide storage-rule metadata the studio's inspector reads:
880
- * every statically-discovered `(bucket, on, prefix, procedure)` entry across all
881
- * `.use(storageRules(...))` chains. Only the builder form can declare rules, so
882
- * bare-factory procedures contribute nothing.
883
- */
884
- declare const discoverStorageRulesMetadata: (project: Project, lunoraDirectory: string) => StorageRulesMetadataIR;
1620
+ * One discovered `httpRoute.<verb>("/admin/…")` route on an admin/privileged-looking
1621
+ * path, with whether its builder chain references an auth/admin guard — the
1622
+ * `admin_route_without_guard` lint input. Structurally identical to
1623
+ * `AdvisorAdminRoute`.
1624
+ */
1625
+ interface AdminRouteIR {
1626
+ /** Export binding name of the route handler. */
1627
+ exportName: string;
1628
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1629
+ file: string;
1630
+ /** HTTP verb the route binds to (uppercased), e.g. `"POST"`. */
1631
+ method: string;
1632
+ /** The route path, e.g. `/admin/users`. */
1633
+ path: string;
1634
+ /** `true` when the handler body references an auth/session/admin guard (`ctx.auth`, `getSession`, `requireAdmin`, …). */
1635
+ usesGuard: boolean;
1636
+ }
1637
+ /**
1638
+ * One tracked `ctx.storage.<bucket>.<method>(...)` upload/signing call — the
1639
+ * shared input for the storage config-hygiene security lints
1640
+ * (`storage_upload_without_content_type_allowlist`, `storage_upload_without_max_size`,
1641
+ * `storage_generate_upload_url_no_content_type_pin`, `storage_presigned_url_for_private_content`).
1642
+ * `upload`/`store` carry the `UploadOptions` guards (`allowedContentTypes` /
1643
+ * `maxSize`); `generateUploadUrl` carries the signed-PUT `contentType` pin;
1644
+ * `getPresignedUrl`/`getSignedUrl` carry a statically-known `expiresInSeconds`
1645
+ * literal. `presentKeys` is empty (and `expiresInSeconds` unset) when the
1646
+ * options argument was absent, a non-literal, or a spread — see `analyzable`.
1647
+ * Structurally identical to `AdvisorStorageUpload`.
1648
+ */
1649
+ interface StorageUploadIR {
1650
+ /** `true` when the call's options-object argument (or its deliberate absence) was statically resolvable. */
1651
+ analyzable: boolean;
1652
+ /** Numeric literal value of an `expiresInSeconds` option, when statically known (`getSignedUrl` / `getPresignedUrl` only). */
1653
+ expiresInSeconds?: number;
1654
+ /** Export binding name of the procedure performing the call. */
1655
+ exportName: string;
1656
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1657
+ file: string;
1658
+ /** 1-based line of the call, or `0` when unknown. */
1659
+ line: number;
1660
+ /** The `ctx.storage` method invoked. */
1661
+ method: "generateUploadUrl" | "getPresignedUrl" | "getSignedUrl" | "store" | "upload";
1662
+ /** Options-object keys present at the call site (empty when not `analyzable`, or when no options argument was passed). */
1663
+ presentKeys: string[];
1664
+ }
1665
+ /**
1666
+ * One discovered `httpAction`/`httpRoute` handler in `lunora/` that performs a
1667
+ * side effect (`ctx.runMutation` / `ctx.runAction` / a `ctx.db.{insert,patch,
1668
+ * replace,delete,insertManyUnsafe}` write) from the HTTP edge, with whether it
1669
+ * reads `ctx.auth` — the `http_action_missing_auth_guard` lint input. A handler
1670
+ * that mutates state or dispatches an action without ever consulting the request
1671
+ * identity is an unauthenticated write bypassing identity/RLS. Only handlers with
1672
+ * a statically-resolvable inline body and `ctx` binding are recorded (fail-safe
1673
+ * under-report); read-only handlers are never recorded. Structurally identical to
1674
+ * `AdvisorHttpActionGuard`.
1675
+ */
1676
+ interface HttpActionGuardIR {
1677
+ /** Export binding name of the handler (or `"<module>"` when mounted inline / not a named binding). */
1678
+ exportName: string;
1679
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1680
+ file: string;
1681
+ /** Which HTTP surface the handler is: a raw `httpAction` or a typed `httpRoute` route. */
1682
+ kind: "httpAction" | "httpRoute";
1683
+ /** 1-based line of the handler call, or `0` when unknown. */
1684
+ line: number;
1685
+ /** For an `httpRoute`, the uppercased verb (`"POST"`); absent for a raw `httpAction`. */
1686
+ method?: string;
1687
+ /** `true` when the handler reads `ctx.auth` (a direct member access or a `const { auth } = ctx` destructure). */
1688
+ readsAuth: boolean;
1689
+ /** The first side effect found, as a stable label: `runMutation`, `runAction`, or `db.<method>`. */
1690
+ sideEffect: string;
1691
+ }
1692
+ /**
1693
+ * One response-header write, inside an `httpAction` handler, whose value is derived
1694
+ * from raw request input (`request.headers`, `request.url`/query, `await
1695
+ * request.json()`) with no CR/LF sanitizer — the
1696
+ * `http_action_response_header_injection` lint input. A `Request`-derived string
1697
+ * placed verbatim into a response header lets a caller smuggle `\r\n` and inject
1698
+ * extra headers or split the response (header injection / response splitting). Only
1699
+ * sites whose value is request-tainted AND unguarded are recorded: a value routed
1700
+ * through a CR/LF guard (`isSafeHeaderValue`), a URL/URI encoder
1701
+ * (`encodeURIComponent`/`encodeURI`), a numeric coercion (`Number`/`parseInt`/
1702
+ * `parseFloat`), or `btoa` is treated as safe and never recorded (`String(...)` /
1703
+ * `.toString()` are NOT sanitizers — they don't strip CR/LF). Structurally
1704
+ * identical to `AdvisorHttpHeaderWrite`.
1705
+ */
1706
+ interface HttpHeaderWriteIR {
1707
+ /** Export binding name of the enclosing handler, or `"<module>"` when mounted inline. */
1708
+ exportName: string;
1709
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1710
+ file: string;
1711
+ /** The header name being written (`"location"`), or `""` when the key is not a string literal. */
1712
+ headerName: string;
1713
+ /** 1-based line of the request-tainted header value. */
1714
+ line: number;
1715
+ /** How the header was written. */
1716
+ via: "headers-append" | "headers-ctor" | "headers-set" | "response-init";
1717
+ }
1718
+ /**
1719
+ * One rate-limit / Turnstile middleware call in `lunora/` — the
1720
+ * `ratelimit_middleware_fail_open` lint input. `rateLimit`/`dbRateLimit`
1721
+ * (`@lunora/ratelimit`) and `verifyTurnstileMiddleware` (`@lunora/auth`) each
1722
+ * accept a `failOpen` escape hatch that admits every request when the
1723
+ * limiter/siteverify is unavailable; `failOpen` is `true` only when the options
1724
+ * literal set it to the boolean literal `true` (anything else is fail-closed).
1725
+ * The lint escalates a fail-open guard to a finding when the guarded procedure
1726
+ * (`exportName`/`limitName`) looks auth/payment-sensitive. Structurally
1727
+ * identical to `AdvisorFailOpenGuard`.
1728
+ */
1729
+ interface FailOpenGuardIR {
1730
+ /** The middleware factory at the call site: `rateLimit` / `dbRateLimit` / `verifyTurnstileMiddleware`. */
1731
+ callee: string;
1732
+ /** Export binding name of the procedure the guard is attached to, or `"<module>"` at file scope. */
1733
+ exportName: string;
1734
+ /** `true` only when the options literal set `failOpen: true` as a boolean literal; a non-literal or absent option is treated as fail-closed. */
1735
+ failOpen: boolean;
1736
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1737
+ file: string;
1738
+ /** The rate-limit `name` (second string argument) for `rateLimit`/`dbRateLimit`; `""` for `verifyTurnstileMiddleware`. */
1739
+ limitName: string;
1740
+ /** 1-based line of the middleware call, or `0` when unknown. */
1741
+ line: number;
1742
+ }
1743
+ /**
1744
+ * One `ctx.flags.boolean("key", <boolean-literal>)` read in `lunora/` — the
1745
+ * `flag_gates_security_with_unsafe_default` lint input. OpenFeature returns the
1746
+ * `defaultValue` when the provider errors, so a fail-open default on a
1747
+ * security-shaped key silently opens access during an outage. Only reads with a
1748
+ * statically-known string key and boolean-literal default are recorded; the lint
1749
+ * owns the security-shape + polarity judgment. Structurally identical to
1750
+ * `AdvisorFlagSecurityDefault`.
1751
+ */
1752
+ interface FlagSecurityDefaultIR {
1753
+ /** The boolean-literal default returned on a provider outage (fail-open value). */
1754
+ defaultValue: boolean;
1755
+ /** Export binding name of the procedure performing the flag read, or `"<module>"` at file scope. */
1756
+ exportName: string;
1757
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1758
+ file: string;
1759
+ /** The flag key — the first string-literal argument of `ctx.flags.boolean`. */
1760
+ key: string;
1761
+ /** 1-based line of the `ctx.flags.boolean` call, or `0` when unknown. */
1762
+ line: number;
1763
+ }
1764
+ /**
1765
+ * One `generateText` / `streamText` call in `lunora/` whose `tools` reach a
1766
+ * privileged side effect (a DB write, function dispatch, or outbound
1767
+ * fetch/mail/queue send). `userInputDerived` records whether the model input
1768
+ * (`prompt`/`messages`/`system`) flows from the handler's `args`; the
1769
+ * `ai_tool_side_effect_prompt_injection` lint fires only when it does.
1770
+ * Structurally identical to `AdvisorAiToolSideEffect`.
1771
+ */
1772
+ interface AiToolSideEffectIR {
1773
+ /** Export binding name of the procedure performing the call. */
1774
+ exportName: string;
1775
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1776
+ file: string;
1777
+ /** 1-based line of the generation call, or `0` when unknown. */
1778
+ line: number;
1779
+ /** The generation entrypoint invoked. */
1780
+ method: "generateText" | "streamText";
1781
+ /** The privileged side-effect sink a model-callable tool reaches (`ctx.db.insert`, `ctx.run`, `ctx.fetch`, …). */
1782
+ sideEffect: string;
1783
+ /** `true` when a model-input option is derived from the handler's `args` (a bare `args.x`, or a name destructured from `args`). */
1784
+ userInputDerived: boolean;
1785
+ }
1786
+ /**
1787
+ * One `<receiver>.identity.<key>` claim read in `lunora/`, where `<receiver>` is
1788
+ * an RLS/mask policy `auth` (or `ctx.auth`/`context.auth`). `declared` records
1789
+ * whether `<key>` is in the app's `defineIdentity({ ... })` contract (or the
1790
+ * always-present `userId`); the `identity_undeclared_claim_trusted` lint fires on
1791
+ * the undeclared reads. Emitted only when a resolvable identity contract exists.
1792
+ * Structurally identical to `AdvisorIdentityClaimRead`.
1793
+ */
1794
+ interface IdentityClaimReadIR {
1795
+ /** `true` when `key` is a declared claim (in the `defineIdentity` contract, or the always-present `userId`). */
1796
+ declared: boolean;
1797
+ /** Export binding name of the enclosing declaration (`<module>` at file scope). */
1798
+ exportName: string;
1799
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1800
+ file: string;
1801
+ /** The claim key read off the identity bag. */
1802
+ key: string;
1803
+ /** 1-based line of the read, or `0` when unknown. */
1804
+ line: number;
1805
+ }
1806
+ /**
1807
+ * One payment webhook-adapter construction in `lunora/` (`createStripeAdapter` /
1808
+ * `createPolarAdapter` / `createAutumnAdapter` / `createDodoPaymentsAdapter`).
1809
+ * `toleranceSeconds` carries the statically-known `webhookToleranceSeconds`
1810
+ * replay window when it is a plain numeric literal; the payment-webhook
1811
+ * wide-tolerance lint fires when it exceeds a conservative ceiling. Structurally
1812
+ * identical to `AdvisorPaymentWebhook`.
1813
+ */
1814
+ interface PaymentWebhookIR {
1815
+ /** The adapter factory invoked. */
1816
+ callee: "createAutumnAdapter" | "createDodoPaymentsAdapter" | "createPolarAdapter" | "createStripeAdapter";
1817
+ /** Export binding name of the enclosing declaration (`<module>` at file scope). */
1818
+ exportName: string;
1819
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1820
+ file: string;
1821
+ /** 1-based line of the construction, or `0` when unknown. */
1822
+ line: number;
1823
+ /** Statically-known `webhookToleranceSeconds` literal, when present and a plain numeric literal. */
1824
+ toleranceSeconds?: number;
1825
+ }
1826
+ /**
1827
+ * One `ctx.db.<table>.findMany({ includeDeleted })` list read whose
1828
+ * `includeDeleted` is either a hardcoded `true` or derived from the handler's
1829
+ * `args` — the `soft_delete_include_deleted_from_args` lint input. The lint joins
1830
+ * `table` against the schema's soft-delete tables and `visibility` against
1831
+ * `.public()` before flagging. Structurally identical to `AdvisorSoftDeleteRead`
1832
+ * so values pass straight through without conversion.
1833
+ */
1834
+ interface SoftDeleteReadIR {
1835
+ /** Export binding name of the procedure performing the read. */
1836
+ exportName: string;
1837
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1838
+ file: string;
1839
+ /** `true` when `includeDeleted` was derived from the handler's `args` (any caller can flip it). */
1840
+ fromArgs: boolean;
1841
+ /** `true` when `includeDeleted` was a hardcoded `true` literal (always resurfaces soft-deleted rows). */
1842
+ hardcodedTrue: boolean;
1843
+ /** 1-based line of the read call. */
1844
+ line: number;
1845
+ /** Table read, or `""` when the table-arg form's first argument wasn't a string literal. */
1846
+ table: string;
1847
+ /** `"internal"` for `internalQuery` / `internalMutation` / `internalAction`. */
1848
+ visibility: "internal" | "public";
1849
+ }
1850
+ /**
1851
+ * One `ctx.db.<table>.findMany({ with: { <rel> } })` relation-hydrating list read
1852
+ * — the `masked_relation_leak_via_with` lint input. Column masking does not
1853
+ * descend into `with`-hydrated relations, so a masked table surfaced only through
1854
+ * a `with` on an unprotected parent read is returned in the clear. The lint
1855
+ * resolves each relation accessor to its target table and joins it against the
1856
+ * discovered mask evidence before flagging. Structurally identical to
1857
+ * `AdvisorRelationLoad` so values pass straight through without conversion.
1858
+ */
1859
+ interface RelationLoadIR {
1860
+ /** Export binding name of the procedure performing the read. */
1861
+ exportName: string;
1862
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1863
+ file: string;
1864
+ /** 1-based line of the read call. */
1865
+ line: number;
1866
+ /** Parent table the read targets, or `""` when the table-arg form's first argument wasn't a string literal. */
1867
+ parentTable: string;
1868
+ /** Relation accessor names named in the read's `with: { … }` map — matched against the parent table's declared relations. */
1869
+ relations: string[];
1870
+ /** `"internal"` for `internalQuery` / `internalMutation` / `internalAction`. */
1871
+ visibility: "internal" | "public";
1872
+ }
1873
+ /**
1874
+ * One `query` handler whose `return` hands back the raw rows of a table — the
1875
+ * result of a `ctx.db.<table>.findMany()` / `.findFirst()` / `.get()` read, or a
1876
+ * `ctx.db.query("<table>")…collect()` fluent chain — returned directly (or through
1877
+ * one local `const` hop) with no hand-built projection. The
1878
+ * `output_projection_missing_on_public_read` lint keeps only `visibility ===
1879
+ * "public"` rows with no `.output(...)` / `.use(mask(...))` on the chain, then
1880
+ * joins `table` against the schema and flags one whose columns are PII-named.
1881
+ * Structurally identical to `AdvisorRawRowReturn` so values pass straight through
1882
+ * without conversion.
1883
+ */
1884
+ interface RawRowReturnIR {
1885
+ /** Export binding name of the query returning the raw rows. */
1886
+ exportName: string;
1887
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1888
+ file: string;
1889
+ /** 1-based line of the `return` (or concise-body) expression. */
1890
+ line: number;
1891
+ /** Table whose raw rows are returned, or `""` when the read's table wasn't a string literal. */
1892
+ table: string;
1893
+ /** `true` when the procedure's builder chain carries a `.use(mask(...))` step. */
1894
+ usesMask: boolean;
1895
+ /** `true` when the procedure's builder chain carries an `.output(...)` return-shape projection. */
1896
+ usesOutput: boolean;
1897
+ /** `"internal"` for `internalQuery`; `"public"` for `query`. */
1898
+ visibility: "internal" | "public";
1899
+ }
1900
+ /**
1901
+ * One `query`/`mutation` handler that gates a `ctx.db.get`/`patch`/`delete` on a
1902
+ * null-checked `ctx.db.normalizeId(table, id)` result — the
1903
+ * `normalize_id_used_as_authorization` lint input. `normalizeId` validates an id's
1904
+ * structural shape only (it never reads the database), so a non-null result proves
1905
+ * the id is well-formed, never that the caller owns the row; gating access on it is
1906
+ * an IDOR. The lint owns the negative proof — it keeps only `visibility === "public"`
1907
+ * rows with no `.use(rls(...))` and no ownership/identity mention (`mentionsOwnership`),
1908
+ * then joins `table` against the schema's RLS mode before flagging. Structurally
1909
+ * identical to `AdvisorNormalizeIdAuthorization` so values pass straight through.
1910
+ */
1911
+ interface NormalizeIdAuthorizationIR {
1912
+ /** Export binding name of the procedure performing the normalize-then-access. */
1913
+ exportName: string;
1914
+ /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1915
+ file: string;
1916
+ /** 1-based line of the `ctx.db.normalizeId(...)` call the access is gated on. */
1917
+ line: number;
1918
+ /** `true` when the handler anywhere reads an ownership-named identifier or `ctx.auth`/`ctx.identity`/… — an intervening ownership signal. */
1919
+ mentionsOwnership: boolean;
1920
+ /** The id-first `ctx.db` sink the normalized id reaches. */
1921
+ sinkMethod: "delete" | "get" | "patch";
1922
+ /** Table named in the `normalizeId` call, or `""` when its table argument wasn't a string literal. */
1923
+ table: string;
1924
+ /** `true` when the procedure's builder chain carries a `.use(rls(...))` step. */
1925
+ usesRls: boolean;
1926
+ /** `"internal"` for `internalQuery`/`internalMutation`; `"public"` for `query`/`mutation`. */
1927
+ visibility: "internal" | "public";
1928
+ }
1929
+ /**
1930
+ * One committed `wrangler.jsonc` `vars` entry whose value is a plaintext secret —
1931
+ * the `plaintext_secret_in_wrangler_vars` lint input. `vars` are baked into the
1932
+ * deployed Worker in cleartext and checked into source control, so a real API key
1933
+ * / token / private key there ships the secret to every reader of the repo and the
1934
+ * bundle; it belongs in a Secrets Store binding or `wrangler secret put`. Produced
1935
+ * by `@lunora/config` (which reads `wrangler.jsonc`), not a ts-morph feeder —
1936
+ * codegen only passes it through. Structurally identical to `AdvisorWranglerVariable`.
1937
+ */
1938
+ interface WranglerVariableIR {
1939
+ /** The `wrangler.jsonc` file the var was read from, relative to the project root. */
1940
+ file: string;
1941
+ /** The offending `vars` key (e.g. `STRIPE_SECRET_KEY`). */
1942
+ key: string;
1943
+ /** Heuristic that matched, e.g. `stripe_live_key` / `private_key` / `secret_named_var`. */
1944
+ kind: string;
1945
+ /** Redacted preview of the value (first few chars + length) for the finding detail — never the full secret. */
1946
+ preview: string;
1947
+ }
1948
+ interface ProjectIR {
1949
+ crons: ReadonlyArray<CronJobIR>;
1950
+ functions: ReadonlyArray<FunctionIR>;
1951
+ /** Typed REST routes discovered from `httpRoute.<verb>(...)` builder chains. */
1952
+ httpRoutes: ReadonlyArray<HttpRouteIR>;
1953
+ migrations: ReadonlyArray<MigrationIR>;
1954
+ schema: SchemaIR;
1955
+ }
1956
+ /**
1957
+ * Named inputs for {@link lintSchema}. Every feeder is a discrete key rather than
1958
+ * a positional argument: the feeder list grows every few releases and many IR
1959
+ * types are structurally similar (`{file, exportName, line}`-shaped evidence),
1960
+ * so a positional call was a silent-transposition hazard — swapping two adjacent
1961
+ * arguments could typecheck yet feed the wrong evidence to the wrong lint and
1962
+ * corrupt a security advisory. `schema` is the only required field; every other
1963
+ * feeder defaults to "not analyzed" when omitted.
1964
+ */
1965
+ interface LintSchemaOptions {
1966
+ adminRoutes?: ReadonlyArray<AdminRouteIR>;
1967
+ aiRawRuns?: ReadonlyArray<AiRawRunIR>;
1968
+ aiToolSideEffects?: ReadonlyArray<AiToolSideEffectIR>;
1969
+ argumentDerivedFetches?: ReadonlyArray<ArgumentDerivedFetchIR>;
1970
+ argumentValidators?: ReadonlyArray<ArgumentValidatorIR>;
1971
+ authApiCalls?: ReadonlyArray<AuthApiCallIR>;
1972
+ authConfigs?: ReadonlyArray<AuthConfigIR>;
1973
+ browserUrlAccesses?: ReadonlyArray<BrowserUrlAccessIR>;
1974
+ configCalls?: ReadonlyArray<ConfigCallIR>;
1975
+ containerKeyAccesses?: ReadonlyArray<ContainerKeyAccessIR>;
1976
+ containerOverrides?: ReadonlyArray<ContainerOverrideIR>;
1977
+ containers?: ReadonlyArray<ContainerIR>;
1978
+ exportSinks?: ReadonlyArray<AdvisorExportSink>;
1979
+ failOpenGuards?: ReadonlyArray<FailOpenGuardIR>;
1980
+ flagSecurityDefaults?: ReadonlyArray<FlagSecurityDefaultIR>;
1981
+ geoIndexUsages?: ReadonlyArray<AdvisorGeoIndexUsage>;
1982
+ httpActionGuards?: ReadonlyArray<HttpActionGuardIR>;
1983
+ httpHeaderWrites?: ReadonlyArray<HttpHeaderWriteIR>;
1984
+ identityClaimReads?: ReadonlyArray<IdentityClaimReadIR>;
1985
+ imageDeliveryUrlAccesses?: ReadonlyArray<ImageDeliveryUrlAccessIR>;
1986
+ inserts?: ReadonlyArray<InsertWriteIR>;
1987
+ kvKeyAccesses?: ReadonlyArray<KvKeyAccessIR>;
1988
+ mailRecipientAccesses?: ReadonlyArray<MailRecipientAccessIR>;
1989
+ maskProcedures?: ReadonlyArray<MaskProcedureIR>;
1990
+ maskStrategies?: ReadonlyArray<MaskStrategyIR>;
1991
+ mutatorWrites?: ReadonlyArray<MutatorWriteIR>;
1992
+ nondeterministicCalls?: ReadonlyArray<NondeterministicCallIR>;
1993
+ normalizeIdAuthorizations?: ReadonlyArray<NormalizeIdAuthorizationIR>;
1994
+ notifyCalls?: ReadonlyArray<AdvisorNotifyCall>;
1995
+ notifyConfig?: AdvisorNotifyConfig;
1996
+ ownerFieldWrites?: ReadonlyArray<OwnerFieldWriteIR>;
1997
+ paymentWebhooks?: ReadonlyArray<PaymentWebhookIR>;
1998
+ privilegedDispatches?: ReadonlyArray<PrivilegedDispatchIR>;
1999
+ procedureProtections?: ReadonlyArray<ProcedureMiddlewareIR>;
2000
+ queries?: ReadonlyArray<QueryReadIR>;
2001
+ queues?: ReadonlyArray<QueueIR>;
2002
+ r2sqlCalls?: ReadonlyArray<R2sqlCallIR>;
2003
+ ratelimitKeySelectors?: ReadonlyArray<RatelimitKeySelectorIR>;
2004
+ rawRowReturns?: ReadonlyArray<RawRowReturnIR>;
2005
+ relationLoads?: ReadonlyArray<RelationLoadIR>;
2006
+ rlsProcedures?: ReadonlyArray<RlsProcedureIR>;
2007
+ schema: SchemaIR;
2008
+ secretLiterals?: ReadonlyArray<SecretLiteralIR>;
2009
+ shapes?: ReadonlyArray<ShapeIR>;
2010
+ softDeleteReads?: ReadonlyArray<SoftDeleteReadIR>;
2011
+ sqlInterpolations?: ReadonlyArray<SqlInterpolationIR>;
2012
+ storageKeyAccesses?: ReadonlyArray<StorageKeyAccessIR>;
2013
+ storageUploads?: ReadonlyArray<StorageUploadIR>;
2014
+ unrestrictedWhereBranches?: ReadonlyArray<UnrestrictedWhereBranchIR>;
2015
+ vectorNamespaceAccesses?: ReadonlyArray<VectorNamespaceAccessIR>;
2016
+ workflowCalls?: ReadonlyArray<WorkflowCallIR>;
2017
+ workflows?: ReadonlyArray<WorkflowIR>;
2018
+ wranglerVariables?: ReadonlyArray<WranglerVariableIR>;
2019
+ }
2020
+ /**
2021
+ * Normalize feeder options into the advisor's {@link LintContext} — the input
2022
+ * both `runAdvisor` and `scoreAdvisor` take. Shared by {@link lintSchema} so the
2023
+ * lint run and the scored map always see byte-identical evidence.
2024
+ *
2025
+ * Exported instead of a `mapSchema(options)` convenience that lints *and* scores:
2026
+ * such a wrapper would either re-run every rule or need a `findings` escape hatch
2027
+ * nothing could validate against its `options`, so mismatched findings would
2028
+ * silently produce a wrong map. Two lines at the call site buys that away:
2029
+ *
2030
+ * ```ts
2031
+ * const context = toAdvisorContext(options);
2032
+ * const map = scoreAdvisor(context.procedureProtections ?? [], runAdvisor(context, { source: "static" }));
2033
+ * ```
2034
+ */
2035
+ declare const toAdvisorContext: (options: LintSchemaOptions) => LintContext;
2036
+ /**
2037
+ * Run the static lints against a discovered {@link SchemaIR} and the reads/writes/calls
2038
+ * found in function bodies: query reads feed `filter_without_index`, insert writes
2039
+ * feed `table_without_insert`, authApi calls feed `auth_api_call_without_headers`,
2040
+ * rls procedure snapshots feed `rls_uncovered_table`, mask procedure
2041
+ * snapshots feed `mask_uncovered_pii_column`, and per-column mask strategies
2042
+ * feed `mask_weak_hash_strategy_on_pii`; declared containers
2043
+ * feed the `container_*` lints; declared workflows (with their durable step labels)
2044
+ * + `ctx.workflows.get(...)` call sites feed the `workflow_unused` /
2045
+ * `workflow_unknown_target` / duplicate-step-name lints; non-deterministic
2046
+ * calls inside query/mutation handlers feed the `nondeterministic_query_mutation` lint
2047
+ * (all default empty for callers that don't analyze functions/containers/workflows).
2048
+ * The IR types are structurally identical to the advisor's evidence types so they
2049
+ * pass straight through without conversion. Returns the findings; surfacing them
2050
+ * (console, error overlay, studio Advisors table) is the caller's choice.
2051
+ */
2052
+ declare const lintSchema: (options: LintSchemaOptions) => Finding[];
2053
+ /**
2054
+ * Render advisor findings as a single multi-line string for console surfacing:
2055
+ * a one-line summary header followed by one `[LEVEL] name: detail` line per
2056
+ * finding. Returns `""` when there are no findings.
2057
+ */
2058
+ declare const formatAdvisories: (findings: ReadonlyArray<Finding>) => string;
2059
+ /**
2060
+ * The canonical capability list. **Order is load-bearing** for the `emit-app.ts`
2061
+ * long-tail: the fluent methods are emitted in the order the `appMethod`-bearing
2062
+ * rows appear here, so this array is ordered to reproduce the original
2063
+ * `LONG_TAIL` sequence (ai, analytics, browser, hyperdrive, images, kv, payment,
2064
+ * r2sql, vectors). The `serverCtxField` rows are referenced by name in the ctx
2065
+ * interface templates, so their order here is not output-affecting.
2066
+ */
2067
+ declare const CAPABILITY_ROWS: readonly [{
2068
+ readonly contextProperty: "access";
2069
+ readonly key: "access";
2070
+ readonly moduleSpecifier: "@lunora/cloudflare-access";
2071
+ }, {
2072
+ readonly appMethod: {
2073
+ readonly configKey: "ai";
2074
+ readonly doc: "Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).";
2075
+ readonly method: "ai";
2076
+ };
2077
+ readonly contextProperty: "ai";
2078
+ readonly key: "ai";
2079
+ readonly moduleSpecifier: "@lunora/ai";
2080
+ }, {
2081
+ readonly appMethod: {
2082
+ readonly configKey: "analytics";
2083
+ readonly doc: "Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).";
2084
+ readonly method: "analytics";
2085
+ };
2086
+ readonly contextProperty: "analytics";
2087
+ readonly key: "analytics";
2088
+ readonly moduleSpecifier: "@lunora/bindings/analytics";
2089
+ readonly serverCtxField: {
2090
+ readonly field: "\n /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */\n readonly analytics: import(\"@lunora/bindings/analytics\").AnalyticsClient;";
2091
+ readonly tier: "every";
2092
+ };
2093
+ }, {
2094
+ readonly appMethod: {
2095
+ readonly configKey: "browser";
2096
+ readonly doc: "Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).";
2097
+ readonly method: "browser";
2098
+ };
2099
+ readonly contextProperty: "browser";
2100
+ readonly key: "browser";
2101
+ readonly moduleSpecifier: "@lunora/browser";
2102
+ readonly serverCtxField: {
2103
+ readonly field: "\n /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */\n readonly browser: import(\"@lunora/browser\").Browser;";
2104
+ readonly tier: "action";
2105
+ };
2106
+ }, {
2107
+ readonly contextProperty: "containers";
2108
+ readonly key: "container";
2109
+ readonly moduleSpecifier: "@lunora/container";
2110
+ }, {
2111
+ readonly contextProperty: "flags";
2112
+ readonly key: "flags";
2113
+ readonly moduleSpecifier: "@lunora/flags";
2114
+ }, {
2115
+ readonly appMethod: {
2116
+ readonly configKey: "sql";
2117
+ readonly doc: "Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`.";
2118
+ readonly method: "hyperdrive";
2119
+ };
2120
+ readonly contextProperty: "sql";
2121
+ readonly key: "hyperdrive";
2122
+ readonly moduleSpecifier: "@lunora/hyperdrive";
2123
+ readonly serverCtxField: {
2124
+ readonly field: "\n /**\n * External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.\n */\n readonly sql: import(\"@lunora/hyperdrive\").SqlClient;";
2125
+ readonly tier: "action";
2126
+ };
2127
+ }, {
2128
+ readonly appMethod: {
2129
+ readonly configKey: "images";
2130
+ readonly doc: "Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`).";
2131
+ readonly method: "images";
2132
+ };
2133
+ readonly contextProperty: "images";
2134
+ readonly key: "images";
2135
+ readonly moduleSpecifier: "@lunora/bindings/images";
2136
+ readonly serverCtxField: {
2137
+ readonly field: "\n /** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */\n readonly images: import(\"@lunora/bindings/images\").Images;";
2138
+ readonly tier: "action";
2139
+ };
2140
+ }, {
2141
+ readonly appMethod: {
2142
+ readonly configKey: "kv";
2143
+ readonly doc: "Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`).";
2144
+ readonly method: "kv";
2145
+ };
2146
+ readonly contextProperty: "kv";
2147
+ readonly key: "kv";
2148
+ readonly moduleSpecifier: "@lunora/bindings/kv";
2149
+ readonly serverCtxField: {
2150
+ readonly field: "\n readonly kv: import(\"@lunora/bindings/kv\").Kv;";
2151
+ readonly tier: "every";
2152
+ };
2153
+ }, {
2154
+ readonly key: "mail";
2155
+ readonly moduleSpecifier: "@lunora/mail";
2156
+ }, {
2157
+ readonly contextProperty: "notify";
2158
+ readonly key: "notify";
2159
+ readonly moduleSpecifier: "@lunora/notify";
2160
+ }, {
2161
+ readonly appMethod: {
2162
+ readonly configKey: "payment";
2163
+ readonly doc: "Wire the payment options backing `ctx.payments`.";
2164
+ readonly method: "payment";
2165
+ };
2166
+ readonly contextProperty: "payments";
2167
+ readonly key: "payments";
2168
+ readonly moduleSpecifier: "@lunora/payment";
2169
+ }, {
2170
+ readonly appMethod: {
2171
+ readonly configKey: "x402";
2172
+ readonly doc: "Wire the x402 agent-wallet pay rail backing `ctx.x402` — a payment-enabled `fetch` that answers `402` challenges under a mandatory spend policy (ActionCtx-only; spends real funds).";
2173
+ readonly method: "x402";
2174
+ };
2175
+ readonly contextProperty: "x402";
2176
+ readonly key: "x402";
2177
+ readonly moduleSpecifier: "@lunora/x402/pay";
2178
+ }, {
2179
+ readonly contextProperty: "pipelines";
2180
+ readonly key: "pipelines";
2181
+ readonly moduleSpecifier: "@lunora/bindings/pipelines";
2182
+ readonly serverCtxField: {
2183
+ readonly field: "\n /** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */\n readonly pipelines: import(\"@lunora/bindings/pipelines\").PipelineClient;";
2184
+ readonly tier: "action";
2185
+ };
2186
+ }, {
2187
+ readonly appMethod: {
2188
+ readonly configKey: "r2sql";
2189
+ readonly doc: "Wire the R2 SQL client backing `ctx.r2sql` — build it with `createR2Sql({ accountId, apiToken, bucket })` (defaults to env `R2_SQL_TOKEN` / `R2_SQL_ACCOUNT_ID` / `R2_SQL_BUCKET`).";
2190
+ readonly method: "r2sql";
2191
+ };
2192
+ readonly contextProperty: "r2sql";
2193
+ readonly key: "r2sql";
2194
+ readonly moduleSpecifier: "@lunora/bindings/r2sql";
2195
+ readonly serverCtxField: {
2196
+ readonly field: "\n /**\n * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.\n */\n readonly r2sql: import(\"@lunora/bindings/r2sql\").R2SqlClient;";
2197
+ readonly tier: "action";
2198
+ };
2199
+ }, {
2200
+ readonly contextProperty: "scheduler";
2201
+ readonly key: "scheduler";
2202
+ readonly moduleSpecifier: "@lunora/scheduler";
2203
+ }, {
2204
+ readonly contextProperty: "storage";
2205
+ readonly key: "storage";
2206
+ readonly moduleSpecifier: "@lunora/storage";
2207
+ }, {
2208
+ readonly appMethod: {
2209
+ readonly configKey: "vectors";
2210
+ readonly doc: "Wire the Vectorize index map backing `ctx.vectors`.";
2211
+ readonly method: "vectors";
2212
+ };
2213
+ readonly contextProperty: "vectors";
2214
+ readonly key: "vectors";
2215
+ readonly moduleSpecifier: "@lunora/bindings/vectors";
2216
+ }, {
2217
+ readonly contextProperty: "workflows";
2218
+ readonly key: "workflows";
2219
+ readonly moduleSpecifier: "@lunora/workflow";
2220
+ }];
2221
+ /** The literal union of every capability id — the single source of truth for `FeatureUsage`'s keys (so they cannot drift). */
2222
+ type CapabilityKey = (typeof CAPABILITY_ROWS)[number]["key"];
2223
+ /** The default codegen target — today's behavior, byte-identical goldens. */
2224
+ declare const DEFAULT_TARGET = "cloudflare";
2225
+ /**
2226
+ * Read `target` from `<projectRoot>/lunora.json`.
2227
+ *
2228
+ * This lives in `@lunora/codegen` rather than `@lunora/config` — where the rest
2229
+ * of the `lunora.json` reading lives — because `@lunora/config` depends on
2230
+ * `@lunora/codegen`, not the reverse. Putting it there and importing it here
2231
+ * would invert that edge, so config delegates to this instead and there is
2232
+ * still exactly one parser for the key.
2233
+ *
2234
+ * Best-effort and deliberately unvalidated: a missing file, malformed JSONC, or
2235
+ * a non-string value all collapse to `undefined`, because those are shape
2236
+ * errors rather than a name the user meant. An unrecognized *name* is returned
2237
+ * as-is so the caller's registry lookup rejects it — swallowing a typo into the
2238
+ * default would ship an app to the wrong provider.
2239
+ * @param projectRoot Directory containing `lunora.json`.
2240
+ * @returns the declared target, or `undefined` when none is usable.
2241
+ */
2242
+ declare const readProjectTarget: (projectRoot: string) => string | undefined;
2243
+ /**
2244
+ * The target codegen should emit for: an explicit option wins, then
2245
+ * `lunora.json`, then the default.
2246
+ *
2247
+ * `runCodegen` applies this itself so a caller that forgets to pass a target
2248
+ * still emits the surface the project declared. That default matters more than
2249
+ * it looks: a call site that silently omits the target emits the *default*
2250
+ * surface with no diagnostic to notice, and the mismatch only shows up at
2251
+ * runtime on the deployed app.
2252
+ * @param projectRoot Directory containing `lunora.json`.
2253
+ * @param explicit A caller-supplied target, if any.
2254
+ * @returns the resolved target id — not guaranteed to be registered.
2255
+ */
2256
+ declare const resolveCodegenTarget: (projectRoot: string, explicit?: string) => string;
2257
+ /**
2258
+ * The target ids codegen can gate against.
2259
+ *
2260
+ * `@lunora/config`'s driver registry (`deployTargetIds`) used to assert
2261
+ * equality against this — "two id spaces for one concept" — on the theory that
2262
+ * a target with a matrix but no driver "gates a surface nothing can deploy."
2263
+ * Plan 234 found that reasoning incomplete by registering `node` here: a
2264
+ * codegen-gateable target and a deployable target are genuinely different
2265
+ * questions, and a spike/dev-only host answers the first "yes" and the second
2266
+ * "not yet" without that being a bug in either registry. See
2267
+ * `plans/234-node-host-findings.md` for the finding and `@lunora/config`'s
2268
+ * `project-config.test.ts` for where the now-relaxed invariant lives.
2269
+ * @returns the registered matrix ids, sorted.
2270
+ */
2271
+ declare const platformMatrixIds: () => ReadonlyArray<string>;
2272
+ /** An advisor-style diagnostic about a target's platform capabilities. */
2273
+ interface PlatformDiagnostic {
2274
+ /** The codegen capability this concerns, when it is feature-specific. */
2275
+ feature?: CapabilityKey;
2276
+ /** Severity. All three names are errors — each drops or misdirects an emitted surface. */
2277
+ level: "error" | "warn";
2278
+ /** Human-readable explanation of the gap. */
2279
+ message: string;
2280
+ /** The lint id: `platform_unsupported_feature`, `platform_undeclared_feature`, or `platform_unknown_target`. */
2281
+ name: "platform_undeclared_feature" | "platform_unknown_target" | "platform_unsupported_feature";
2282
+ /** How to resolve it. */
2283
+ remediation: string;
2284
+ /** The requested deploy target. */
2285
+ target: string;
2286
+ }
2287
+ /**
2288
+ * Committed, tracked baseline file holding the blessed structural schema
2289
+ * snapshot the pre-deploy drift gate diffs against. Lives in `lunora/` (NOT the
2290
+ * gitignored `_generated/`) so it is committed alongside `schema.ts`. Leading
2291
+ * dot keeps it tucked away next to the schema it describes.
2292
+ */
2293
+ declare const SCHEMA_SNAPSHOT_FILENAME = ".lunora-schema.json";
2294
+ /**
2295
+ * Construct the ts-morph `Project` codegen discovers over. Prefers the user's
2296
+ * `tsconfig.json` (when one is found walking up from `lunoraDirectory`) so
2297
+ * cross-file type resolution and path aliases work; falls back to an isolated
2298
+ * project otherwise. This is the exact construction {@link runCodegen} uses
2299
+ * when no `project` is injected — exported so a long-lived caller (the Vite
2300
+ * dev-loop) can build one once and reuse it across runs via
2301
+ * {@link refreshCodegenProject} instead of re-parsing the user's whole TS
2302
+ * program on every save.
2303
+ */
2304
+ declare const createCodegenProject: (lunoraDirectory: string) => Project;
2305
+ /**
2306
+ * Synchronise a reused {@link createCodegenProject} Project with the current
2307
+ * on-disk state of `lunoraDirectory`, so the next {@link runCodegen} sees the
2308
+ * same files a freshly-constructed Project would — without re-parsing the whole
2309
+ * TS program. Adds any on-disk source file the Project doesn't yet have, and
2310
+ * `refreshFromFileSystemSync()`es the ones it does (picking up edits); then
2311
+ * removes Project source files under `lunoraDirectory` that no longer exist on
2312
+ * disk (the classic stale-deleted-file cache bug).
2313
+ *
2314
+ * Files outside `lunoraDirectory` (e.g. those pulled in by the user's tsconfig)
2315
+ * are left untouched — they back type resolution and rarely change in the
2316
+ * dev-loop; a tsconfig change invalidates the whole cached Project upstream.
2317
+ */
2318
+ declare const refreshCodegenProject: (project: Project, lunoraDirectory: string) => void;
2319
+ /**
2320
+ * Top-level codegen entry. Parses `<projectRoot>/lunora/schema.ts` and every
2321
+ * function file under `<projectRoot>/lunora/`, then writes
2322
+ * `_generated/{api,server,dataModel}.ts` next to them.
2323
+ *
2324
+ * When `LUNORA_CODEGEN_TIMING` is set (truthy), a single diagnostic summary
2325
+ * line is written to stderr with the total wall time and the discovery-vs-emit
2326
+ * split — opt-in instrumentation that is otherwise zero-cost and side-effect-free
2327
+ * on the returned {@link CodegenResult}.
2328
+ */
2329
+ declare const runCodegen: (options: CodegenOptions) => CodegenResult;
2330
+ interface CodegenOptions {
2331
+ /**
2332
+ * Which machine-readable API spec(s) to emit into `_generated/`.
2333
+ *
2334
+ * `"openapi"` (the default) writes only `openapi.json` (OpenAPI 3.1; covers
2335
+ * both the RPC functions and `httpRouter()` REST routes). `"openrpc"` writes
2336
+ * only `openrpc.json` (OpenRPC 1.x; the RPC functions only — OpenRPC cannot
2337
+ * represent REST routes). `"both"` writes both files; `"none"` writes neither.
2338
+ *
2339
+ * Regardless of the choice, `CodegenResult.generated.openApi` and `.openRpc`
2340
+ * always carry the rendered string (computation is cheap and pure); only the
2341
+ * on-disk write is gated by this option.
2342
+ */
2343
+ apiSpec?: "both" | "none" | "openapi" | "openrpc";
2344
+ /**
2345
+ * When true, run discovery + emit (so any schema/function parse error
2346
+ * surfaces) but skip writing files to `_generated/`. The returned
2347
+ * `outputDirectory` is still the path that *would* have been written.
2348
+ */
2349
+ dryRun?: boolean;
2350
+ /**
2351
+ * Run the static schema advisor (unindexed FKs, …) during codegen.
2352
+ * Defaults to `true`. When `false`, `CodegenResult.advisories` is empty.
2353
+ * Computed regardless of `dryRun`; codegen never prints them — see
2354
+ * {@link CodegenResult.advisories}.
2355
+ */
2356
+ lint?: boolean;
2357
+ /** Override the lunora subdirectory name. Defaults to `"lunora"`. */
2358
+ lunoraDirectory?: string;
2359
+ /**
2360
+ * Reuse a previously-constructed ts-morph {@link Project} instead of building
2361
+ * a fresh one each run. The caller owns refreshing its source files from disk
2362
+ * (see {@link refreshCodegenProject}) — codegen does not re-read changed files
2363
+ * off an injected Project. Built via {@link createCodegenProject} when absent.
2364
+ * Used by the Vite dev-loop to avoid re-parsing the whole TS program on every
2365
+ * save; omit it (CLI one-shot path) to get the default fresh-Project behaviour.
2366
+ */
2367
+ project?: Project;
2368
+ /** Project root containing the `lunora/` directory. */
2369
+ projectRoot: string;
2370
+ /**
2371
+ * The deploy target codegen tailors the emitted `ctx.*` surface to.
2372
+ * Defaults to `"cloudflare"` — whose capability matrix marks every feature
2373
+ * native or emulated, so the default output is unchanged (byte-identical
2374
+ * goldens). A target that marks a used feature unsupported omits its
2375
+ * `ctx.*` surface and reports it in {@link CodegenResult.platformDiagnostics}.
2376
+ * Only `"cloudflare"` is registered until other per-target `@lunora/platform`
2377
+ * matrices land; an unknown target emits the full surface un-gated and a
2378
+ * `platform_unknown_target` diagnostic.
2379
+ */
2380
+ target?: string;
2381
+ /**
2382
+ * Re-bless the committed schema-drift baseline (`lunora/.lunora-schema.json`)
2383
+ * with the current structural snapshot. The baseline is ALWAYS written on
2384
+ * first capture (when the file is absent); set this to overwrite an existing
2385
+ * one — e.g. after the developer has added the data migration that justifies
2386
+ * a breaking change. Ignored when `dryRun` is true.
2387
+ */
2388
+ updateSchemaBaseline?: boolean;
2389
+ /**
2390
+ * Committed `wrangler.jsonc` `vars` entries that hold plaintext secrets — the
2391
+ * `plaintext_secret_in_wrangler_vars` lint input. Produced by `@lunora/config`
2392
+ * (which reads `wrangler.jsonc`) and threaded through by the CLI / Vite plugin;
2393
+ * codegen only forwards it to the advisor. Absent when no wrangler config is
2394
+ * present or the caller doesn't scan it.
2395
+ */
2396
+ wranglerVariables?: ReadonlyArray<WranglerVariableIR>;
2397
+ }
2398
+ interface CodegenResult {
2399
+ /**
2400
+ * The normalized advisor evidence the findings were produced from, so a
2401
+ * caller can score it into a health map (`scoreAdvisor`) without re-running
2402
+ * discovery. `undefined` under `lint: false`.
2403
+ *
2404
+ * Deliberately not scored here: the map carries a `generatedAt` stamp, and
2405
+ * codegen's result stays a pure function of the sources.
2406
+ */
2407
+ advisorContext?: LintContext;
2408
+ /**
2409
+ * Static schema advisor findings (e.g. unindexed foreign keys) produced
2410
+ * this run. Empty when `lint` is `false` or the schema is clean. Codegen
2411
+ * does not print these itself — each caller presents them through its own
2412
+ * channel (the CLI logger, the vite overlay, the studio Advisors table).
2413
+ * `formatAdvisories` is exported for a plain multi-line rendering.
2414
+ */
2415
+ advisories: ReadonlyArray<Finding>;
2416
+ /**
2417
+ * Agents discovered from `defineAgent` exports in `lunora/agents.ts` — the
2418
+ * list the config layer reconciles into wrangler's `workflows[]` array (an
2419
+ * agent compiles onto a Cloudflare Workflow). Agents are NOT Durable Objects,
2420
+ * so this adds no binding or migration. Empty when the project declares none.
2421
+ */
2422
+ agents: ReadonlyArray<AgentIR>;
2423
+ /**
2424
+ * Containers discovered from `defineContainer` exports in
2425
+ * `lunora/containers.ts` — the list the config layer reconciles into
2426
+ * wrangler's `containers[]`, `CONTAINER_*` Durable Object bindings, and
2427
+ * migration classes. Empty when the project declares no containers.
2428
+ */
2429
+ containers: ReadonlyArray<ContainerIR>;
2430
+ /**
2431
+ * Deduplicated cron schedules discovered from `cronJobs()` definitions —
2432
+ * the array the vite plugin reconciles into `wrangler.jsonc`'s
2433
+ * `triggers.crons`. Empty when the project declares no crons.
2434
+ */
2435
+ cronTriggers: ReadonlyArray<string>;
2436
+ generated: {
2437
+ /** WorkflowEntrypoint classes for declared agents (`_generated/agents.ts`); `""` (and not written) when no agents are declared. */
2438
+ agents: string;
2439
+ api: string;
2440
+ /** Fluent worker-composition builder (`_generated/app.ts`) — `defineApp()`. Always written. */
2441
+ app: string;
2442
+ /** Partial-replication collection factories (`_generated/collections.ts`); `""` (and not written) unless the project declares shapes and installs `@lunora/db`. */
2443
+ collections: string;
2444
+ /** Container DO classes (`_generated/containers.ts`); `""` (and not written) when no containers are declared. */
2445
+ containers: string;
2446
+ crons: string;
2447
+ dataModel: string;
2448
+ drizzleGlobal: string;
2449
+ drizzleShard: string;
2450
+ functions: string;
2451
+ /** OpenAPI 3.1.0 document (`_generated/openapi.json`), pretty-printed JSON. */
2452
+ openApi: string;
2453
+ /**
2454
+ * OpenAPI document as an importable TS module (`_generated/openapi.ts`) —
2455
+ * `export const openApiSpec`, the worker imports it for
2456
+ * `createWorker({ openApiSpec })`. Same document as `openApi`. Written
2457
+ * alongside `openapi.json` whenever `apiSpec` includes `openapi`.
2458
+ */
2459
+ openApiModule: string;
2460
+ /** OpenRPC 1.x document (`_generated/openrpc.json`), pretty-printed JSON. Always computed; written only when `apiSpec` includes `openrpc`. */
2461
+ openRpc: string;
2462
+ /**
2463
+ * OpenRPC document as an importable TS module (`_generated/openrpc.ts`) —
2464
+ * `export const openRpcSpec`, for `createWorker({ openRpcSpec })`. Same
2465
+ * document as `openRpc`. Written alongside `openrpc.json` whenever
2466
+ * `apiSpec` includes `openrpc`.
2467
+ */
2468
+ openRpcModule: string;
2469
+ /** Push-consumer queue registry (`_generated/queues.ts`); `""` (and not written) when no push queues are declared. */
2470
+ queues: string;
2471
+ /** Project-bound seed client (`_generated/seed.ts`); `""` (and not written) when `@lunora/seed` is not a declared dependency. */
2472
+ seed: string;
2473
+ server: string;
2474
+ shard: string;
2475
+ /** Static vector-index registry (`_generated/vectors.ts`) — `LUNORA_VECTOR_INDEXES`. Empty array body when the schema declares none. */
2476
+ vectors: string;
2477
+ /** WorkflowEntrypoint classes (`_generated/workflows.ts`); `""` (and not written) when no workflows are declared. */
2478
+ workflows: string;
2479
+ };
2480
+ outputDirectory: string;
2481
+ /**
2482
+ * Portability diagnostics for the requested {@link CodegenOptions.target}:
2483
+ * `ctx.*` features the app uses that the target does not support (omitted
2484
+ * from the emitted surface), or an unknown target. Empty for a
2485
+ * fully-supported app on the default Cloudflare target. Presentation is the
2486
+ * caller's job, like {@link CodegenResult.advisories}.
2487
+ */
2488
+ platformDiagnostics: ReadonlyArray<PlatformDiagnostic>;
2489
+ /**
2490
+ * Queues discovered from `defineQueue` exports in `lunora/queues.ts` — the
2491
+ * list the config layer reconciles into wrangler's `queues.producers[]` /
2492
+ * `queues.consumers[]`. Queues are NOT Durable Objects, so this adds no
2493
+ * binding or migration. Empty when the project declares no queues.
2494
+ */
2495
+ queues: ReadonlyArray<QueueIR>;
2496
+ /**
2497
+ * The CURRENT structural schema snapshot computed this run (tables + field
2498
+ * kinds/optionality + indexes/relations/shard mode + declared migration ids).
2499
+ * The pre-deploy drift gate diffs this against the committed baseline read
2500
+ * from {@link CodegenResult.schemaSnapshotPath}. Always present, even on a
2501
+ * `dryRun`.
2502
+ */
2503
+ schemaSnapshot: SchemaSnapshot;
2504
+ /** Absolute path of the committed baseline file (`lunora/.lunora-schema.json`). */
2505
+ schemaSnapshotPath: string;
2506
+ /**
2507
+ * Workflows discovered from `defineWorkflow` exports in
2508
+ * `lunora/workflows.ts` — the list the config layer reconciles into
2509
+ * wrangler's `workflows[]` array. Workflows are NOT Durable Objects, so this
2510
+ * adds no binding or migration. Empty when the project declares no workflows.
2511
+ */
2512
+ workflows: ReadonlyArray<WorkflowIR>;
2513
+ }
2514
+ /** Deduplicated, sorted names of every ERROR-level advisory in `advisories`. */
2515
+ declare const errorAdvisoryNames: (advisories: ReadonlyArray<Pick<Finding, "level" | "name">>) => ReadonlyArray<string>;
2516
+ /** Deduplicated, sorted names of every error-level platform diagnostic in `platformDiagnostics`. */
2517
+ declare const errorPlatformDiagnosticNames: (platformDiagnostics: ReadonlyArray<Pick<PlatformDiagnostic, "level" | "name">>) => ReadonlyArray<string>;
2518
+ /**
2519
+ * Convenience read combining both categories from a full {@link CodegenResult}
2520
+ * — the shape the Vite plugin's `buildBlockingMessage` needs, which (unlike
2521
+ * the CLI's `lunora codegen`/`lunora deploy`) folds ERROR-level advisories and
2522
+ * platform diagnostics into a single blocking message with no strict/CI
2523
+ * opt-out.
2524
+ */
2525
+ declare const describeErrorLevelFindings: (result: Pick<CodegenResult, "advisories" | "platformDiagnostics">) => {
2526
+ advisoryNames: ReadonlyArray<string>;
2527
+ platformDiagnosticNames: ReadonlyArray<string>;
2528
+ };
2529
+ /**
2530
+ * An error thrown by codegen discovery when the user's schema or function
2531
+ * source has a structural problem that can be pinpointed to a specific source
2532
+ * location. A `LunoraError` subclass (`code: "CODEGEN_DIAGNOSTIC"`); the `file`,
2533
+ * `line`, and `column` properties (also passed through as the base `loc`) mirror
2534
+ * what Vite's error-overlay `loc` field expects so the browser can display the
2535
+ * exact spot.
2536
+ */
2537
+ declare class CodegenDiagnosticError extends LunoraError {
2538
+ readonly column: number;
2539
+ readonly file: string;
2540
+ readonly line: number;
2541
+ constructor(message: string, file: string, line: number, column: number);
2542
+ }
2543
+ /**
2544
+ * Build a {@link CodegenDiagnosticError} whose message includes the source
2545
+ * location and whose `file`/`line`/`column` properties are set from the
2546
+ * ts-morph `Node`'s position in its source file.
2547
+ *
2548
+ * Message format: `@lunora/codegen: <detail> (<file>:<line>:<column>)`
2549
+ *
2550
+ * `meta` is merged onto the returned error for callers that also carry the
2551
+ * project-wide `LunoraError` envelope (`code`/`name`/`status`) — it never
2552
+ * touches `file`/`line`/`column`, and the error stays an instance of
2553
+ * {@link CodegenDiagnosticError} so the Vite overlay's `instanceof` location
2554
+ * lookup is unaffected.
2555
+ */
2556
+ declare const diagnosticAt: (node: Node, detail: string, meta?: Record<string, unknown>) => CodegenDiagnosticError;
2557
+ /** The only file agents may be declared in — mirrors `lunora/workflows.ts`. */
2558
+ declare const AGENTS_FILENAME = "agents.ts";
2559
+ /**
2560
+ * Discover every agent the project declares: exported `defineAgent()` calls in
2561
+ * `lunora/agents.ts`. Returns `[]` when the file doesn't exist. Only four things
2562
+ * are read statically — the optional `name` override (wrangler `workflows[].name`),
2563
+ * the optional `publicRun` opt-in (the `agents:agentRun` capability gate), the
2564
+ * presence of a `voice` block (which turns on the voice-session Durable Object),
2565
+ * and the presence of an `onEmail` mapper (which wires the worker `email()`
2566
+ * handler); the rest of the agent config (model / tools / memory / voice models /
2567
+ * the `onEmail` closure body) is runtime-only, so codegen never evaluates it.
2568
+ */
2569
+ declare const discoverAgents: (project: Project, lunoraDirectory: string) => AgentIR[];
2570
+ /**
2571
+ * Discover `ctx.authApi.<method>(...)` (and bare `authApi.<method>(...)`) calls
2572
+ * under the lunora source directory and attribute each to the exported function
2573
+ * (and file) performing it. Calls outside an exported declaration are dropped.
2574
+ */
2575
+ declare const discoverAuthApiCalls: (project: Project, lunoraDirectory: string) => AuthApiCallIR[];
2576
+ /** The only file containers may be declared in — mirrors `lunora/crons.ts`. */
2577
+ declare const CONTAINERS_FILENAME = "containers.ts";
2578
+ /**
2579
+ * Discover every container the project declares: exported `defineContainer()`
2580
+ * calls in `lunora/containers.ts`. Returns `[]` when the file doesn't exist.
2581
+ * Wrangler-relevant fields (`image`, `instanceType`, `maxInstances`, `name`)
2582
+ * must be static literals; runtime-only fields (`env`, `sleepAfter`, …) may be
2583
+ * any expression since the generated class imports the definition object.
2584
+ */
2585
+ declare const discoverContainers: (project: Project, lunoraDirectory: string) => ContainerIR[];
2586
+ /**
2587
+ * Scan every `.ts` file under `lunoraDir` for `cronJobs()` builder registrations
2588
+ * (`crons.interval(...)`, `crons.daily(...)`, `crons.cron(...)`, …) and lift them
2589
+ * into {@link CronJobIR}. Schedules are compiled to standard cron expressions;
2590
+ * function references are resolved to their `namespace:fn` dispatch path, while a
2591
+ * `workflows.NAME` / `agents.NAME` reference (or a bare identifier naming a
2592
+ * declared workflow) resolves to a durable workflow start. Names must be unique
2593
+ * across the project.
2594
+ */
2595
+ declare const discoverCrons: (project: Project, lunoraDirectory: string, workflows?: ReadonlyArray<WorkflowIR>, agents?: ReadonlyArray<AgentIR>) => CronJobIR[];
2596
+ /** The only file a feature-flag provider may be declared in — mirrors `lunora/queues.ts`. */
2597
+ declare const FLAGS_FILENAME = "flags.ts";
2598
+ /**
2599
+ * Discover the feature-flag provider a project declares in `lunora/flags.ts`.
2600
+ * Returns `undefined` when the file doesn't exist (the app has no flags). The
2601
+ * read is metadata-only and lenient: codegen wires `ctx.flags` purely from the
2602
+ * file's *existence* (`run-codegen.ts`) and imports the real module for the
2603
+ * provider value — this IR exists solely so the config layer can reconcile the
2604
+ * wrangler `flagship` binding for the Flagship binding-mode provider. Anything
2605
+ * it can't read statically degrades to a `custom` provider (no binding), never
2606
+ * a thrown error.
2607
+ */
2608
+ declare const discoverFlags: (project: Project, lunoraDirectory: string) => FlagsIR | undefined;
2609
+ /**
2610
+ * Scan all .ts files under `lunoraDir` (skipping `_generated/` and `schema.ts`)
2611
+ * for top-level `export const x = query/mutation/action({...})` registrations.
2612
+ */
2613
+ declare const discoverFunctions: (project: Project, lunoraDirectory: string) => FunctionIR[];
2614
+ /**
2615
+ * Scan all `.ts` files under `lunoraDir` (skipping `_generated/` and `schema.ts`)
2616
+ * for `export const x = httpRoute.<verb>(...)…handler(...)` typed REST routes.
2617
+ * These are the headline OpenAPI target: each becomes a real `paths` entry.
2618
+ */
2619
+ declare const discoverHttpRoutes: (project: Project, lunoraDirectory: string) => HttpRouteIR[];
2620
+ /**
2621
+ * Discover `ctx.db.insert("table", …)` writes under the lunora source directory
2622
+ * and attribute each to the exported function (and file) performing it. Calls
2623
+ * with a non-literal table argument, or outside an exported declaration, are
2624
+ * dropped (`table === ""` / no enclosing export).
2625
+ */
2626
+ declare const discoverInserts: (project: Project, lunoraDirectory: string) => InsertWriteIR[];
2627
+ /**
2628
+ * Discover masking usage for every exported Lunora procedure under the lunora
2629
+ * source directory — the column-level twin of `discoverRlsProcedures`. For each
2630
+ * procedure, records whether its builder chain includes `.use(mask(...))`, which
2631
+ * `(table, column)` pairs that mask declares, and which tables it reads/writes
2632
+ * through `ctx.db`. Feeds the `mask_uncovered_pii_column` advisor lint.
2633
+ */
2634
+ declare const discoverMaskProcedures: (project: Project, lunoraDirectory: string) => MaskProcedureIR[];
2635
+ /**
2636
+ * Scan all `.ts` files under `lunoraDir` for top-level
2637
+ * `export const x = defineMigration({...})` declarations and lift them into
2638
+ * {@link MigrationIR}. `id` must be a static string literal (it's the registry
2639
+ * key); `table` is best-effort and left `""` when not a literal.
2640
+ */
2641
+ declare const discoverMigrations: (project: Project, lunoraDirectory: string) => MigrationIR[];
2642
+ /** The only file custom mutators may be declared in — mirrors `lunora/queues.ts`. */
2643
+ declare const MUTATORS_FILENAME = "mutators.ts";
2644
+ /**
2645
+ * Discover every custom mutator the project declares: exported
2646
+ * `defineMutator()` calls in `lunora/mutators.ts`. Returns `[]` when the file
2647
+ * doesn't exist. The export binding plus the declared `args` / `server` return
2648
+ * type are lifted — enough to emit a typed `api.mutators.<name>` reference —
2649
+ * while the runtime object still carries the authoritative `server` impl +
2650
+ * `handler`, so codegen never evaluates the body. The client `client` impl is
2651
+ * split into the browser bundle separately.
2652
+ */
2653
+ declare const discoverMutators: (project: Project, lunoraDirectory: string) => MutatorIR[];
2654
+ /**
2655
+ * Discover non-deterministic API calls (`Date.now`, `new Date()`, `Date()`,
2656
+ * `Math.random`, `crypto.randomUUID`, `crypto.getRandomValues` — including
2657
+ * `globalThis`/`self`/`window`-prefixed receivers — and `fetch`) lexically inside
2658
+ * the handler body of every exported `query(...)` / `mutation(...)` registration
2659
+ * under the lunora source directory — the `nondeterministic_query_mutation` lint
2660
+ * input. `action(...)` (and `stream(...)`) registrations are intentionally
2661
+ * skipped: actions run exactly once and may use ambient APIs freely.
2662
+ *
2663
+ * Traversal is scoped to the handler node (not the whole declaration), mirroring
2664
+ * how the auth-api / insert feeders attribute calls — so a call in a sibling
2665
+ * helper outside the handler, or in a nested `action(...)` passed elsewhere, is
2666
+ * not attributed to the query/mutation. One {@link NondeterministicCallIR} is
2667
+ * produced per call site.
2668
+ */
2669
+ declare const discoverNondeterministicCalls: (project: Project, lunoraDirectory: string) => NondeterministicCallIR[];
2670
+ /** The only file a `@lunora/notify` provider may be declared in — mirrors `lunora/flags.ts`. */
2671
+ declare const NOTIFY_FILENAME = "notify.ts";
2672
+ /**
2673
+ * Discover `ctx.notify` / `ctx.push` sends lexically inside the handler body of
2674
+ * every exported `query(...)` / `mutation(...)` registration under the lunora
2675
+ * source directory — the `notify_send_outside_action` lint input. `action(...)`
2676
+ * (and `stream(...)`) registrations are intentionally skipped: a notification
2677
+ * send is external I/O that belongs in actions. One {@link AdvisorNotifyCall} is
2678
+ * produced per send site.
2679
+ */
2680
+ declare const discoverNotifyCalls: (project: Project, lunoraDirectory: string) => AdvisorNotifyCall[];
2681
+ /**
2682
+ * Discover which push channels the project's `lunora/notify.ts` default export
2683
+ * (`defineNotify({...})`) wires plus whether any handler sends a push — the
2684
+ * `notify_missing_push_config` lint input. Returns `undefined` when the file is
2685
+ * absent (the app declares no notify config). The read is metadata-only and
2686
+ * lenient (like `discoverFlags`): a `webPush`/`fcm` property's mere presence
2687
+ * counts as the channel being wired; a non-literal config degrades to "unwired"
2688
+ * rather than throwing.
2689
+ */
2690
+ declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string) => AdvisorNotifyConfig | undefined;
2691
+ /**
2692
+ * Every package name the project declares a dependency on, read from the
2693
+ * `package.json` at the project root across all four dependency fields
2694
+ * (`dependencies`, `devDependencies`, `peerDependencies`,
2695
+ * `optionalDependencies`).
2696
+ *
2697
+ * Returns `undefined` — NOT an empty set — when the manifest is absent or
2698
+ * unparseable, which is the whole reason this exists. Studio nav gating can
2699
+ * treat "declares nothing" and "cannot tell" the same way, but a check that
2700
+ * errors on a missing package cannot: conflating them makes it fire on every
2701
+ * project without a root `package.json` (the codegen fixtures, an embedded
2702
+ * schema, a tool driving `runCodegen` directly).
2703
+ */
2704
+ declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
2705
+ /**
2706
+ * Discover `ctx.db.query("table")…` reads under the lunora source directory and
2707
+ * reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
2708
+ * returned — an unfiltered read is never a `filter_without_index` candidate, so
2709
+ * dropping the rest keeps the lint input small.
2710
+ */
2711
+ declare const discoverQueries: (project: Project, lunoraDirectory: string) => QueryReadIR[];
2712
+ /** The only file queues may be declared in — mirrors `lunora/workflows.ts`. */
2713
+ declare const QUEUES_FILENAME = "queues.ts";
2714
+ /**
2715
+ * Discover every queue the project declares: exported `defineQueue()` calls in
2716
+ * `lunora/queues.ts`. Returns `[]` when the file doesn't exist. Only the
2717
+ * wrangler-relevant literals (`name`/`mode`/batch tuning) are read; the handler
2718
+ * body is runtime-only, so codegen never evaluates it.
2719
+ */
2720
+ declare const discoverQueues: (project: Project, lunoraDirectory: string) => QueueIR[];
2721
+ /**
2722
+ * Discover `ctx.r2sql` accesses lexically inside the handler body of every
2723
+ * exported `query(...)` / `mutation(...)` registration under the lunora source
2724
+ * directory — the `r2sql_outside_action` lint input. `action(...)` (and
2725
+ * `stream(...)`) registrations are intentionally skipped: R2 SQL is the
2726
+ * external, non-reactive surface that belongs in actions.
2727
+ *
2728
+ * Traversal is scoped to the handler node (not the whole declaration), mirroring
2729
+ * `discoverNondeterministicCalls` — so a `ctx.r2sql` touch in a sibling helper
2730
+ * outside the handler is not attributed to the query/mutation. One
2731
+ * {@link R2sqlCallIR} is produced per access site.
2732
+ */
2733
+ declare const discoverR2sqlCalls: (project: Project, lunoraDirectory: string) => R2sqlCallIR[];
2734
+ declare const discoverRlsProcedures: (project: Project, lunoraDirectory: string) => RlsProcedureIR[];
2735
+ /**
2736
+ * Aggregate the schema-wide RLS metadata the studio's read-only inspector reads:
2737
+ * every statically-discovered `(table, on, procedure)` policy entry plus every
2738
+ * role declared via `rls(policies, { roles })`. Walks the same builder chains as
2739
+ * {@link discoverRlsProcedures} but extracts the richer `{ on }` operation +
2740
+ * role/permission shape rather than the lint's table-name set.
2741
+ *
2742
+ * Only the **builder** form (`c.use(rls(...)).query(...)`) can declare policies,
2743
+ * so bare-factory procedures contribute nothing. The `when` predicate is never
2744
+ * read — it's an opaque JS closure whose logic belongs in code, not the UI.
2745
+ * Roles are deduped by name (first declaration wins) so a role registered on
2746
+ * several procedures lists once.
2747
+ */
2748
+ declare const discoverRlsMetadata: (project: Project, lunoraDirectory: string) => RlsMetadataIR;
2749
+ /**
2750
+ * Which sandbox tools a project imports from `@lunora/agent` (main entry or the
2751
+ * `/sandbox` subpath), detected by NAMED value import. Drives two things:
2752
+ * registering the `sandbox:invoke` dispatcher (either tool) and provisioning the
2753
+ * `BROWSER` wrangler binding (`browserTool` — the browser op runs on
2754
+ * `ctx.browser` inside the dispatcher).
2755
+ */
2756
+ interface SandboxUsage {
2757
+ /** `import { browserTool } from "@lunora/agent"` (or `/sandbox`) appears in `lunora/`. */
2758
+ usesSandboxBrowser: boolean;
2759
+ /** `import { containerTool } from "@lunora/agent"` (or `/sandbox`) appears in `lunora/`. */
2760
+ usesSandboxContainer: boolean;
2761
+ }
2762
+ declare const discoverSandboxUsage: (project: Project, lunoraDirectory: string) => SandboxUsage;
2763
+ /**
2764
+ * Load `<projectRoot>/lunora/schema.ts`, find `defineSchema({...})`, and
2765
+ * return a structural IR. Throws if the file or call cannot be found.
2766
+ */
2767
+ declare const discoverSchema: (project: Project, schemaPath: string, projectRoot?: string) => SchemaIR;
2768
+ /** The only file shapes may be declared in — mirrors `lunora/queues.ts`. */
2769
+ declare const SHAPES_FILENAME = "shapes.ts";
2770
+ /**
2771
+ * Discover every replication shape the project declares: exported
2772
+ * `defineShape()` calls in `lunora/shapes.ts`. Returns `[]` when the file
2773
+ * doesn't exist. Only the export binding is lifted — the runtime object carries
2774
+ * the authoritative `table`/`columns`/`compileWhere`, so codegen never
2775
+ * evaluates the predicate.
2776
+ */
2777
+ declare const discoverShapes: (project: Project, lunoraDirectory: string) => ShapeIR[];
2778
+ /**
2779
+ * Aggregate the schema-wide storage-rule metadata the studio's inspector reads:
2780
+ * every statically-discovered `(bucket, on, prefix, procedure)` entry across all
2781
+ * `.use(storageRules(...))` chains. Only the builder form can declare rules, so
2782
+ * bare-factory procedures contribute nothing.
2783
+ */
2784
+ declare const discoverStorageRulesMetadata: (project: Project, lunoraDirectory: string) => StorageRulesMetadataIR;
885
2785
  /** The only file workflows may be declared in — mirrors `lunora/containers.ts`. */
886
2786
  declare const WORKFLOWS_FILENAME = "workflows.ts";
887
2787
  /**
888
- * Discover every workflow the project declares: exported `defineWorkflow()`
889
- * calls in `lunora/workflows.ts`. Returns `[]` when the file doesn't exist. The
890
- * only wrangler-relevant literal is the optional `name` override; the workflow
891
- * body is runtime-only, so codegen never evaluates it.
892
- */
2788
+ * Discover every workflow the project declares: exported `defineWorkflow()`
2789
+ * calls in `lunora/workflows.ts`. Returns `[]` when the file doesn't exist. The
2790
+ * only wrangler-relevant literal is the optional `name` override; the workflow
2791
+ * body is runtime-only, so codegen never evaluates it.
2792
+ */
893
2793
  declare const discoverWorkflows: (project: Project, lunoraDirectory: string) => WorkflowIR[];
894
2794
  declare const GENERATED_HEADER = "// GENERATED by @lunora/codegen — do not edit.\n// Run `lunora codegen` to regenerate.\n\n";
895
- /** Emit `_generated/dataModel.ts` — `Doc&lt;"name">` + `Id&lt;"name">` for every table. */
896
- declare const emitDataModel: (schema: SchemaIR, useUmbrella?: boolean) => string;
897
- /**
898
- * Emit `_generated/api.ts` — the typed `api.*` registry (public functions), the
899
- * `internal.*` registry, and (when the project declares workflows) the typed
900
- * `workflows.*` reference object. `api`/`internal` are the same `anyApi` proxy
901
- * at runtime (the `__lunoraRef` is identical); visibility is enforced
902
- * server-side at dispatch, not in the reference. Splitting the *types* keeps
903
- * internal functions off the client-facing `api` surface.
904
- */
905
- declare const emitApi: (functions: ReadonlyArray<FunctionIR>, workflows?: ReadonlyArray<WorkflowIR>, useUmbrella?: boolean) => string;
906
- /**
907
- * Emit `_generated/seed.ts` — a project-bound `createSeedClient` with this
908
- * schema's `InsertModel` and runtime schema pre-applied, so a test or script
909
- * calls `createSeedClient({ seed: 1 }).users(5)` with full column types and no
910
- * manual wiring. The runtime schema is the default export of `lunora/schema.ts`
911
- * (the same import the generated ShardDO uses).
912
- *
913
- * Returns `""` when `@lunora/seed` is not a declared dependency, so projects
914
- * that don't use it keep a clean `_generated/` and never import the package.
915
- */
2795
+ /** Emit `_generated/dataModel.ts` — `Doc<"name">` + `Id<"name">` for every table. */
2796
+ declare const emitDataModel: (schema: SchemaIR) => string;
2797
+ /**
2798
+ * Emit `_generated/api.ts` — the typed `api.*` registry (public functions), the
2799
+ * `internal.*` registry, and (when the project declares them) the typed
2800
+ * `workflows.*` / `agents.*` scheduler-target reference objects. `api`/`internal` are the same `anyApi` proxy
2801
+ * at runtime (the `__lunoraRef` is identical); visibility is enforced
2802
+ * server-side at dispatch, not in the reference. Splitting the *types* keeps
2803
+ * internal functions off the client-facing `api` surface.
2804
+ */
2805
+ interface EmitApiOptions {
2806
+ agents?: ReadonlyArray<AgentIR>;
2807
+ functions: ReadonlyArray<FunctionIR>;
2808
+ /** Typed REST routes; only `.stream()` (SSE) routes emit a `httpStreams.*` reference. */
2809
+ httpRoutes?: ReadonlyArray<HttpRouteIR>;
2810
+ /** Custom mutators (`lunora/mutators.ts`) emitted as `api.mutators.*` so a client `serverRef` is compile-checked. */
2811
+ mutators?: ReadonlyArray<MutatorIR>;
2812
+ useUmbrella?: boolean;
2813
+ workflows?: ReadonlyArray<WorkflowIR>;
2814
+ }
2815
+ declare const emitApi: (options: EmitApiOptions) => string;
2816
+ /**
2817
+ * Emit `_generated/collections.ts` — a typed TanStack DB binding per `defineShape`
2818
+ * in `lunora/shapes.ts` (the local-first partial-replication surface).
2819
+ *
2820
+ * Each shape emits **two** entry points.
2821
+ *
2822
+ * `<shape>CollectionOptions(options)` is the composable form: it returns the full
2823
+ * `LunoraCollectionOptions` — `config` for `createCollection`, plus `checkpoints`
2824
+ * (which `bindMutators` gates optimistic overlays on) and `scope`. This is what an app
2825
+ * with custom mutators needs, and what the old single-factory form made impossible: it
2826
+ * built the collection internally and dropped `checkpoints` on the floor, so there was
2827
+ * no way to wire mutators to the collection codegen produced.
2828
+ *
2829
+ * `<shape>Collection(options)` is the convenience form for a read-only collection: it
2830
+ * returns `{ checkpoints, collection, scope }` rather than a bare `Collection`, so the
2831
+ * sync controls stay reachable even from the short path.
2832
+ *
2833
+ * Both are typed: `args` comes from the shape's own validators (a parameterless
2834
+ * shape takes none), rows resolve to `Doc<"table">` when the shape names its table
2835
+ * with a literal, and `shardKey` / `getKey` / `load` / `onError` / `checkpoints` are
2836
+ * all threadable — a sharded table needs `shardKey` for its watermark to land in the
2837
+ * right bucket, and a server-minted `_id` that differs from the app's natural key
2838
+ * needs `getKey`.
2839
+ *
2840
+ * Returns `""` (so `writeIfPresent` skips the file) unless the project both
2841
+ * declares shapes AND installs `@lunora/db` — the add-on that ships
2842
+ * `lunoraCollectionOptions`. `@lunora/db` stays a scoped install even under the
2843
+ * `lunorash` umbrella (an opt-in add-on, like `@lunora/auth`), so its import is
2844
+ * always `@lunora/db/collections`; only the in-umbrella `@lunora/client` import
2845
+ * is remapped to `lunorash/client`.
2846
+ */
2847
+ declare const emitCollections: (shapes: ReadonlyArray<ShapeIR>, hasDatabase: boolean, useUmbrella?: boolean) => string;
916
2848
  interface EmitServerOptions {
2849
+ /** Agents declared via `defineAgent` exports — wires the typed `ctx.agents` producers onto Mutation/Action contexts. */
2850
+ agents?: ReadonlyArray<AgentIR>;
917
2851
  containers?: ReadonlyArray<ContainerIR>;
2852
+ /**
2853
+ * The single `defineEnv(...)` contract declared in `lunora/env.ts`. When
2854
+ * present, `ctx.env` is typed as the validated `InferEnv` shape (recovered
2855
+ * via `ReturnType` over the accessor's `typeof`). `undefined` leaves `ctx.env`
2856
+ * the base optional binding record — byte-identical to today.
2857
+ */
2858
+ env?: EnvIR;
2859
+ /**
2860
+ * A `lunora/` source reads `ctx.access` — wires the verified Cloudflare Access
2861
+ * facade (`@lunora/cloudflare-access/context`) onto every ctx. Distinct from
2862
+ * `emitApp`'s `hasAccess` (which gates the worker's `.access()` resolveIdentity
2863
+ * method); this one gates the per-request `ctx.access` read surface.
2864
+ */
2865
+ hasAccessFacade?: boolean;
918
2866
  hasAi?: boolean;
919
- /** A `lunora/` source uses `@lunora/analytics` / `ctx.analytics` — wires the write helper onto every ctx. */
2867
+ /** A `lunora/` source uses `@lunora/bindings/analytics` / `ctx.analytics` — wires the write helper onto every ctx. */
920
2868
  hasAnalytics?: boolean;
921
2869
  /** A `lunora/` source uses `@lunora/browser` / `ctx.browser` — wires `ctx.browser` onto ActionCtx only. */
922
2870
  hasBrowser?: boolean;
2871
+ /** The project declares `lunora/flags.ts` — wires `ctx.flags` (OpenFeature) onto every ctx. */
2872
+ hasFlags?: boolean;
923
2873
  /** A `lunora/` source uses `@lunora/hyperdrive` / `ctx.sql` — wires `ctx.sql` onto ActionCtx only. */
924
2874
  hasHyperdrive?: boolean;
925
- /** A `lunora/` source uses `@lunora/images` / `ctx.images` — wires `ctx.images` onto ActionCtx only. */
2875
+ /** A `lunora/` source uses `@lunora/bindings/images` / `ctx.images` — wires `ctx.images` onto ActionCtx only. */
926
2876
  hasImages?: boolean;
927
- /** A `lunora/` source uses `@lunora/kv` / `ctx.kv` — wires `ctx.kv` onto every ctx. */
2877
+ /** A `lunora/` source uses `@lunora/bindings/kv` / `ctx.kv` — wires `ctx.kv` onto every ctx. */
928
2878
  hasKv?: boolean;
2879
+ /** The project declares `lunora/notify.ts` — wires `ctx.notify` + its `ctx.push` alias (`@lunora/notify`) onto every ctx. */
2880
+ hasNotify?: boolean;
929
2881
  hasPayments?: boolean;
930
- /** A `lunora/` source uses `@lunora/pipelines` / `ctx.pipelines` — wires `ctx.pipelines` onto ActionCtx only. */
2882
+ /** A `lunora/` source uses `@lunora/bindings/pipelines` / `ctx.pipelines` — wires `ctx.pipelines` onto ActionCtx only. */
931
2883
  hasPipelines?: boolean;
932
- /** A `lunora/` source uses `@lunora/r2sql` / `ctx.r2sql` — wires `ctx.r2sql` onto ActionCtx only. */
2884
+ /** A `lunora/` source uses `@lunora/bindings/r2sql` / `ctx.r2sql` — wires `ctx.r2sql` onto ActionCtx only. */
933
2885
  hasR2sql?: boolean;
2886
+ /** A `lunora/` source uses `@lunora/x402/pay` / `ctx.x402` — wires the agent-wallet pay rail onto ActionCtx only. */
2887
+ hasX402?: boolean;
2888
+ /**
2889
+ * The single `defineIdentity(...)` claim contract declared in
2890
+ * `lunora/identity.ts` (Plan 080). When present, `ctx.auth.getIdentity()`,
2891
+ * the RLS policy `ctx.auth.identity`, and the shard-authorization hooks
2892
+ * narrow to the declared shape (recovered via `InferIdentity` over the
2893
+ * contract's `typeof`). `undefined` keeps the identity an untyped bag —
2894
+ * byte-identical to today.
2895
+ */
2896
+ identity?: IdentityIR;
2897
+ /** Queues declared via `defineQueue` exports — wires the typed `ctx.queues` producers onto Mutation/Action contexts. */
2898
+ queues?: ReadonlyArray<QueueIR>;
934
2899
  schema?: SchemaIR;
935
2900
  storageRuleBuckets?: ReadonlyArray<string>;
936
2901
  /** The project depends on the `lunora` umbrella — import base packages via its subpaths. */
937
2902
  useUmbrella?: boolean;
938
2903
  workflows?: ReadonlyArray<WorkflowIR>;
939
2904
  }
940
- declare const emitServer: ({
941
- containers,
942
- hasAi,
943
- hasAnalytics,
944
- hasBrowser,
945
- hasHyperdrive,
946
- hasImages,
947
- hasKv,
948
- hasPayments,
949
- hasPipelines,
950
- hasR2sql,
951
- schema,
952
- storageRuleBuckets,
953
- useUmbrella,
954
- workflows
955
- }?: EmitServerOptions) => string;
956
- declare const emitFunctions: (functions: ReadonlyArray<FunctionIR>, migrations?: ReadonlyArray<MigrationIR>, useUmbrella?: boolean) => string;
957
- /**
958
- * Storage-column map per table for the file browser: `{ table: [field, …] }` for
959
- * every field declared `v.storage(...)` (unwrapping `v.optional(...)`). The
960
- * generated shard hands this to the base `storageColumns` hook so the admin
961
- * `storageReferences` read can join R2 objects back to the rows that own them
962
- * (and flag orphans objects no row references). Only scalar storage columns
963
- * are emitted; an array-of-storage field can't be matched by an equality scan,
964
- * so it is skipped here.
965
- */
966
- /**
967
- * Emit `_generated/containers.ts` one container-enabled Durable Object class
968
- * per `defineContainer` export, each a thin subclass of `LunoraContainer`
969
- * (`@lunora/container/do`) constructed with the user's definition object. The
970
- * worker entry must re-export these classes: wrangler requires every
971
- * `containers[].class_name` to be exported by the deployed worker. Returns ""
972
- * when the project declares no containers (the file is not written then).
973
- */
974
- declare const emitContainers: (containers: ReadonlyArray<ContainerIR>) => string;
975
- /**
976
- * Emit `_generated/workflows.ts` — one `WorkflowEntrypoint` class per
977
- * `defineWorkflow` export, each a thin subclass of `LunoraWorkflow`
978
- * (`@lunora/workflow/do`) constructed with the user's definition object. The
979
- * worker entry must re-export these classes: wrangler requires every
980
- * `workflows[].class_name` to be exported by the deployed worker. Returns ""
981
- * when the project declares no workflows (the file is not written then).
982
- */
2905
+ declare const emitServer: ({ agents, containers, env, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasX402, identity, queues, schema, storageRuleBuckets, useUmbrella, workflows }?: EmitServerOptions) => string;
2906
+ interface EmitFunctionsOptions {
2907
+ agents?: ReadonlyArray<AgentIR>;
2908
+ functions: ReadonlyArray<FunctionIR>;
2909
+ migrations?: ReadonlyArray<MigrationIR>;
2910
+ mutators?: ReadonlyArray<MutatorIR>;
2911
+ shapes?: ReadonlyArray<ShapeIR>;
2912
+ /** Import of a sandbox tool (`browserTool`/`containerTool`) auto-registers the `sandbox:invoke` action. */
2913
+ usesSandbox?: boolean;
2914
+ useUmbrella?: boolean;
2915
+ }
2916
+ declare const emitFunctions: (options: EmitFunctionsOptions) => string;
2917
+ /**
2918
+ * Emit `_generated/containers.ts` — one container-enabled Durable Object class
2919
+ * per `defineContainer` export, each a thin subclass of `LunoraContainer`
2920
+ * (`@lunora/container/do`) constructed with the user's definition object. The
2921
+ * worker entry must re-export these classes: wrangler requires every
2922
+ * `containers[].class_name` to be exported by the deployed worker. Returns ""
2923
+ * when the project declares no containers (the file is not written then).
2924
+ */
2925
+ declare const emitContainers: (containers: ReadonlyArray<ContainerIR>, jurisdiction?: JurisdictionIR) => string;
2926
+ /**
2927
+ * Emit `_generated/workflows.ts`one `WorkflowEntrypoint` class per
2928
+ * `defineWorkflow` export, each a thin subclass of `LunoraWorkflow`
2929
+ * (`@lunora/workflow/do`) constructed with the user's definition object. The
2930
+ * worker entry must re-export these classes: wrangler requires every
2931
+ * `workflows[].class_name` to be exported by the deployed worker. Returns ""
2932
+ * when the project declares no workflows (the file is not written then).
2933
+ */
983
2934
  declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
2935
+ /**
2936
+ * Emit `_generated/agents.ts` — one `WorkflowEntrypoint` class per `defineAgent`
2937
+ * export, each a thin subclass of `LunoraWorkflow` (`@lunora/workflow/do`)
2938
+ * constructed with the compiled agent tool-loop (`compileAgentWorkflow`). Like
2939
+ * `_generated/workflows.ts`, the worker entry must re-export these classes:
2940
+ * wrangler requires every `workflows[].class_name` to be exported by the
2941
+ * deployed worker. Returns "" when the project declares no agents (the file is
2942
+ * not written then).
2943
+ */
2944
+ declare const emitAgents: (agents: ReadonlyArray<AgentIR>) => string;
984
2945
  interface EmitShardOptions {
985
2946
  advisories?: ReadonlyArray<Finding>;
2947
+ /** Every declared procedure — the health map's denominator, served via `getAdvisorProcedures`. */
2948
+ advisorProcedures?: ReadonlyArray<AdvisorProcedureProtection>;
2949
+ /** Agents declared via `defineAgent` exports in `lunora/agents.ts` — wires the typed `ctx.agents` producers. */
2950
+ agents?: ReadonlyArray<AgentIR>;
986
2951
  containers?: ReadonlyArray<ContainerIR>;
2952
+ /** The single `defineEnv(...)` contract declared in `lunora/env.ts` — applies the accessor to the worker `env` to populate `ctx.env`. */
2953
+ env?: EnvIR;
2954
+ /** Statically-discovered `ctx.flags.<type>("key")` reads — the studio Flags page + reactive evaluation iterate these. */
2955
+ flagKeys?: ReadonlyArray<{
2956
+ key: string;
2957
+ type: "boolean" | "number" | "object" | "string";
2958
+ }>;
2959
+ /** A `lunora/` source reads `ctx.access` — wires the verified Cloudflare Access facade onto every ctx. */
2960
+ hasAccessFacade?: boolean;
987
2961
  hasAi?: boolean;
988
2962
  /** A `lunora/` source reads `ctx.analytics` — wires the Analytics Engine write helper onto every ctx. */
989
2963
  hasAnalytics?: boolean;
990
2964
  /** A `lunora/` source reads `ctx.browser` — wires `ctx.browser` onto the ActionCtx only. */
991
2965
  hasBrowser?: boolean;
2966
+ /** The project declares `lunora/flags.ts` — wires `ctx.flags` (OpenFeature) onto every ctx. */
2967
+ hasFlags?: boolean;
992
2968
  /** A `lunora/` source reads `ctx.sql` (Hyperdrive) — wires `ctx.sql` onto the ActionCtx only. */
993
2969
  hasHyperdrive?: boolean;
994
2970
  /** A `lunora/` source reads `ctx.images` — wires `ctx.images` onto the ActionCtx only. */
995
2971
  hasImages?: boolean;
996
2972
  /** A `lunora/` source reads `ctx.kv` — wires `ctx.kv` onto every ctx. */
997
2973
  hasKv?: boolean;
2974
+ /** The project declares `lunora/notify.ts` — wires `ctx.notify` + its `ctx.push` alias (`@lunora/notify`) onto every ctx. */
2975
+ hasNotify?: boolean;
998
2976
  hasPayments?: boolean;
2977
+ /** A `lunora/` source reads `ctx.pipelines` — wires `ctx.pipelines` onto the ActionCtx only. */
2978
+ hasPipelines?: boolean;
999
2979
  /** A `lunora/` source reads `ctx.r2sql` (R2 SQL) — wires `ctx.r2sql` onto the ActionCtx only. */
1000
2980
  hasR2sql?: boolean;
2981
+ /** A `lunora/` source reads `ctx.x402` — wires the agent-wallet pay rail onto the ActionCtx only. */
2982
+ hasX402?: boolean;
1001
2983
  maskMetadata?: MaskMetadataIR;
2984
+ /** Custom mutators declared via `defineMutator` in `lunora/mutators.ts` — wires the `isCustomMutator` push-protocol override. */
2985
+ mutators?: ReadonlyArray<MutatorIR>;
2986
+ /** Queues declared via `defineQueue` exports in `lunora/queues.ts` — wires the typed `ctx.queues` producers. */
2987
+ queues?: ReadonlyArray<QueueIR>;
1002
2988
  rlsMetadata?: RlsMetadataIR;
1003
2989
  schema: SchemaIR;
2990
+ /**
2991
+ * The structural snapshot the pre-deploy drift gate diffs against, threaded
2992
+ * in so the emitted DO records it in `__lunora_schema_history` on cold start
2993
+ * (plan 200 — the Studio's schema-version timeline). Optional so an emitter
2994
+ * caller that has no snapshot (tests, fixtures) emits the pre-ledger shape
2995
+ * unchanged.
2996
+ */
2997
+ schemaSnapshot?: SchemaSnapshot;
2998
+ /** Replication shapes declared via `defineShape` in `lunora/shapes.ts` — wires the `resolveShape` subscription override. */
2999
+ shapes?: ReadonlyArray<ShapeIR>;
1004
3000
  storageRules?: StorageRulesMetadataIR;
1005
3001
  studioFeatures?: StudioFeaturesResult;
1006
3002
  /** The project depends on the `lunora` umbrella — import base packages via its subpaths. */
1007
3003
  useUmbrella?: boolean;
1008
3004
  workflows?: ReadonlyArray<WorkflowIR>;
1009
3005
  }
1010
- declare const emitShard: ({
1011
- advisories,
1012
- containers,
1013
- hasAi,
1014
- hasAnalytics,
1015
- hasBrowser,
1016
- hasHyperdrive,
1017
- hasImages,
1018
- hasKv,
1019
- hasPayments,
1020
- hasR2sql,
1021
- maskMetadata,
1022
- rlsMetadata,
1023
- schema,
1024
- storageRules,
1025
- studioFeatures,
1026
- useUmbrella,
1027
- workflows
1028
- }: EmitShardOptions) => string;
1029
- /**
1030
- * Emit drizzle `sqliteTable` definitions for the project schema, split into
1031
- * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
1032
- * `.global()` go in the global file; everything else (default root + `.shardBy()`)
1033
- * goes in the shard file.
1034
- *
1035
- * `searchIndexes` are intentionally not emitted — drizzle has no `sqliteTable`
1036
- * abstraction for FTS5 virtual tables. FTS plumbing is handled by the runtime
1037
- * outside of drizzle.
1038
- */
3006
+ declare const emitShard: ({ advisories, advisorProcedures, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, schemaSnapshot, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
3007
+ /**
3008
+ * Emit drizzle `sqliteTable` definitions for the project schema, split into
3009
+ * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
3010
+ * `.global()` go in the global file; everything else (default root + `.shardBy()`)
3011
+ * goes in the shard file.
3012
+ *
3013
+ * `searchIndexes` are intentionally not emitted — drizzle has no `sqliteTable`
3014
+ * abstraction for FTS5 virtual tables. FTS plumbing is handled by the runtime
3015
+ * outside of drizzle.
3016
+ */
1039
3017
  declare const emitDrizzleSchema: (schema: SchemaIR, useUmbrella?: boolean) => {
1040
3018
  global: string;
1041
3019
  shard: string;
1042
3020
  };
1043
3021
  /**
1044
- * Emit `_generated/crons.ts` from the discovered cron jobs.
1045
- *
1046
- * `LUNORA_CRON_TRIGGERS` is the deduplicated schedule array — what lands in
1047
- * wrangler's `triggers.crons` (the vite plugin reconciles it into
1048
- * `wrangler.jsonc`, and {@link emitWranglerCronTriggers} renders the same list
1049
- * for the CLI / docs).
1050
- *
1051
- * `LUNORA_CRONS` is the dispatcher map keyed by cron expression, each value a
1052
- * list of `{ name, functionPath, args }`. Cloudflare's `scheduled()` handler
1053
- * receives only the cron string, so multiple jobs sharing one expression must
1054
- * all fire — hence a list per key rather than a single entry.
1055
- *
1056
- * Jobs arrive pre-sorted by name (deterministic output); the trigger array
1057
- * preserves first-seen order of distinct expressions.
1058
- *
1059
- * Cloudflare caps a Worker at **3 Cron Triggers** (i.e. 3 distinct cron
1060
- * expressions). Because the dispatcher fires every job sharing an expression,
1061
- * many jobs can ride a single trigger — only the count of *distinct* schedules
1062
- * matters. `lunora codegen` warns when that count exceeds the limit; for
1063
- * finer-grained scheduling use Durable Object alarms (`@lunora/scheduler`),
1064
- * which have no such cap.
1065
- */
3022
+ * Emit `_generated/crons.ts` from the discovered cron jobs.
3023
+ *
3024
+ * `LUNORA_CRON_TRIGGERS` is the deduplicated schedule array — what lands in
3025
+ * wrangler's `triggers.crons` (the vite plugin reconciles it into
3026
+ * `wrangler.jsonc`, and {@link emitWranglerCronTriggers} renders the same list
3027
+ * for the CLI / docs).
3028
+ *
3029
+ * `LUNORA_CRONS` is the dispatcher map keyed by cron expression, each value a
3030
+ * list of `{ name, functionPath, args }`. Cloudflare's `scheduled()` handler
3031
+ * receives only the cron string, so multiple jobs sharing one expression must
3032
+ * all fire — hence a list per key rather than a single entry.
3033
+ *
3034
+ * Jobs arrive pre-sorted by name (deterministic output); the trigger array
3035
+ * preserves first-seen order of distinct expressions.
3036
+ *
3037
+ * Cloudflare caps a Worker at **3 Cron Triggers** (i.e. 3 distinct cron
3038
+ * expressions). Because the dispatcher fires every job sharing an expression,
3039
+ * many jobs can ride a single trigger — only the count of *distinct* schedules
3040
+ * matters. `lunora codegen` warns when that count exceeds the limit; for
3041
+ * finer-grained scheduling use Durable Object alarms (`@lunora/scheduler`),
3042
+ * which have no such cap.
3043
+ */
1066
3044
  declare const emitCrons: (crons: ReadonlyArray<CronJobIR>) => string;
1067
3045
  /**
1068
- * Render `_generated/vectors.ts` — the static registry of every vector index
1069
- * declared in `schema.ts` (inline `.vectorize()` columns + standalone
1070
- * `defineVectorIndex()` definitions).
1071
- *
1072
- * Cloudflare Vectorize exposes no way to enumerate an account's indexes at
1073
- * runtime — a binding can `describe()` itself but the worker can't ask "which
1074
- * indexes exist". So this generated array is the source of truth the studio's
1075
- * vector browser lists, and the worker's admin route pairs each entry with its
1076
- * live `describe()` stats. Entries are sorted by name for deterministic output.
1077
- */
3046
+ * Render `_generated/vectors.ts` — the static registry of every vector index
3047
+ * declared in `schema.ts` (inline `.vectorize()` columns + standalone
3048
+ * `defineVectorIndex()` definitions).
3049
+ *
3050
+ * Cloudflare Vectorize exposes no way to enumerate an account's indexes at
3051
+ * runtime — a binding can `describe()` itself but the worker can't ask "which
3052
+ * indexes exist". So this generated array is the source of truth the studio's
3053
+ * vector browser lists, and the worker's admin route pairs each entry with its
3054
+ * live `describe()` stats. Entries are sorted by name for deterministic output.
3055
+ */
1078
3056
  declare const emitVectors: (vectorIndexes: ReadonlyArray<VectorIndexIR>) => string;
1079
3057
  /**
1080
- * Render the deduplicated cron schedules as a JSON fragment suitable for
1081
- * splicing into `wrangler.jsonc`'s `triggers.crons`. The vite plugin uses this
1082
- * (plus the parsed wrangler config) to reconcile generated triggers without the
1083
- * user hand-editing the file.
1084
- */
3058
+ * Render the deduplicated cron schedules as a JSON fragment suitable for
3059
+ * splicing into `wrangler.jsonc`'s `triggers.crons`. The vite plugin uses this
3060
+ * (plus the parsed wrangler config) to reconcile generated triggers without the
3061
+ * user hand-editing the file.
3062
+ */
1085
3063
  declare const emitWranglerCronTriggers: (crons: ReadonlyArray<CronJobIR>) => string[];
1086
3064
  /** Which capability methods the generated `defineApp` builder exposes — one flag per package-backed feature the app actually uses. */
1087
3065
  interface EmitAppOptions {
3066
+ /**
3067
+ * Inbound-email agents (`defineAgent({ onEmail })`) → wire the worker's
3068
+ * top-level `email()` handler to `dispatchAgentEmail(...)` (from
3069
+ * `@lunora/agent/inbound`), so received mail starts a durable run. Empty/absent
3070
+ * ⇒ no wiring, byte-identical output for email-free (and agent-free) projects.
3071
+ */
3072
+ emailAgents?: ReadonlyArray<{
3073
+ bindingName: string;
3074
+ exportName: string;
3075
+ }>;
3076
+ /** App depends on `@lunora/cloudflare-access` → emit `.access()` (wire the Cloudflare Access `resolveIdentity`, composed ahead of `@lunora/auth` when both are present). */
3077
+ hasAccess: boolean;
1088
3078
  /** App uses `@lunora/ai` / `ctx.ai` → emit `.ai()` (override the Workers AI binding backing `ctx.ai`). */
1089
3079
  hasAi: boolean;
1090
- /** App uses `@lunora/analytics` / `ctx.analytics` → emit `.analytics()` (override the dataset backing `ctx.analytics`). */
3080
+ /** App uses `@lunora/bindings/analytics` / `ctx.analytics` → emit `.analytics()` (override the dataset backing `ctx.analytics`). */
1091
3081
  hasAnalytics: boolean;
1092
3082
  /** App depends on `@lunora/auth` → emit `.auth()` + the lazy build/migrate dance. */
1093
3083
  hasAuth: boolean;
@@ -1101,13 +3091,17 @@ interface EmitAppOptions {
1101
3091
  hasHyperdrive: boolean;
1102
3092
  /** Schema declares **Hyperdrive-backed** `.global({ backend: "hyperdrive" })` tables → emit `.hyperdriveGlobal()` (reactive Postgres/MySQL ctx-db over Hyperdrive). */
1103
3093
  hasHyperdriveGlobal: boolean;
1104
- /** App uses `@lunora/images` / `ctx.images` → emit `.images()`. */
3094
+ /** App uses `@lunora/bindings/images` / `ctx.images` → emit `.images()`. */
1105
3095
  hasImages: boolean;
1106
- /** App uses `@lunora/kv` / `ctx.kv` → emit `.kv()`. */
3096
+ /** App uses `@lunora/bindings/kv` / `ctx.kv` → emit `.kv()`. */
1107
3097
  hasKv: boolean;
3098
+ /** App declares `lunora/notify.ts` (`@lunora/notify`) → wire `options.notifySubscriptionStore` so the studio Notifications page can read registered devices. */
3099
+ hasNotify: boolean;
1108
3100
  /** App uses `@lunora/payment` / `ctx.payments` → emit `.payment()`. */
1109
3101
  hasPayments: boolean;
1110
- /** App uses `@lunora/r2sql` / `ctx.r2sql` → emit `.r2sql()`. */
3102
+ /** App declares push queues (`defineQueue`)wire `LUNORA_QUEUE_REGISTRY` into the worker's `queue()` consumer entry. */
3103
+ hasQueue: boolean;
3104
+ /** App uses `@lunora/bindings/r2sql` / `ctx.r2sql` → emit `.r2sql()`. */
1111
3105
  hasR2sql: boolean;
1112
3106
  /** App imports `@lunora/scheduler` / declares crons → emit `.scheduler()`. */
1113
3107
  hasScheduler: boolean;
@@ -1117,28 +3111,45 @@ interface EmitAppOptions {
1117
3111
  hasVectors: boolean;
1118
3112
  /** App declares Cloudflare Workflows (`defineWorkflow`) → wire `options.workflowsClient` so the studio's workflow-instance proxy can reach the CF REST API. */
1119
3113
  hasWorkflow: boolean;
3114
+ /** App uses `@lunora/x402/pay` / `ctx.x402` → emit `.x402()` (wire the agent-wallet pay rail). */
3115
+ hasX402: boolean;
3116
+ /** The single `defineIdentity(...)` contract in `lunora/identity.ts` (Plan 080) → import it as a VALUE and wire `options.identity`, so the runtime trust boundary validates every resolved identity before it becomes `ctx.auth`. `undefined` ⇒ no wiring, byte-identical output. */
3117
+ identity?: IdentityIR;
3118
+ /** Schema declares `.jurisdiction("…")` → pin every DO the worker reaches (shards, fan-out, scheduler, containers) to the Cloudflare data-residency jurisdiction. */
3119
+ jurisdiction?: JurisdictionIR;
1120
3120
  /** Project depends on the unscoped `lunorash` umbrella → import the runtime via `lunorash/runtime` instead of `@lunora/runtime`. */
1121
3121
  useUmbrella: boolean;
3122
+ /**
3123
+ * Voice-enabled agents (`defineAgent({ voice: … })`) → wire
3124
+ * `options.voiceAgents`, mapping each agent's export name to its `VOICE_*`
3125
+ * Durable Object namespace binding so the runtime exposes
3126
+ * `/_lunora/voice/<exportName>`. Empty/absent ⇒ no wiring, byte-identical
3127
+ * output for voice-free (and agent-free) projects.
3128
+ */
3129
+ voiceAgents?: ReadonlyArray<{
3130
+ bindingName: string;
3131
+ exportName: string;
3132
+ }>;
1122
3133
  /** An OpenAPI spec is emitted (`openapi.ts`) → wire `openApiSpec` into the worker. */
1123
3134
  wantsOpenApi: boolean;
1124
3135
  /** An OpenRPC spec is emitted (`openrpc.ts`) → wire `openRpcSpec` into the worker. */
1125
3136
  wantsOpenRpc: boolean;
1126
3137
  }
1127
3138
  /**
1128
- * Emit `_generated/app.ts` — a fluent, feature-specialized worker-composition
1129
- * builder. Only the methods for capabilities THIS app uses are emitted, so the
1130
- * builder's type surface (IntelliSense) lists exactly what can be configured.
1131
- *
1132
- * Each capability declaration is fanned into BOTH runtime surfaces: the DO-side
1133
- * `createShardDO(...)` factory that backs `ctx.*`, and the worker-side
1134
- * `createWorker(...)` options that back the studio/admin endpoints — so storage
1135
- * / scheduler / global are declared once instead of twice. The builder is pure
1136
- * sugar over the public `createWorker` / `createShardDO`; both stay usable.
1137
- *
1138
- * Lives in generated code (not `@lunora/runtime`, which is dependency-free) so
1139
- * it can import the add-on packages the app installed (`@lunora/auth`,
1140
- * `@lunora/storage`, …) directly.
1141
- */
3139
+ * Emit `_generated/app.ts` — a fluent, feature-specialized worker-composition
3140
+ * builder. Only the methods for capabilities THIS app uses are emitted, so the
3141
+ * builder's type surface (IntelliSense) lists exactly what can be configured.
3142
+ *
3143
+ * Each capability declaration is fanned into BOTH runtime surfaces: the DO-side
3144
+ * `createShardDO(...)` factory that backs `ctx.*`, and the worker-side
3145
+ * `createWorker(...)` options that back the studio/admin endpoints — so storage
3146
+ * / scheduler / global are declared once instead of twice. The builder is pure
3147
+ * sugar over the public `createWorker` / `createShardDO`; both stay usable.
3148
+ *
3149
+ * Lives in generated code (not `@lunora/runtime`, which is dependency-free) so
3150
+ * it can import the add-on packages the app installed (`@lunora/auth`,
3151
+ * `@lunora/storage`, …) directly.
3152
+ */
1142
3153
  declare const emitApp: (options: EmitAppOptions) => string;
1143
3154
  /** Inputs the OpenAPI emitter needs from a codegen run. */
1144
3155
  interface OpenApiEmitInput {
@@ -1148,40 +3159,40 @@ interface OpenApiEmitInput {
1148
3159
  version?: string;
1149
3160
  }
1150
3161
  /**
1151
- * Emit an OpenAPI 3.1.0 document covering both Lunora function surfaces.
1152
- *
1153
- * `httpRouter()` typed REST routes become real `paths` keyed by their method +
1154
- * URL, with query/path parameters and JSON request bodies derived from their
1155
- * `v.*` validators, and a response schema from `.output()` when declared.
1156
- *
1157
- * RPC `query`/`mutation`/`action` functions become one operation each on
1158
- * `POST /_lunora/rpc` (disambiguated by a `#functionPath` path fragment), with a
1159
- * requestBody pinning `functionPath` + typed `args`. `internal`/`stream`
1160
- * functions are excluded (unreachable / not invocable on the external RPC path).
1161
- *
1162
- * Operations are grouped into `tags` by file namespace, and every operation
1163
- * references a reusable `LunoraError` error-response component enumerating the
1164
- * standard error codes. Borrows oRPC's per-procedure-operation + tag-grouping +
1165
- * internal-filtering structure; the JSON Schema dialect matches `@lunora/values`
1166
- * (Draft 2020-12). Returns the document as a plain object (the single source of
1167
- * truth `emitOpenApi` stringifies and `emitOpenApiModule` inlines, so the
1168
- * `.json` and `.ts` artifacts can never drift).
1169
- */
3162
+ * Emit an OpenAPI 3.1.0 document covering both Lunora function surfaces.
3163
+ *
3164
+ * `httpRouter()` typed REST routes become real `paths` keyed by their method +
3165
+ * URL, with query/path parameters and JSON request bodies derived from their
3166
+ * `v.*` validators, and a response schema from `.output()` when declared.
3167
+ *
3168
+ * RPC `query`/`mutation`/`action` functions become one operation each on
3169
+ * `POST /_lunora/rpc` (disambiguated by a `#functionPath` path fragment), with a
3170
+ * requestBody pinning `functionPath` + typed `args`. `internal`/`stream`
3171
+ * functions are excluded (unreachable / not invocable on the external RPC path).
3172
+ *
3173
+ * Operations are grouped into `tags` by file namespace, and every operation
3174
+ * references a reusable `LunoraError` error-response component enumerating the
3175
+ * standard error codes. Borrows oRPC's per-procedure-operation + tag-grouping +
3176
+ * internal-filtering structure; the JSON Schema dialect matches `@lunora/values`
3177
+ * (Draft 2020-12). Returns the document as a plain object (the single source of
3178
+ * truth `emitOpenApi` stringifies and `emitOpenApiModule` inlines, so the
3179
+ * `.json` and `.ts` artifacts can never drift).
3180
+ */
1170
3181
  declare const buildOpenApiDocument: (input: OpenApiEmitInput) => Record<string, unknown>;
1171
3182
  /**
1172
- * Emit the OpenAPI 3.1 document as a pretty-printed JSON string
1173
- * (`_generated/openapi.json`) — the portable artifact for external tooling.
1174
- */
3183
+ * Emit the OpenAPI 3.1 document as a pretty-printed JSON string
3184
+ * (`_generated/openapi.json`) — the portable artifact for external tooling.
3185
+ */
1175
3186
  declare const emitOpenApi: (input: OpenApiEmitInput) => string;
1176
3187
  /**
1177
- * Emit the OpenAPI document as an importable TS module
1178
- * (`_generated/openapi.ts`) the worker entry imports and passes to
1179
- * `createWorker({ openApiSpec })`. The document object literal is inlined
1180
- * verbatim (same `JSON.stringify` form the `.json` uses), so the `.ts` and
1181
- * `.json` are byte-identical content and regenerate together — closing the gap
1182
- * where a Worker cannot read the JSON file at runtime. `document_` is the object
1183
- * returned by {@link buildOpenApiDocument} (reused, never recomputed).
1184
- */
3188
+ * Emit the OpenAPI document as an importable TS module
3189
+ * (`_generated/openapi.ts`) the worker entry imports and passes to
3190
+ * `createWorker({ openApiSpec })`. The document object literal is inlined
3191
+ * verbatim (same `JSON.stringify` form the `.json` uses), so the `.ts` and
3192
+ * `.json` are byte-identical content and regenerate together — closing the gap
3193
+ * where a Worker cannot read the JSON file at runtime. `document_` is the object
3194
+ * returned by {@link buildOpenApiDocument} (reused, never recomputed).
3195
+ */
1185
3196
  declare const emitOpenApiModule: (document_: Record<string, unknown>) => string;
1186
3197
  /** The OpenRPC dialect version this emitter targets. */
1187
3198
  declare const OPENRPC_VERSION = "1.3.2";
@@ -1192,127 +3203,71 @@ interface OpenRpcEmitInput {
1192
3203
  version?: string;
1193
3204
  }
1194
3205
  /**
1195
- * Emit an OpenRPC 1.x document describing Lunora's JSON-RPC surface.
1196
- *
1197
- * Only the RPC `query`/`mutation`/`action` functions become `methods` — one per
1198
- * function, `name` = `file:fn`. `internal` (off the external RPC path) and
1199
- * `stream` (not invocable over the RPC envelope) are excluded, the same filter
1200
- * the OpenAPI emitter applies. Each method's single `args` param is typed from
1201
- * the function's `v.*` validators (`argsObjectSchema`); `result` is the
1202
- * `.output()` schema when declared, else a best-effort inferred schema. The
1203
- * standard `LunoraError` codes ride along under each method's `errors`.
1204
- *
1205
- * `httpRouter()` typed REST routes are deliberately omitted — OpenRPC is
1206
- * RPC-only and cannot represent REST paths; the OpenAPI document is the spec
1207
- * that covers the REST surface. Methods are sorted by name for stable output.
1208
- * Returns the document as a plain object (the single source of truth
1209
- * `emitOpenRpc` stringifies and `emitOpenRpcModule` inlines, so the `.json` and
1210
- * `.ts` artifacts can never drift).
1211
- */
3206
+ * Emit an OpenRPC 1.x document describing Lunora's JSON-RPC surface.
3207
+ *
3208
+ * Only the RPC `query`/`mutation`/`action` functions become `methods` — one per
3209
+ * function, `name` = `file:fn`. `internal` (off the external RPC path) and
3210
+ * `stream` (not invocable over the RPC envelope) are excluded, the same filter
3211
+ * the OpenAPI emitter applies. Each method's single `args` param is typed from
3212
+ * the function's `v.*` validators (`argsObjectSchema`); `result` is the
3213
+ * `.output()` schema when declared, else a best-effort inferred schema. The
3214
+ * standard `LunoraError` codes ride along under each method's `errors`.
3215
+ *
3216
+ * `httpRouter()` typed REST routes are deliberately omitted — OpenRPC is
3217
+ * RPC-only and cannot represent REST paths; the OpenAPI document is the spec
3218
+ * that covers the REST surface. Methods are sorted by name for stable output.
3219
+ * Returns the document as a plain object (the single source of truth
3220
+ * `emitOpenRpc` stringifies and `emitOpenRpcModule` inlines, so the `.json` and
3221
+ * `.ts` artifacts can never drift).
3222
+ */
1212
3223
  declare const buildOpenRpcDocument: (input: OpenRpcEmitInput) => Record<string, unknown>;
1213
3224
  /**
1214
- * Emit the OpenRPC 1.x document as a pretty-printed JSON string
1215
- * (`_generated/openrpc.json`) — the portable artifact for external tooling.
1216
- */
3225
+ * Emit the OpenRPC 1.x document as a pretty-printed JSON string
3226
+ * (`_generated/openrpc.json`) — the portable artifact for external tooling.
3227
+ */
1217
3228
  declare const emitOpenRpc: (input: OpenRpcEmitInput) => string;
1218
3229
  /**
1219
- * Emit the OpenRPC document as an importable TS module
1220
- * (`_generated/openrpc.ts`) the worker entry imports and passes to
1221
- * `createWorker({ openRpcSpec })`. The document object literal is inlined
1222
- * verbatim (same `JSON.stringify` form the `.json` uses), so the `.ts` and
1223
- * `.json` are byte-identical content and regenerate together. `document_` is
1224
- * the object returned by {@link buildOpenRpcDocument} (reused, never recomputed).
1225
- */
3230
+ * Emit the OpenRPC document as an importable TS module
3231
+ * (`_generated/openrpc.ts`) the worker entry imports and passes to
3232
+ * `createWorker({ openRpcSpec })`. The document object literal is inlined
3233
+ * verbatim (same `JSON.stringify` form the `.json` uses), so the `.ts` and
3234
+ * `.json` are byte-identical content and regenerate together. `document_` is
3235
+ * the object returned by {@link buildOpenRpcDocument} (reused, never recomputed).
3236
+ */
1226
3237
  declare const emitOpenRpcModule: (document_: Record<string, unknown>) => string;
1227
- /** Current snapshot format version. Bumped if the structural shape below changes. */
1228
- declare const SCHEMA_SNAPSHOT_VERSION: 1;
1229
- /** A single field's structural shape: its value kind and whether it is optional. */
1230
- interface FieldSnapshot {
1231
- /** The validator kind (`string`, `number`, `id`, `object`, …) after unwrapping `v.optional`. */
1232
- kind: string;
1233
- /** True when declared `v.optional(...)` — accepts `undefined` / absent on insert. */
1234
- optional: boolean;
1235
- }
1236
- /** A single secondary index's structural shape. */
1237
- interface IndexSnapshot {
1238
- fields: ReadonlyArray<string>;
1239
- unique: boolean;
1240
- }
1241
- /** A single relation's structural shape. */
1242
- interface RelationSnapshot {
1243
- field: string;
1244
- kind: "many" | "one";
1245
- table: string;
1246
- }
1247
- /** Structural snapshot of one table. */
1248
- interface TableSnapshot {
1249
- /** Field name → {@link FieldSnapshot}, in declared order. */
1250
- fields: Record<string, FieldSnapshot>;
1251
- /** Index name → {@link IndexSnapshot}. */
1252
- indexes: Record<string, IndexSnapshot>;
1253
- /** Relation accessor name → {@link RelationSnapshot}. */
1254
- relations: Record<string, RelationSnapshot>;
1255
- /**
1256
- * `"root"` (default single-DO), `"global"` (D1-replicated), or
1257
- * `"shardBy:&lt;field>"` (partitioned). Encoded as a string so the snapshot
1258
- * stays a plain JSON-stable value.
1259
- */
1260
- shardMode: string;
1261
- }
1262
- /** The committed baseline — a deterministic structural view of the whole schema. */
1263
- interface SchemaSnapshot {
1264
- /** Sorted list of every declared `defineMigration` id at capture time. */
1265
- migrationIds: ReadonlyArray<string>;
1266
- /** Table name → {@link TableSnapshot}, keys sorted for stable serialization. */
1267
- tables: Record<string, TableSnapshot>;
1268
- version: typeof SCHEMA_SNAPSHOT_VERSION;
1269
- }
1270
- /** One classified structural change between the baseline and the current schema. */
1271
- interface DriftChange {
1272
- /** `"breaking"` changes need a data migration; `"safe"` changes are additive. */
1273
- severity: "breaking" | "safe";
1274
- /** Human-readable, actionable description (used in the gate message). */
1275
- summary: string;
1276
- /** A machine-readable change discriminator. */
1277
- type: "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedIndex" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "removedField" | "removedIndex" | "removedRelation" | "removedTable";
1278
- }
1279
- /** The result of diffing two snapshots: every classified change. */
1280
- interface SchemaDrift {
1281
- /** Every classified change, in a stable order (added/changed per table, then removals). */
1282
- changes: ReadonlyArray<DriftChange>;
1283
- }
1284
3238
  /**
1285
- * Build a {@link SchemaSnapshot} from a parsed {@link SchemaIR} and the set of
1286
- * declared migration ids. Tables and migration ids are sorted so the emitted
1287
- * JSON is byte-stable across runs (no spurious diffs / churn).
1288
- */
3239
+ * Build a {@link SchemaSnapshot} from a parsed {@link SchemaIR} and the set of
3240
+ * declared migration ids. Tables and migration ids are sorted so the emitted
3241
+ * JSON is byte-stable across runs AND across machines (no spurious diffs /
3242
+ * churn) — see `sortKeys` in `shared/schema-snapshot.ts` for why that ordering
3243
+ * must not be locale-aware.
3244
+ *
3245
+ * Field / index / relation keys are deliberately NOT sorted: they are emitted in
3246
+ * declaration order from the schema source, which is already deterministic for a
3247
+ * given source file and keeps the snapshot readable next to the schema it mirrors.
3248
+ */
1289
3249
  declare const buildSchemaSnapshot: (schema: SchemaIR, migrationIds: ReadonlyArray<string>) => SchemaSnapshot;
1290
- /** Serialize a snapshot to the exact bytes written to `lunora/.lunora-schema.json` (trailing newline). */
1291
- declare const serializeSchemaSnapshot: (snapshot: SchemaSnapshot) => string;
1292
3250
  /**
1293
- * Thrown by {@link parseSchemaSnapshot} when the baseline file exists but is
1294
- * malformed (bad JSON / wrong version / invalid table shape). Lets the CLI gate
1295
- * treat a corrupt baseline as a hard error rather than silently degrading to a
1296
- * "first capture" that would mask drift and then overwrite the bad file.
1297
- */
1298
- declare class SchemaSnapshotParseError extends Error {
1299
- override readonly name = "SchemaSnapshotParseError";
1300
- }
1301
- /**
1302
- * Parse a committed snapshot file. Returns `undefined` ONLY when the content is
1303
- * absent/empty; throws {@link SchemaSnapshotParseError} when content is present
1304
- * but malformed (bad JSON, wrong version, or structurally-invalid tables) so the
1305
- * caller can distinguish "no baseline yet" (a legitimate first capture) from "a
1306
- * corrupt baseline" (which must not be silently treated as a first capture).
1307
- */
1308
- declare const parseSchemaSnapshot: (content: string | undefined) => SchemaSnapshot | undefined;
3251
+ * Thrown by {@link parseSchemaSnapshot} when the baseline file exists but is
3252
+ * malformed (bad JSON / wrong version / invalid table shape). Lets the CLI gate
3253
+ * treat a corrupt baseline as a hard error rather than silently degrading to a
3254
+ * "first capture" that would mask drift and then overwrite the bad file.
3255
+ */
3256
+ declare class SchemaSnapshotParseError extends LunoraError {
3257
+ constructor(message: string);
3258
+ }
1309
3259
  /**
1310
- * Diff the current snapshot against a committed baseline and classify every
1311
- * structural change. Pure no I/O. When `baseline` is `undefined` (no committed
1312
- * snapshot yet) there is no drift to report: every table is treated as a fresh
1313
- * additive `addedTable`, so a first deploy is never blocked.
1314
- */
1315
- declare const diffSchemaSnapshots: (baseline: SchemaSnapshot | undefined, current: SchemaSnapshot) => SchemaDrift;
3260
+ * Parse a committed snapshot file. Returns `undefined` ONLY when the content is
3261
+ * absent/empty; throws {@link SchemaSnapshotParseError} when content is present
3262
+ * but malformed (bad JSON, wrong version, or structurally-invalid tables) so the
3263
+ * caller can distinguish "no baseline yet" (a legitimate first capture) from "a
3264
+ * corrupt baseline" (which must not be silently treated as a first capture).
3265
+ *
3266
+ * The parsing itself lives in `shared/schema-snapshot.ts` (the Studio reads the
3267
+ * same JSON out of the DO ledger); this wrapper only applies the CLI's policy of
3268
+ * treating a malformed baseline as fatal.
3269
+ */
3270
+ declare const parseSchemaSnapshot: (content: string | undefined) => SchemaSnapshot | undefined;
1316
3271
  /** The decision the pre-deploy gate returns. */
1317
3272
  interface SchemaDriftDecision {
1318
3273
  /** True when the deploy must be blocked (breaking drift with no new migration, and no override). */
@@ -1322,217 +3277,53 @@ interface SchemaDriftDecision {
1322
3277
  /** Migration ids declared now but absent from the baseline — proof a migration was added. */
1323
3278
  newMigrationIds: ReadonlyArray<string>;
1324
3279
  /**
1325
- * A multi-line, actionable explanation. Always present; empty string when
1326
- * there is no drift at all. Mirrors the D1-placeholder guard's message style.
1327
- */
3280
+ * A multi-line, actionable explanation. Always present; empty string when
3281
+ * there is no drift at all. Mirrors the D1-placeholder guard's message style.
3282
+ */
1328
3283
  reason: string;
1329
3284
  }
1330
3285
  /**
1331
- * Decide whether breaking schema drift should block a deploy.
1332
- *
1333
- * Blocks only when the baseline exists (a first-ever capture is never blocking),
1334
- * there is at least one `breaking` change, no NEW migration id was added since
1335
- * the baseline, and the `allowDrift` override is not set. Safe-only drift (or
1336
- * breaking drift accompanied by a new migration id) passes.
1337
- */
3286
+ * Decide whether breaking schema drift should block a deploy.
3287
+ *
3288
+ * Blocks only when the baseline exists (a first-ever capture is never blocking),
3289
+ * there is at least one `breaking` change, no NEW migration id was added since
3290
+ * the baseline, and the `allowDrift` override is not set. Safe-only drift (or
3291
+ * breaking drift accompanied by a new migration id) passes.
3292
+ */
1338
3293
  declare const evaluateSchemaDrift: (options: {
1339
3294
  allowDrift?: boolean;
1340
3295
  baseline: SchemaSnapshot | undefined;
3296
+ /** The command printing the remediation, so it names only flags that command accepts. */
3297
+ command?: string;
1341
3298
  current: SchemaSnapshot;
1342
3299
  }) => SchemaDriftDecision;
1343
3300
  /**
1344
- * Committed, tracked baseline file holding the blessed structural schema
1345
- * snapshot the pre-deploy drift gate diffs against. Lives in `lunora/` (NOT the
1346
- * gitignored `_generated/`) so it is committed alongside `schema.ts`. Leading
1347
- * dot keeps it tucked away next to the schema it describes.
1348
- */
1349
- declare const SCHEMA_SNAPSHOT_FILENAME = ".lunora-schema.json";
1350
- /**
1351
- * Construct the ts-morph `Project` codegen discovers over. Prefers the user's
1352
- * `tsconfig.json` (when one is found walking up from `lunoraDirectory`) so
1353
- * cross-file type resolution and path aliases work; falls back to an isolated
1354
- * project otherwise. This is the exact construction {@link runCodegen} uses
1355
- * when no `project` is injected — exported so a long-lived caller (the Vite
1356
- * dev-loop) can build one once and reuse it across runs via
1357
- * {@link refreshCodegenProject} instead of re-parsing the user's whole TS
1358
- * program on every save.
1359
- */
1360
- declare const createCodegenProject: (lunoraDirectory: string) => Project;
1361
- /**
1362
- * Synchronise a reused {@link createCodegenProject} Project with the current
1363
- * on-disk state of `lunoraDirectory`, so the next {@link runCodegen} sees the
1364
- * same files a freshly-constructed Project would — without re-parsing the whole
1365
- * TS program. Adds any on-disk source file the Project doesn't yet have, and
1366
- * `refreshFromFileSystemSync()`es the ones it does (picking up edits); then
1367
- * removes Project source files under `lunoraDirectory` that no longer exist on
1368
- * disk (the classic stale-deleted-file cache bug).
1369
- *
1370
- * Files outside `lunoraDirectory` (e.g. those pulled in by the user's tsconfig)
1371
- * are left untouched — they back type resolution and rarely change in the
1372
- * dev-loop; a tsconfig change invalidates the whole cached Project upstream.
1373
- */
1374
- declare const refreshCodegenProject: (project: Project, lunoraDirectory: string) => void;
1375
- /**
1376
- * Top-level codegen entry. Parses `&lt;projectRoot>/lunora/schema.ts` and every
1377
- * function file under `&lt;projectRoot>/lunora/`, then writes
1378
- * `_generated/{api,server,dataModel}.ts` next to them.
1379
- *
1380
- * When `LUNORA_CODEGEN_TIMING` is set (truthy), a single diagnostic summary
1381
- * line is written to stderr with the total wall time and the discovery-vs-emit
1382
- * split — opt-in instrumentation that is otherwise zero-cost and side-effect-free
1383
- * on the returned {@link CodegenResult}.
1384
- */
1385
- declare const runCodegen: (options: CodegenOptions) => CodegenResult;
1386
- interface CodegenOptions {
1387
- /**
1388
- * Which machine-readable API spec(s) to emit into `_generated/`.
1389
- *
1390
- * `"openapi"` (the default) writes only `openapi.json` (OpenAPI 3.1; covers
1391
- * both the RPC functions and `httpRouter()` REST routes). `"openrpc"` writes
1392
- * only `openrpc.json` (OpenRPC 1.x; the RPC functions only — OpenRPC cannot
1393
- * represent REST routes). `"both"` writes both files; `"none"` writes neither.
1394
- *
1395
- * Regardless of the choice, `CodegenResult.generated.openApi` and `.openRpc`
1396
- * always carry the rendered string (computation is cheap and pure); only the
1397
- * on-disk write is gated by this option.
1398
- */
1399
- apiSpec?: "both" | "none" | "openapi" | "openrpc";
1400
- /**
1401
- * When true, run discovery + emit (so any schema/function parse error
1402
- * surfaces) but skip writing files to `_generated/`. The returned
1403
- * `outputDirectory` is still the path that *would* have been written.
1404
- */
1405
- dryRun?: boolean;
1406
- /**
1407
- * Run the static schema advisor (unindexed FKs, …) during codegen.
1408
- * Defaults to `true`. When `false`, `CodegenResult.advisories` is empty.
1409
- * Computed regardless of `dryRun`; codegen never prints them — see
1410
- * {@link CodegenResult.advisories}.
1411
- */
1412
- lint?: boolean;
1413
- /** Override the lunora subdirectory name. Defaults to `"lunora"`. */
1414
- lunoraDirectory?: string;
1415
- /**
1416
- * Reuse a previously-constructed ts-morph {@link Project} instead of building
1417
- * a fresh one each run. The caller owns refreshing its source files from disk
1418
- * (see {@link refreshCodegenProject}) — codegen does not re-read changed files
1419
- * off an injected Project. Built via {@link createCodegenProject} when absent.
1420
- * Used by the Vite dev-loop to avoid re-parsing the whole TS program on every
1421
- * save; omit it (CLI one-shot path) to get the default fresh-Project behaviour.
1422
- */
1423
- project?: Project;
1424
- /** Project root containing the `lunora/` directory. */
1425
- projectRoot: string;
1426
- /**
1427
- * Re-bless the committed schema-drift baseline (`lunora/.lunora-schema.json`)
1428
- * with the current structural snapshot. The baseline is ALWAYS written on
1429
- * first capture (when the file is absent); set this to overwrite an existing
1430
- * one — e.g. after the developer has added the data migration that justifies
1431
- * a breaking change. Ignored when `dryRun` is true.
1432
- */
1433
- updateSchemaBaseline?: boolean;
1434
- }
1435
- interface CodegenResult {
1436
- /**
1437
- * Static schema advisor findings (e.g. unindexed foreign keys) produced
1438
- * this run. Empty when `lint` is `false` or the schema is clean. Codegen
1439
- * does not print these itself — each caller presents them through its own
1440
- * channel (the CLI logger, the vite overlay, the studio Advisors table).
1441
- * `formatAdvisories` is exported for a plain multi-line rendering.
1442
- */
1443
- advisories: ReadonlyArray<Finding>;
1444
- /**
1445
- * Containers discovered from `defineContainer` exports in
1446
- * `lunora/containers.ts` — the list the config layer reconciles into
1447
- * wrangler's `containers[]`, `CONTAINER_*` Durable Object bindings, and
1448
- * migration classes. Empty when the project declares no containers.
1449
- */
1450
- containers: ReadonlyArray<ContainerIR>;
1451
- /**
1452
- * Deduplicated cron schedules discovered from `cronJobs()` definitions —
1453
- * the array the vite plugin reconciles into `wrangler.jsonc`'s
1454
- * `triggers.crons`. Empty when the project declares no crons.
1455
- */
1456
- cronTriggers: ReadonlyArray<string>;
1457
- generated: {
1458
- api: string; /** Fluent worker-composition builder (`_generated/app.ts`) — `defineApp()`. Always written. */
1459
- app: string;
1460
- /** Container DO classes (`_generated/containers.ts`); `""` (and not written) when no containers are declared. */
1461
- containers: string;
1462
- crons: string;
1463
- dataModel: string;
1464
- drizzleGlobal: string;
1465
- drizzleShard: string;
1466
- functions: string; /** OpenAPI 3.1.0 document (`_generated/openapi.json`), pretty-printed JSON. */
1467
- openApi: string;
1468
- /**
1469
- * OpenAPI document as an importable TS module (`_generated/openapi.ts`) —
1470
- * `export const openApiSpec`, the worker imports it for
1471
- * `createWorker({ openApiSpec })`. Same document as `openApi`. Written
1472
- * alongside `openapi.json` whenever `apiSpec` includes `openapi`.
1473
- */
1474
- openApiModule: string;
1475
- /** OpenRPC 1.x document (`_generated/openrpc.json`), pretty-printed JSON. Always computed; written only when `apiSpec` includes `openrpc`. */
1476
- openRpc: string;
1477
- /**
1478
- * OpenRPC document as an importable TS module (`_generated/openrpc.ts`) —
1479
- * `export const openRpcSpec`, for `createWorker({ openRpcSpec })`. Same
1480
- * document as `openRpc`. Written alongside `openrpc.json` whenever
1481
- * `apiSpec` includes `openrpc`.
1482
- */
1483
- openRpcModule: string;
1484
- /** Project-bound seed client (`_generated/seed.ts`); `""` (and not written) when `@lunora/seed` is not a declared dependency. */
1485
- seed: string;
1486
- server: string;
1487
- shard: string; /** Static vector-index registry (`_generated/vectors.ts`) — `LUNORA_VECTOR_INDEXES`. Empty array body when the schema declares none. */
1488
- vectors: string;
1489
- /** WorkflowEntrypoint classes (`_generated/workflows.ts`); `""` (and not written) when no workflows are declared. */
1490
- workflows: string;
1491
- };
1492
- outputDirectory: string;
1493
- /**
1494
- * The CURRENT structural schema snapshot computed this run (tables + field
1495
- * kinds/optionality + indexes/relations/shard mode + declared migration ids).
1496
- * The pre-deploy drift gate diffs this against the committed baseline read
1497
- * from {@link CodegenResult.schemaSnapshotPath}. Always present, even on a
1498
- * `dryRun`.
1499
- */
1500
- schemaSnapshot: SchemaSnapshot;
1501
- /** Absolute path of the committed baseline file (`lunora/.lunora-schema.json`). */
1502
- schemaSnapshotPath: string;
1503
- /**
1504
- * Workflows discovered from `defineWorkflow` exports in
1505
- * `lunora/workflows.ts` — the list the config layer reconciles into
1506
- * wrangler's `workflows[]` array. Workflows are NOT Durable Objects, so this
1507
- * adds no binding or migration. Empty when the project declares no workflows.
1508
- */
1509
- workflows: ReadonlyArray<WorkflowIR>;
1510
- }
1511
- /**
1512
- * Convert a {@link SchemaIR} into a synthetic runtime {@link Schema} carrying just
1513
- * the `tables[name].shape` surface `@lunora/seed` introspects. System columns
1514
- * (`_id`, `_creationTime`) are absent from the IR shape, exactly as the seed
1515
- * engine expects (it assigns `_id` itself).
1516
- */
3301
+ * Convert a {@link SchemaIR} into a synthetic runtime {@link Schema} carrying just
3302
+ * the `tables[name].shape` surface `@lunora/seed` introspects. System columns
3303
+ * (`_id`, `_creationTime`) are absent from the IR shape, exactly as the seed
3304
+ * engine expects (it assigns `_id` itself).
3305
+ */
1517
3306
  declare const schemaFromIr: (ir: SchemaIR) => Schema;
1518
3307
  /**
1519
- * Convert a codegen {@link ValidatorIR} into a JSON Schema node. A thin wrapper
1520
- * over the shared {@link jsonSchemaFromNode} core (from `@lunora/values`) with the
1521
- * IR-backed {@link irReader}, so the kind→schema mapping is the *same* algorithm
1522
- * `@lunora/values`' `toJsonSchema` runs — codegen never instantiates the runtime
1523
- * `v.*` objects, it only holds the reflected IR. Shared by the OpenAPI and
1524
- * OpenRPC emitters so both surfaces speak one JSON Schema dialect.
1525
- */
3308
+ * Convert a codegen {@link ValidatorIR} into a JSON Schema node. A thin wrapper
3309
+ * over the shared {@link jsonSchemaFromNode} core (from `@lunora/values`) with the
3310
+ * IR-backed {@link irReader}, so the kind→schema mapping is the *same* algorithm
3311
+ * `@lunora/values`' `toJsonSchema` runs — codegen never instantiates the runtime
3312
+ * `v.*` objects, it only holds the reflected IR. Shared by the OpenAPI and
3313
+ * OpenRPC emitters so both surfaces speak one JSON Schema dialect.
3314
+ */
1526
3315
  declare const validatorIrToJsonSchema: (validator: ValidatorIR) => JsonSchema;
1527
- /** Build `{ type: "object", properties, required }` from an IR shape (mirrors `@lunora/values`' object mapping). */
1528
-
1529
- /**
1530
- * The machine-readable `LunoraError` codes Lunora emits on the RPC + REST
1531
- * surfaces, enumerated from `@lunora/server`'s `CODE_STATUS` map plus the
1532
- * runtime/DO dispatch codes (`FUNCTION_NOT_FOUND`, `PAYLOAD_TOO_LARGE`,
1533
- * `METHOD_NOT_ALLOWED`, the `*_NOT_CONFIGURED` admin gates, …). The list documents
1534
- * the contract; clients switch on `error.code`. Kept sorted for stable output.
1535
- */
3316
+ /**
3317
+ * The machine-readable `LunoraError` codes Lunora emits on the RPC + REST
3318
+ * surfaces, enumerated from `@lunora/server`'s `CODE_STATUS` map plus the
3319
+ * runtime/DO dispatch codes (`FUNCTION_NOT_FOUND`, `PAYLOAD_TOO_LARGE`,
3320
+ * `METHOD_NOT_ALLOWED`, the `*_NOT_CONFIGURED` admin gates, …). The list documents
3321
+ * the contract; clients switch on `error.code`. Kept sorted for stable output.
3322
+ */
1536
3323
  declare const LUNORA_ERROR_CODES: ReadonlyArray<string>;
3324
+ /** The matching secret rule's `kind` for a string value, or `undefined` when none matches. */
3325
+ declare const secretKindOf: (value: string) => string | undefined;
3326
+ /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3327
+ declare const redact: (value: string) => string;
1537
3328
  declare const VERSION = "0.0.0";
1538
- export { type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, type DriftChange, type EmitAppOptions, type FieldSnapshot, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type MaskProcedureIR, type MigrationIR, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type ProjectIR, type QueryReadIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverNondeterministicCalls, discoverQueries, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSchema, discoverStorageRulesMetadata, discoverWorkflows, emitApi, emitApp, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, refreshCodegenProject, runCodegen, schemaFromIr, serializeSchemaSnapshot, validatorIrToJsonSchema };
3329
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };