@almadar/core 7.26.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1474 +0,0 @@
1
- import { a6 as EntityField, a9 as EntityPersistence, cX as TraitReference, c$ as TraitScope, cS as TraitEventListener, a2 as Entity, br as Page, bh as OrbitalSchema, cE as Trait } from '../schema-BVni4uNf.js';
2
- import { S as SExpr } from '../expression-BVRFm0sV.js';
3
- import 'zod';
4
- import '@almadar/patterns';
5
-
6
- /**
7
- * Domain Language Types
8
- *
9
- * AST node types for the domain language that maps to KFlow schema.
10
- * All entity references use explicit names (e.g., Order, Task, CurrentUser)
11
- * per GAP-002 - no magic variables like `entity.` or `context.`.
12
- *
13
- * @packageDocumentation
14
- */
15
-
16
- /**
17
- * Field type mapping: OrbitalSchema type → Domain Language keyword
18
- *
19
- * This is the single source of truth for type conversion.
20
- * When adding new field types to OrbitalSchema, add the mapping here.
21
- */
22
- declare const FIELD_TYPE_MAPPING: {
23
- readonly string: "text";
24
- readonly number: "number";
25
- readonly boolean: "yes/no";
26
- readonly date: "date";
27
- readonly timestamp: "timestamp";
28
- readonly datetime: "datetime";
29
- readonly array: "list";
30
- readonly object: "object";
31
- readonly enum: "enum";
32
- readonly relation: "relation";
33
- };
34
- /**
35
- * Effect operator mapping: Both systems use the same operator names
36
- */
37
- declare const EFFECT_OPERATORS: readonly ["set", "emit", "navigate", "render-ui", "persist", "call-service", "spawn", "despawn", "do", "notify"];
38
- /**
39
- * Effect operator names (S-expression first element)
40
- * These are the operators used in S-expression effects like ['emit', ...]
41
- */
42
- type EffectType = (typeof EFFECT_OPERATORS)[number];
43
- interface SourceLocation {
44
- line: number;
45
- column: number;
46
- offset: number;
47
- }
48
- interface SourceRange {
49
- start: SourceLocation;
50
- end: SourceLocation;
51
- }
52
- interface ASTNode {
53
- type: string;
54
- range?: SourceRange;
55
- }
56
- /**
57
- * Domain Language field types
58
- *
59
- * Note: These map to OrbitalSchema types via DOMAIN_TO_SCHEMA_FIELD_TYPE
60
- */
61
- type DomainFieldType = 'text' | 'long text' | 'number' | 'currency' | 'date' | 'timestamp' | 'datetime' | 'yes/no' | 'enum' | 'list' | 'object' | 'relation';
62
- /**
63
- * OrbitalSchema field types (for reference)
64
- */
65
- type SchemaFieldType = keyof typeof FIELD_TYPE_MAPPING;
66
- /**
67
- * Default value for a `DomainField`. Mirrors the JSON-leaf shape an
68
- * `EntityField.default` may carry on `OrbitalSchema`: scalar, list, or
69
- * nested object (when the field type is `'object'` or `'list'`).
70
- */
71
- type DomainFieldDefault = string | number | boolean | null | DomainFieldDefault[] | {
72
- [k: string]: DomainFieldDefault;
73
- };
74
- /**
75
- * For `fieldType: 'list'`, the typed shape of each item. Mirrors
76
- * `EntityField.items` on `OrbitalSchema`. Currently a single-level
77
- * type tag (matching how the schema uses it); extend if/when nested
78
- * list-of-list / list-of-object signatures are required.
79
- */
80
- interface DomainFieldItems {
81
- type: DomainFieldType;
82
- }
83
- interface DomainField extends ASTNode {
84
- type: 'field';
85
- name: string;
86
- fieldType: DomainFieldType;
87
- required: boolean;
88
- unique: boolean;
89
- auto: boolean;
90
- default?: DomainFieldDefault;
91
- enumValues?: string[];
92
- /** List-of-X item type when `fieldType === 'list'`. */
93
- items?: DomainFieldItems;
94
- }
95
- type RelationshipType = 'belongs_to' | 'has_many' | 'has_one';
96
- interface DomainRelationship extends ASTNode {
97
- type: 'relationship';
98
- relationshipType: RelationshipType;
99
- targetEntity: string;
100
- alias?: string;
101
- }
102
- interface DomainEntity extends ASTNode {
103
- type: 'entity';
104
- name: string;
105
- description: string;
106
- fields: DomainField[];
107
- relationships: DomainRelationship[];
108
- states?: string[];
109
- initialState?: string;
110
- /**
111
- * Storage mode on the resolved schema. Mirrors `EntityPersistence` in
112
- * `@almadar/core/types/entity.ts`. Omitted ⇒ projector defaults to
113
- * `'persistent'`. Domain text syntax: `Persistence: <value>` line in
114
- * the entity section.
115
- */
116
- persistence?: EntityPersistence;
117
- /**
118
- * Storage collection key. Mirrors `OrbitalSchema.entities[i].collection`.
119
- * Omitted ⇒ defaults to `plural(name).toLowerCase()`. Surfaced to the
120
- * factory translator so the LLM can override the storage key without
121
- * touching the entity name (e.g. entity `Product` → collection
122
- * `"catalog"`).
123
- */
124
- collection?: string;
125
- }
126
- interface DomainPageSection extends ASTNode {
127
- type: 'page_section';
128
- description: string;
129
- }
130
- interface DomainPageAction extends ASTNode {
131
- type: 'page_action';
132
- trigger: string;
133
- action: string;
134
- }
135
- interface DomainPage extends ASTNode {
136
- type: 'page';
137
- name: string;
138
- description: string;
139
- purpose: string;
140
- url: string;
141
- primaryEntity?: string;
142
- traitName?: string;
143
- sections: DomainPageSection[];
144
- actions: DomainPageAction[];
145
- onAccess?: string;
146
- }
147
- type ComparisonOperator = '==' | '!=' | '>' | '<' | '>=' | '<=';
148
- type LogicalOperator = 'AND' | 'OR';
149
- interface FieldReference extends ASTNode {
150
- type: 'field_reference';
151
- entityName: string;
152
- fieldName: string;
153
- }
154
- interface FieldCheckCondition extends ASTNode {
155
- type: 'field_check';
156
- field: FieldReference;
157
- check: 'provided' | 'empty' | 'equals';
158
- value?: string | number | boolean;
159
- }
160
- interface ComparisonCondition extends ASTNode {
161
- type: 'comparison';
162
- field: FieldReference;
163
- operator: ComparisonOperator;
164
- value: string | number | boolean;
165
- }
166
- interface UserCheckCondition extends ASTNode {
167
- type: 'user_check';
168
- check: 'is_role' | 'owns_this';
169
- role?: string;
170
- ownerField?: string;
171
- }
172
- interface LogicalCondition extends ASTNode {
173
- type: 'logical';
174
- operator: LogicalOperator;
175
- left: GuardCondition;
176
- right: GuardCondition;
177
- }
178
- type GuardCondition = FieldCheckCondition | ComparisonCondition | UserCheckCondition | LogicalCondition;
179
- interface DomainGuard extends ASTNode {
180
- type: 'guard';
181
- condition: GuardCondition;
182
- raw: string;
183
- }
184
- interface DomainEffect extends ASTNode {
185
- type: 'effect';
186
- effectType: EffectType;
187
- description: string;
188
- config: Record<string, unknown>;
189
- }
190
- interface DomainTransition extends ASTNode {
191
- type: 'transition';
192
- fromState: string;
193
- toState: string;
194
- event: string;
195
- guards: DomainGuard[];
196
- effects: DomainEffect[];
197
- }
198
- interface DomainTick extends ASTNode {
199
- type: 'tick';
200
- name: string;
201
- interval: string;
202
- intervalMs?: number;
203
- guard?: DomainGuard;
204
- effects: DomainEffect[];
205
- }
206
- interface DomainBehavior extends ASTNode {
207
- type: 'behavior';
208
- name: string;
209
- entityName: string;
210
- states: string[];
211
- initialState: string;
212
- transitions: DomainTransition[];
213
- ticks: DomainTick[];
214
- rules: string[];
215
- /**
216
- * Instance- vs collection-scoped state machine. Mirrors
217
- * `Trait.scope: TraitScope` in `@almadar/core/types/trait.ts`.
218
- * Omitted ⇒ projector defaults to `'instance'`. Domain text syntax:
219
- * `Scope: instance|collection` line in the behavior section.
220
- */
221
- scope?: TraitScope;
222
- }
223
- interface DomainDocument extends ASTNode {
224
- type: 'document';
225
- entities: DomainEntity[];
226
- pages: DomainPage[];
227
- behaviors: DomainBehavior[];
228
- }
229
- interface SectionMapping {
230
- sectionId: string;
231
- sectionType: 'entity' | 'page' | 'behavior' | 'tick';
232
- schemaPath: string;
233
- domainText: string;
234
- aiDescription?: string;
235
- range?: SourceRange;
236
- lastModified?: number;
237
- }
238
- interface ParseError {
239
- message: string;
240
- range?: SourceRange;
241
- suggestion?: string;
242
- }
243
- interface ParseResult<T> {
244
- success: boolean;
245
- data?: T;
246
- errors: ParseError[];
247
- warnings: ParseError[];
248
- }
249
- /**
250
- * One field on a factory's canonical entity, in signature form. Mirrors
251
- * the subset of `EntityField` that the projector needs to score a
252
- * domain-entity match. Auto-added audit fields (id / createdAt /
253
- * updatedAt) are omitted by the extractor.
254
- */
255
- interface FactorySignatureEntityField {
256
- name: string;
257
- type: SchemaFieldType;
258
- required: boolean;
259
- }
260
- /**
261
- * The canonical entity a factory produces. Almost always one entity
262
- * per orbital; modeled as an array to keep the door open for orbitals
263
- * that compose multiple entities.
264
- */
265
- interface FactoryEntitySignature {
266
- /** Canonical entity name the factory's params build (e.g. `"ChatMessage"`). */
267
- name: string;
268
- /** Fields the factory emits, post-auto-field stripping. */
269
- fields: ReadonlyArray<FactorySignatureEntityField>;
270
- /** Persistence mode declared on the canonical entity in the `.orb`. */
271
- persistence: EntityPersistence;
272
- }
273
- /**
274
- * One trait the factory composes into the orbital. The projector reads
275
- * these to determine which factory's trait stack covers a given
276
- * `DomainBehavior` + which override knobs a presentation overlay can
277
- * deterministically target. Trait identity is by `name` only; the
278
- * projector matches structurally on the event / config arrays — no
279
- * inferred "kind" tag.
280
- */
281
- interface FactoryTraitSignature {
282
- /** Canonical trait name post-rename (e.g. `"ChatMessageList"`). */
283
- name: string;
284
- /** Event keys this trait emits (post-rename). Read directly from
285
- * the trait's `emits[].event`. */
286
- emittedEvents: ReadonlyArray<string>;
287
- /** Event keys this trait listens for. Read directly from `listens[].event`. */
288
- listenedEvents: ReadonlyArray<string>;
289
- /** Config keys overridable via `traitOverrides.<name>.config.<key>`.
290
- * Read directly from the trait's `config` declaration block. */
291
- overridableConfigKeys: ReadonlyArray<string>;
292
- /** Capability tags lifted directly from the source `.lolo` trait's
293
- * header annotations. Free-form strings — the Phase 4 translator
294
- * overlay matches rules to traits by exact set membership. Empty
295
- * when the trait declared none. See `docs/Almadar_Domain_Language.md`
296
- * Phase 3. */
297
- capabilities: ReadonlyArray<string>;
298
- }
299
- /** One page the factory emits. The path is the factory default; the
300
- * projector may override via `params.pagePath` or `params.pages[].path`. */
301
- interface FactoryPageSignature {
302
- name: string;
303
- defaultPath: string;
304
- primaryEntity: string;
305
- }
306
- interface FactorySignature {
307
- /** Organism the factory belongs to (e.g. `"std-realtime-chat"`). */
308
- organism: string;
309
- /** Orbital this factory builds within that organism. */
310
- orbital: string;
311
- /** Tier the factory sits in (informational; drives nothing today). */
312
- tier: 'atoms' | 'molecules' | 'organisms';
313
- /** Path of the generated factory source (relative to the std root). */
314
- factoryPath: string;
315
- /** Canonical entity surface(s) the factory produces. */
316
- entities: ReadonlyArray<FactoryEntitySignature>;
317
- /** Trait stack the factory composes. */
318
- traits: ReadonlyArray<FactoryTraitSignature>;
319
- /** Pages the factory emits. */
320
- pages: ReadonlyArray<FactoryPageSignature>;
321
- /** Union of all `traits[].emittedEvents`. */
322
- emittedEvents: ReadonlyArray<string>;
323
- /** Union of all `traits[].listenedEvents`. */
324
- listenedEvents: ReadonlyArray<string>;
325
- /**
326
- * Phase 5 — canonical starting `DomainDocument` fragment the studio
327
- * questionnaire renders before any user input. Lifted verbatim from
328
- * the factory's resolved `.orb` by `almadar-pattern-sync`. Users
329
- * append / override via `DomainMutation` from the questionnaire UI;
330
- * the base itself is never edited in place (consumers compose with
331
- * `mergeDocuments(base, overlay)`).
332
- *
333
- * Optional during the 7.26.x transition — older catalog snapshots
334
- * predating the sync regeneration omit it. Consumers should fall
335
- * back to building a minimal document from `entities` + `pages`
336
- * when this is missing.
337
- */
338
- baseDocument?: DomainDocument;
339
- }
340
- /**
341
- * Aggregate catalog written to
342
- * `packages/almadar-std/behaviors/registry/factory-signatures.json`.
343
- * Sorted by organism then orbital. One entry per factory in the
344
- * regenerate pipeline.
345
- */
346
- interface FactorySignatureCatalog {
347
- /** Generated-by version stamp (the `@almadar/std` minor it shipped in). */
348
- generatedFromStdVersion: string;
349
- /** Sorted list of factory signatures. */
350
- signatures: ReadonlyArray<FactorySignature>;
351
- }
352
- /**
353
- * A single factory invocation, as the typed result of the translator.
354
- * Lower into runtime by calling the factory at `factoryPath` with
355
- * these `params`. Stable identity for downstream diffing is
356
- * `(organism, orbital)`.
357
- */
358
- interface FactoryCallSite {
359
- /** Matches `FactorySignature.organism`. */
360
- organism: string;
361
- /** Matches `FactorySignature.orbital`. */
362
- orbital: string;
363
- /** Matches `FactorySignature.factoryPath`. Convenience pointer; the
364
- * authoritative source remains the signature catalog. */
365
- factoryPath: string;
366
- /** Typed param surface fed to the factory at invocation time. */
367
- params: FactoryCallSiteParams;
368
- }
369
- /**
370
- * The typed param surface every factory's call site populates. Each
371
- * field on this interface corresponds to one row in the translator's
372
- * domain↔factory mapping table. Adding a new domain concept means
373
- * adding a field here AND wiring it in `translateDomainToParams`.
374
- *
375
- * Fields are all optional because not every factory consumes every
376
- * concept; the translator only sets what the chosen signature
377
- * advertises.
378
- */
379
- interface FactoryCallSiteParams {
380
- /** Override `signature.entities[0].name` (entity rename). */
381
- entityName?: string;
382
- /** Additional or overriding entity fields. Caller wins on collision. */
383
- entityFields?: ReadonlyArray<EntityField>;
384
- /** Override `signature.entities[0].persistence`. */
385
- persistence?: EntityPersistence;
386
- /** Override the entity's storage collection key. Defaults to
387
- * `plural(entityName).toLowerCase()` at factory dispatch time
388
- * when omitted. */
389
- collection?: string;
390
- /** Per-page path overrides keyed by `signature.pages[i].name`. */
391
- pagePaths?: Readonly<Record<string, string>>;
392
- /** Trait config overrides keyed by `signature.traits[i].name`. Each
393
- * value is a record keyed by the trait's `overridableConfigKeys`. */
394
- traitOverrides?: Readonly<Record<string, {
395
- config?: Readonly<Record<string, FactoryParamValue>>;
396
- }>>;
397
- /** Extra traits to compose into the orbital that aren't part of the
398
- * canonical signature trait stack. Used when a domain behavior
399
- * isn't covered by any canonical trait. */
400
- extraTraits?: ReadonlyArray<TraitReference>;
401
- }
402
- /**
403
- * Allowed leaf values for the typed factory-param surface. Same as
404
- * `DomainFieldDefault` minus null, plus arrays + records to mirror
405
- * the trait-config shape factories accept today.
406
- */
407
- type FactoryParamValue = string | number | boolean | ReadonlyArray<FactoryParamValue> | {
408
- readonly [key: string]: FactoryParamValue;
409
- };
410
- /**
411
- * Discriminated union of edits to a `DomainDocument`. Each variant
412
- * carries typed AST nodes already defined in this file — never raw
413
- * JSON. `applyMutation` is total over this union.
414
- */
415
- type DomainMutation = {
416
- kind: 'add-entity';
417
- entity: DomainEntity;
418
- } | {
419
- kind: 'remove-entity';
420
- entityName: string;
421
- } | {
422
- kind: 'rename-entity';
423
- from: string;
424
- to: string;
425
- } | {
426
- kind: 'update-entity';
427
- entityName: string;
428
- entity: DomainEntity;
429
- } | {
430
- kind: 'add-field';
431
- entityName: string;
432
- field: DomainField;
433
- } | {
434
- kind: 'remove-field';
435
- entityName: string;
436
- fieldName: string;
437
- } | {
438
- kind: 'update-field';
439
- entityName: string;
440
- field: DomainField;
441
- } | {
442
- kind: 'add-page';
443
- page: DomainPage;
444
- } | {
445
- kind: 'remove-page';
446
- pageName: string;
447
- } | {
448
- kind: 'update-page';
449
- pageName: string;
450
- page: DomainPage;
451
- } | {
452
- kind: 'add-behavior';
453
- behavior: DomainBehavior;
454
- } | {
455
- kind: 'remove-behavior';
456
- behaviorName: string;
457
- } | {
458
- kind: 'update-behavior';
459
- behaviorName: string;
460
- behavior: DomainBehavior;
461
- } | {
462
- kind: 'add-transition';
463
- behaviorName: string;
464
- transition: DomainTransition;
465
- } | {
466
- kind: 'remove-transition';
467
- behaviorName: string;
468
- from: string;
469
- to: string;
470
- event: string;
471
- } | {
472
- kind: 'add-relationship';
473
- entityName: string;
474
- relationship: DomainRelationship;
475
- } | {
476
- kind: 'remove-relationship';
477
- entityName: string;
478
- targetEntity: string;
479
- relationshipType: RelationshipType;
480
- };
481
- /**
482
- * Cross-cutting presentation knobs that don't live in `DomainDocument`
483
- * because they're factory-layer concerns (nav items live on a layout
484
- * trait; theme is a separate `ThemeRef`). The translator reads these
485
- * and threads them into the matching factory params.
486
- */
487
- interface PresentationOverlay {
488
- /** Nav items to add to the orbital's layout trait. The translator
489
- * looks for a `signature.traits[i]` with `overridableConfigKeys`
490
- * including `navItems` and writes into `traitOverrides[name].config.navItems`. */
491
- navAdditions?: ReadonlyArray<PresentationNavItem>;
492
- /** Optional theme ref override for the orbital. */
493
- themeRef?: string;
494
- }
495
- interface PresentationNavItem {
496
- label: string;
497
- path: string;
498
- /** Optional icon key (consumer-resolved). */
499
- icon?: string;
500
- }
501
- /**
502
- * LLM-authored trait-level overrides keyed by trait name (matches
503
- * `signature.traits[].name`). Each entry's `config` keys are
504
- * validated against `signature.traits[i].overridableConfigKeys`;
505
- * unknown trait names or unknown config keys emit typed warnings
506
- * and are skipped. Mirrors the existing call-site override surface
507
- * on `TraitReference` in `OrbitalSchema`.
508
- */
509
- type TraitOverlay = Readonly<Record<string, TraitOverlayEntry>>;
510
- interface TraitOverlayEntry {
511
- config?: Readonly<Record<string, FactoryParamValue>>;
512
- linkedEntity?: string;
513
- events?: Readonly<Record<string, string>>;
514
- name?: string;
515
- emitsScope?: 'internal' | 'external';
516
- /** Reuses `TraitEventListener` from `@almadar/core/types/trait` so the
517
- * overlay's listen entries carry the same `event` / `triggers` /
518
- * `source` / `guard` shape as everywhere else — no narrower clone. */
519
- listens?: ReadonlyArray<TraitEventListener>;
520
- }
521
- /** @deprecated Phase 4.1 placeholder — use `TraitEventListener` instead.
522
- * Kept as a structural type alias so callers that imported it keep
523
- * compiling through the transition; will be removed in 7.25.0. */
524
- type TraitOverlayListener = TraitEventListener;
525
- /**
526
- * Rules carry a free-form `capability: string` that the translator
527
- * matches against `signature.traits[].capabilities` (source-tagged
528
- * in `.lolo`, propagated via `@almadar/core@7.22.0`).
529
- *
530
- * NO closed enum on `capability` — atoms advertise capability
531
- * strings in their `.lolo` headers, and the catalog grows the
532
- * vocabulary organically. The agent emits whatever capability
533
- * string the user's domain expresses; if no trait in the catalog
534
- * advertises that capability, the translator emits a typed warning.
535
- */
536
- interface RuleOverlay {
537
- rules: ReadonlyArray<DomainRuleOverlayEntry>;
538
- /**
539
- * Entity-level ownership signal. Until Phase 1.5 promotes
540
- * `ownedBy` into `DomainEntity`, ownership rides here as a
541
- * parallel typed channel. The translator threads it into the
542
- * matched trait's `config.ownerField` (when the matched trait
543
- * advertises that key in `overridableConfigKeys`).
544
- */
545
- ownership?: ReadonlyArray<OwnershipOverlayEntry>;
546
- }
547
- interface DomainRuleOverlayEntry {
548
- id: string;
549
- /** Free-form capability label, matched against
550
- * `signature.traits[].capabilities` by exact set membership. */
551
- capability: string;
552
- description: string;
553
- /** Entity names this rule binds to. Empty array = cross-cutting:
554
- * the rule applies to every orbital the translator visits. */
555
- appliesTo: ReadonlyArray<string>;
556
- /** Optional role name (e.g. `"admin"`) when the rule is role-scoped. */
557
- role?: string;
558
- /** Optional extra config knobs threaded into the matched trait's
559
- * `config`. Validated against the trait's `overridableConfigKeys`. */
560
- config?: Readonly<Record<string, FactoryParamValue>>;
561
- }
562
- interface OwnershipOverlayEntry {
563
- /** Entity name (matches `DomainEntity.name`). */
564
- entity: string;
565
- /** Field name on the entity that carries the owner identifier. */
566
- ownerField: string;
567
- }
568
-
569
- /**
570
- * Domain Language Tokens
571
- *
572
- * Token definitions for the domain language lexer.
573
- */
574
- declare enum TokenType {
575
- NEWLINE = "NEWLINE",
576
- INDENT = "INDENT",
577
- DEDENT = "DEDENT",
578
- TEMPLATE_VAR = "TEMPLATE_VAR",
579
- A = "A",
580
- AN = "AN",
581
- IS = "IS",
582
- IT = "IT",
583
- HAS = "HAS",
584
- BELONGS = "BELONGS",
585
- TO = "TO",
586
- MANY = "MANY",
587
- ONE = "ONE",
588
- AS = "AS",
589
- CAN = "CAN",
590
- BE = "BE",
591
- STARTS = "STARTS",
592
- THE = "THE",
593
- SHOWS = "SHOWS",
594
- ENTITY = "ENTITY",// Explicit entity reference for pages
595
- PURPOSE = "PURPOSE",
596
- URL = "URL",
597
- DISPLAYS = "DISPLAYS",
598
- USERS = "USERS",
599
- WHEN = "WHEN",
600
- ACCESSED = "ACCESSED",
601
- LIFECYCLE = "LIFECYCLE",
602
- BEHAVIOR = "BEHAVIOR",
603
- STATES = "STATES",
604
- INITIAL = "INITIAL",
605
- TRANSITIONS = "TRANSITIONS",
606
- FROM = "FROM",
607
- IF = "IF",
608
- THEN = "THEN",
609
- RULES = "RULES",
610
- EVERY = "EVERY",
611
- CHECK = "CHECK",
612
- AND = "AND",
613
- OR = "OR",
614
- NOT = "NOT",
615
- PROVIDED = "PROVIDED",
616
- EMPTY = "EMPTY",
617
- USER = "USER",
618
- OWNS = "OWNS",
619
- THIS = "THIS",
620
- TEXT = "TEXT",
621
- LONG_TEXT = "LONG_TEXT",
622
- NUMBER = "NUMBER",
623
- CURRENCY = "CURRENCY",
624
- DATE = "DATE",
625
- TIMESTAMP = "TIMESTAMP",
626
- YES_NO = "YES_NO",
627
- ENUM = "ENUM",
628
- LIST = "LIST",
629
- REQUIRED = "REQUIRED",
630
- UNIQUE = "UNIQUE",
631
- AUTO = "AUTO",
632
- DEFAULT = "DEFAULT",
633
- COLON = "COLON",
634
- COMMA = "COMMA",
635
- PIPE = "PIPE",
636
- DOT = "DOT",
637
- DASH = "DASH",
638
- LBRACKET = "LBRACKET",
639
- RBRACKET = "RBRACKET",
640
- LPAREN = "LPAREN",
641
- RPAREN = "RPAREN",
642
- GREATER_THAN = "GREATER_THAN",
643
- LESS_THAN = "LESS_THAN",
644
- GREATER_EQUAL = "GREATER_EQUAL",
645
- LESS_EQUAL = "LESS_EQUAL",
646
- EQUALS = "EQUALS",
647
- NOT_EQUALS = "NOT_EQUALS",
648
- IDENTIFIER = "IDENTIFIER",
649
- STRING = "STRING",
650
- NUMBER_LITERAL = "NUMBER_LITERAL",
651
- BOOLEAN = "BOOLEAN",
652
- EOF = "EOF",
653
- ERROR = "ERROR"
654
- }
655
- interface Token {
656
- type: TokenType;
657
- value: string;
658
- line: number;
659
- column: number;
660
- offset: number;
661
- }
662
- declare const KEYWORDS: Record<string, TokenType>;
663
- declare const MULTI_WORD_KEYWORDS: Record<string, TokenType>;
664
-
665
- /**
666
- * Domain Language Lexer
667
- *
668
- * Tokenizes domain language text into tokens for parsing.
669
- */
670
-
671
- declare class Lexer {
672
- private input;
673
- private pos;
674
- private line;
675
- private column;
676
- private indentStack;
677
- constructor(input: string);
678
- /**
679
- * Tokenize the entire input
680
- */
681
- tokenize(): Token[];
682
- private nextToken;
683
- private consumeTemplateVar;
684
- private handleIndentation;
685
- private consumeNewline;
686
- private consumeString;
687
- private consumeNumber;
688
- private consumeIdentifier;
689
- private consumeChar;
690
- private consumeChars;
691
- private skipWhitespace;
692
- private skipToEndOfLine;
693
- private makeToken;
694
- private peek;
695
- private peekNext;
696
- private advance;
697
- private isAtEnd;
698
- private isDigit;
699
- private isAlpha;
700
- private isAlphaNumeric;
701
- }
702
- /**
703
- * Convenience function to tokenize a string
704
- */
705
- declare function tokenize(input: string): Token[];
706
-
707
- /**
708
- * Entity Parser
709
- *
710
- * Parses entity definitions from domain language.
711
- * All entity references are explicit (e.g., Order, User, Task).
712
- */
713
-
714
- /**
715
- * Parse an entity definition from domain text
716
- *
717
- * @example
718
- * parseEntity(`
719
- * A Order is a customer purchase request
720
- * It has:
721
- * - order number: text, required, unique
722
- * - amount: currency
723
- * - status: Pending | Confirmed | Shipped
724
- * It belongs to User
725
- * It can be: Pending, Confirmed, Shipped, Delivered, Cancelled
726
- * It starts as Pending
727
- * `)
728
- */
729
- declare function parseEntity(text: string): ParseResult<DomainEntity>;
730
- /**
731
- * Format an entity AST back to domain text
732
- */
733
- declare function formatEntityToDomain(entity: DomainEntity): string;
734
- /**
735
- * Format entity AST to KFlow schema
736
- */
737
- declare function formatEntityToSchema(entity: DomainEntity): Record<string, unknown>;
738
-
739
- /**
740
- * Page Parser
741
- *
742
- * Parses page definitions from domain language.
743
- */
744
-
745
- /**
746
- * Parse a page definition from domain text
747
- *
748
- * @example
749
- * parsePage(`
750
- * The Dashboard shows an overview of system activity
751
- * Purpose: Help users monitor their tasks and orders
752
- * URL: /dashboard
753
- *
754
- * It displays:
755
- * - Summary statistics for today
756
- * - Recent orders list
757
- * - Pending tasks requiring attention
758
- *
759
- * Users can:
760
- * - Click a task to view details
761
- * - Filter orders by status
762
- * `)
763
- */
764
- declare function parsePage(text: string): ParseResult<DomainPage>;
765
- /**
766
- * Format a page AST back to domain text
767
- */
768
- declare function formatPageToDomain(page: DomainPage): string;
769
- /**
770
- * Format page AST to KFlow schema
771
- */
772
- declare function formatPageToSchema(page: DomainPage): Record<string, unknown>;
773
-
774
- /**
775
- * Behavior Parser
776
- *
777
- * Parses behavior/trait definitions from domain language.
778
- * Behaviors define state machines with transitions, guards, and effects.
779
- * All entity references are explicit (e.g., Order.status, CurrentUser.role).
780
- */
781
-
782
- /**
783
- * Parse a behavior definition from domain text
784
- *
785
- * @example
786
- * parseBehavior(`
787
- * Order Lifecycle
788
- *
789
- * States: Pending, Confirmed, Shipped, Delivered, Cancelled
790
- *
791
- * Transitions:
792
- * - From Pending to Confirmed when CONFIRM
793
- * if Order.amount > 0
794
- * then notify customer
795
- * - From Confirmed to Shipped when SHIP
796
- * - From Shipped to Delivered when DELIVER
797
- * - From any to Cancelled when CANCEL
798
- * if Order.status is not Delivered
799
- *
800
- * Rules:
801
- * - Orders over $1000 require manager approval
802
- * - Cancelled orders cannot be reactivated
803
- * `, "Order")
804
- */
805
- declare function parseBehavior(text: string, entityName: string): ParseResult<DomainBehavior>;
806
- /**
807
- * Format a behavior AST back to domain text
808
- */
809
- declare function formatBehaviorToDomain(behavior: DomainBehavior): string;
810
- /**
811
- * Format behavior AST to KFlow schema trait
812
- */
813
- declare function formatBehaviorToSchema(behavior: DomainBehavior): Record<string, unknown>;
814
-
815
- /**
816
- * Guard Expression Parser
817
- *
818
- * Parses guard expressions deterministically from domain language.
819
- * All entity references are explicit (e.g., Order.amount, CurrentUser.role).
820
- */
821
-
822
- /**
823
- * Parse a guard expression from domain text
824
- *
825
- * @example
826
- * parseGuard("if amount > 1000", "Order")
827
- * // Returns: { field: { entityName: "Order", fieldName: "amount" }, operator: ">", value: 1000 }
828
- */
829
- declare function parseGuard(text: string, entityName: string): ParseResult<DomainGuard>;
830
- /**
831
- * Format a guard condition back to KFlow schema guard string
832
- */
833
- declare function formatGuardToSchema(guard: DomainGuard): string;
834
- /**
835
- * Format a guard condition back to domain language
836
- */
837
- declare function formatGuardToDomain(guard: DomainGuard): string;
838
-
839
- /**
840
- * S-Expression Parser
841
- *
842
- * Parses domain language text (guards/effects) back to S-Expression arrays.
843
- * This is the reverse of what sexpr-formatter.ts does.
844
- *
845
- * @example
846
- * parseDomainGuard("health is at least 0") → [">=", "@entity.health", 0]
847
- * parseDomainEffect("update status to 'done'") → ["set", "@entity.status", "done"]
848
- *
849
- * @packageDocumentation
850
- */
851
-
852
- /**
853
- * Parse a domain guard expression to S-Expression.
854
- *
855
- * @param text - Domain language guard (e.g., "health is at least 0", "status is 'active'")
856
- * @param entityName - The entity context for unqualified field references
857
- * @returns S-Expression array
858
- *
859
- * @example
860
- * parseDomainGuard("health is at least 0") → [">=", "@entity.health", 0]
861
- * parseDomainGuard("status is 'active'") → ["=", "@entity.status", "active"]
862
- * parseDomainGuard("x > 0 and y < 100") → ["and", [">", "@entity.x", 0], ["<", "@entity.y", 100]]
863
- */
864
- declare function parseDomainGuard(text: string, entityName?: string): SExpr;
865
- /**
866
- * Parse a domain effect expression to S-Expression.
867
- *
868
- * @param text - Domain language effect (e.g., "update status to 'done'", "emit ORDER_PLACED")
869
- * @param entityName - The entity context for unqualified field references
870
- * @returns S-Expression array
871
- *
872
- * @example
873
- * parseDomainEffect("update status to 'done'") → ["set", "@entity.status", "done"]
874
- * parseDomainEffect("emit ORDER_PLACED") → ["emit", "ORDER_PLACED"]
875
- * parseDomainEffect("render entity-table to main") → ["render-ui", "main", { type: "entity-table" }]
876
- */
877
- declare function parseDomainEffect(text: string, entityName?: string): SExpr;
878
- /**
879
- * Parse multiple domain effects (comma or "then" separated).
880
- *
881
- * @param text - Domain language effects
882
- * @param entityName - The entity context
883
- * @returns Array of S-Expressions (wrapped in ["do", ...] if multiple)
884
- */
885
- declare function parseDomainEffects(text: string, entityName?: string): SExpr[];
886
-
887
- /**
888
- * Entity Formatter
889
- *
890
- * Converts KFlow DataEntity schema to domain language text.
891
- */
892
-
893
- /**
894
- * Convert a KFlow DataEntity to domain language text
895
- */
896
- declare function formatSchemaEntityToDomain(entity: Record<string, unknown>): string;
897
- /**
898
- * Convert KFlow DataEntity to DomainEntity AST
899
- */
900
- declare function schemaEntityToDomainEntity(entity: Record<string, unknown>): DomainEntity;
901
-
902
- /**
903
- * Page Formatter
904
- *
905
- * Converts KFlow Page schema to domain language text.
906
- */
907
-
908
- /**
909
- * Convert a KFlow Page schema to domain language text
910
- */
911
- declare function formatSchemaPageToDomain(page: Record<string, unknown>): string;
912
- /**
913
- * Convert KFlow Page schema to DomainPage AST
914
- */
915
- declare function schemaPageToDomainPage(page: Record<string, unknown>): DomainPage;
916
-
917
- /**
918
- * Behavior Formatter
919
- *
920
- * Converts KFlow Trait schema to domain language text.
921
- * Supports both legacy typed effects and S-expression format.
922
- */
923
-
924
- /**
925
- * Convert a KFlow Trait schema to domain language text
926
- */
927
- declare function formatSchemaTraitToDomain(trait: Record<string, unknown>, entityName?: string): string;
928
- /**
929
- * Convert KFlow Trait schema to DomainBehavior AST
930
- */
931
- declare function schemaTraitToDomainBehavior(trait: Record<string, unknown>, entityName?: string): DomainBehavior;
932
-
933
- /**
934
- * Guard Formatter
935
- *
936
- * Converts KFlow guard conditions to domain language and vice versa.
937
- * All entity references are explicit (e.g., Order.amount, CurrentUser.role).
938
- *
939
- * Supports both legacy string-based conditions and S-expression format.
940
- */
941
-
942
- /**
943
- * Convert a KFlow schema guard to domain language text.
944
- * Handles both legacy string conditions and S-expression format.
945
- */
946
- declare function formatSchemaGuardToDomain(guard: Record<string, unknown> | unknown[], entityName: string): string;
947
- /**
948
- * Convert a DomainGuard to KFlow schema guard format
949
- */
950
- declare function formatDomainGuardToSchema(guard: DomainGuard): string;
951
- /**
952
- * Format a guard condition AST to domain-friendly text
953
- */
954
- declare function formatGuardConditionToDomain(condition: GuardCondition): string;
955
-
956
- /**
957
- * Schema to Domain Converter
958
- *
959
- * Converts a complete OrbitalSchema to domain language text.
960
- * Generates three sections: Entities, Pages, and Behaviors.
961
- *
962
- * Updated to read from OrbitalSchema where entities, pages, and traits
963
- * are grouped into Orbital units. Also supports legacy KFlowSchema format
964
- * for backward compatibility.
965
- */
966
-
967
- interface SchemaToDomainResult {
968
- /** The complete domain text document */
969
- domainText: string;
970
- /** Parsed AST representation */
971
- document: DomainDocument;
972
- /** Mapping of sections to schema paths */
973
- mappings: SectionMapping[];
974
- /** Separate section texts for individual editing */
975
- sections: {
976
- entities: string[];
977
- pages: string[];
978
- behaviors: string[];
979
- };
980
- }
981
- /**
982
- * Legacy KFlowSchema format (for backward compatibility)
983
- */
984
- interface LegacyKFlowSchema {
985
- name?: string;
986
- dataEntities?: Array<Record<string, unknown>>;
987
- ui?: {
988
- pages?: Array<Record<string, unknown>>;
989
- };
990
- traits?: Array<Record<string, unknown>>;
991
- ticks?: Array<Record<string, unknown>>;
992
- }
993
- /**
994
- * Combined input type for the converter
995
- */
996
- type SchemaInput = OrbitalSchema | LegacyKFlowSchema;
997
- /**
998
- * Convert a complete OrbitalSchema or legacy KFlowSchema to domain language
999
- */
1000
- declare function convertSchemaToDomain(schema: SchemaInput): SchemaToDomainResult;
1001
- /**
1002
- * Convert just the entities section
1003
- */
1004
- declare function convertEntitiesToDomain(entities: Entity[]): string;
1005
- /**
1006
- * Convert just the pages section
1007
- */
1008
- declare function convertPagesToDomain(pages: Page[]): string;
1009
- /**
1010
- * Convert just the traits/behaviors section
1011
- */
1012
- declare function convertTraitsToDomain(traits: Trait[]): string;
1013
-
1014
- /**
1015
- * Domain to Schema Converter
1016
- *
1017
- * Applies domain language text changes to an OrbitalSchema.
1018
- * Supports incremental updates (single section) and full replacement.
1019
- *
1020
- * Updated to use OrbitalSchema where entities, pages, and traits
1021
- * are grouped into Orbital units instead of flat arrays.
1022
- */
1023
-
1024
- interface DomainToSchemaResult {
1025
- /** Whether the conversion was successful */
1026
- success: boolean;
1027
- /** The updated schema */
1028
- schema: OrbitalSchema;
1029
- /** Any parse errors encountered */
1030
- errors: ParseError[];
1031
- /** Warnings (non-fatal issues) */
1032
- warnings: ParseError[];
1033
- /** Updated section mappings */
1034
- mappings: SectionMapping[];
1035
- }
1036
- /**
1037
- * Parse a complete domain document and convert to OrbitalSchema
1038
- */
1039
- declare function convertDomainToSchema(domainText: string, baseSchema?: OrbitalSchema): DomainToSchemaResult;
1040
- /**
1041
- * Apply a single section update to an OrbitalSchema
1042
- */
1043
- declare function applySectionUpdate(schema: OrbitalSchema, sectionType: 'entity' | 'page' | 'behavior' | 'tick', sectionId: string, newDomainText: string): DomainToSchemaResult;
1044
- /**
1045
- * Delete a section from the schema
1046
- */
1047
- declare function deleteSection(schema: OrbitalSchema, sectionType: 'entity' | 'page' | 'behavior' | 'tick', sectionId: string): OrbitalSchema;
1048
-
1049
- /**
1050
- * Deterministic translator: one `DomainDocument` slice + one chosen
1051
- * `FactorySignature` → one `FactoryCallSite`. The agent picks the
1052
- * signature upstream via embedding-search over the catalog; this
1053
- * function does ZERO matching. It just lowers domain fields onto the
1054
- * factory's advertised param surface, field-by-field.
1055
- *
1056
- * The binding (which `DomainEntity` / `DomainPage[]` map to this
1057
- * orbital) is the agent's explicit decision and is passed in. No name
1058
- * matching, no scoring, no tie-breaks.
1059
- *
1060
- * Adding a new domain concept means:
1061
- * 1. Add a field on `DomainEntity` / `DomainPage` / `DomainBehavior`
1062
- * (`packages/almadar-core/src/domain-language/types.ts`).
1063
- * 2. Make sure at least one factory signature advertises a
1064
- * consuming knob (Phase 1.5 gate — generated by
1065
- * almadar-pattern-sync from `.orb`).
1066
- * 3. Add one helper-fn row below that lowers the new field into
1067
- * `FactoryCallSiteParams`.
1068
- *
1069
- * If a binding field has no signature consumer, the translator emits
1070
- * a typed warning and SKIPS the field — that's the loud signal the
1071
- * field shouldn't have been admitted to the language.
1072
- */
1073
-
1074
- /**
1075
- * The slice of `DomainDocument` that maps onto the chosen signature.
1076
- * The agent assembles this when it picks the signature: it knows
1077
- * which `DomainEntity` / `DomainPage[]` are this orbital's
1078
- * responsibility.
1079
- */
1080
- interface TranslationBinding {
1081
- /** The single domain entity this signature's orbital owns. */
1082
- entity: DomainEntity;
1083
- /** Pages from the domain doc that map to this orbital's pages. The
1084
- * translator pairs them with `signature.pages[]` by name. */
1085
- pages?: ReadonlyArray<DomainPage>;
1086
- }
1087
- interface TranslationWarning {
1088
- /** Dotted path of the domain field that couldn't be lowered. */
1089
- field: string;
1090
- /** Human-readable reason. */
1091
- reason: string;
1092
- }
1093
- interface TranslationResult {
1094
- callSite: FactoryCallSite;
1095
- warnings: ReadonlyArray<TranslationWarning>;
1096
- }
1097
- declare function translateDomainToParams(binding: TranslationBinding, signature: FactorySignature, presentation?: PresentationOverlay, ruleOverlay?: RuleOverlay, traitOverlay?: TraitOverlay, catalog?: ReadonlyArray<FactorySignature>): TranslationResult;
1098
-
1099
- /**
1100
- * Structural diff between two `FactoryCallSite[]` lists. Pure typed,
1101
- * no side effects. Used by downstream consumers (agent planner, UI
1102
- * cascade view) to turn a "previous calls" + "next calls" pair into a
1103
- * minimal change set.
1104
- *
1105
- * Identity for diffing is `(organism, orbital)`. Renames are not
1106
- * handled here — they show up as a delete + add. The agent layer is
1107
- * expected to merge those back into a `'rename'` op if it can prove
1108
- * the underlying domain entity was renamed.
1109
- */
1110
-
1111
- type CallSiteDiff = {
1112
- kind: 'add';
1113
- orbitalName: string;
1114
- next: FactoryCallSite;
1115
- } | {
1116
- kind: 'delete';
1117
- orbitalName: string;
1118
- prior: FactoryCallSite;
1119
- } | {
1120
- kind: 'edit';
1121
- orbitalName: string;
1122
- prior: FactoryCallSite;
1123
- next: FactoryCallSite;
1124
- } | {
1125
- kind: 'keep';
1126
- orbitalName: string;
1127
- call: FactoryCallSite;
1128
- };
1129
- declare function diffFactoryCalls(prior: ReadonlyArray<FactoryCallSite>, next: ReadonlyArray<FactoryCallSite>): ReadonlyArray<CallSiteDiff>;
1130
-
1131
- /**
1132
- * Section Mapping
1133
- *
1134
- * Tracks the relationship between domain language sections and KFlow schema paths.
1135
- * Enables bidirectional sync and conflict detection.
1136
- */
1137
-
1138
- interface MappingStore {
1139
- /** All tracked mappings */
1140
- mappings: SectionMapping[];
1141
- /** Last sync timestamp */
1142
- lastSync: number;
1143
- /** Schema version hash for change detection */
1144
- schemaHash?: string;
1145
- }
1146
- /**
1147
- * Create a new mapping store
1148
- */
1149
- declare function createMappingStore(mappings?: SectionMapping[]): MappingStore;
1150
- /**
1151
- * Find a mapping by section ID
1152
- */
1153
- declare function findMapping(store: MappingStore, sectionId: string): SectionMapping | undefined;
1154
- /**
1155
- * Find a mapping by schema path
1156
- */
1157
- declare function findMappingByPath(store: MappingStore, schemaPath: string): SectionMapping | undefined;
1158
- /**
1159
- * Find all mappings of a specific type
1160
- */
1161
- declare function findMappingsByType(store: MappingStore, sectionType: 'entity' | 'page' | 'behavior' | 'tick'): SectionMapping[];
1162
- /**
1163
- * Update or add a mapping
1164
- */
1165
- declare function upsertMapping(store: MappingStore, mapping: SectionMapping): MappingStore;
1166
- /**
1167
- * Remove a mapping
1168
- */
1169
- declare function removeMapping(store: MappingStore, sectionId: string): MappingStore;
1170
- /**
1171
- * Detect changes between old and new mappings
1172
- */
1173
- declare function detectChanges(oldMappings: SectionMapping[], newMappings: SectionMapping[]): {
1174
- added: SectionMapping[];
1175
- removed: SectionMapping[];
1176
- modified: SectionMapping[];
1177
- };
1178
- /**
1179
- * Generate a unique section ID
1180
- */
1181
- declare function generateSectionId(sectionType: 'entity' | 'page' | 'behavior' | 'tick', name: string): string;
1182
- /**
1183
- * Extract section type and name from a section ID
1184
- */
1185
- declare function parseSectionId(sectionId: string): {
1186
- sectionType: 'entity' | 'page' | 'behavior' | 'tick';
1187
- name: string;
1188
- } | null;
1189
- /**
1190
- * Get the schema path for a section
1191
- */
1192
- declare function getSchemaPath(sectionType: 'entity' | 'page' | 'behavior' | 'tick', index: number): string;
1193
- /**
1194
- * Update range information for a mapping based on text position
1195
- */
1196
- declare function updateMappingRange(mapping: SectionMapping, fullText: string): SectionMapping;
1197
- /**
1198
- * Resolve conflicts between domain changes and schema changes
1199
- */
1200
- declare function resolveConflict(domainMapping: SectionMapping, schemaMapping: SectionMapping, preference: 'domain' | 'schema' | 'newest'): SectionMapping;
1201
- /**
1202
- * Compute a simple hash of a schema for change detection
1203
- */
1204
- declare function computeSchemaHash(schema: Record<string, unknown>): string;
1205
- /**
1206
- * Check if schema has changed since last sync
1207
- */
1208
- declare function hasSchemaChanged(store: MappingStore, schema: Record<string, unknown>): boolean;
1209
- /**
1210
- * Update the schema hash in the store
1211
- */
1212
- declare function updateSchemaHash(store: MappingStore, schema: Record<string, unknown>): MappingStore;
1213
-
1214
- /**
1215
- * Domain Language Chunk Merging
1216
- *
1217
- * Utilities for merging multiple domain language chunks into a single document.
1218
- * Used by the lean skill to generate orbitals incrementally.
1219
- *
1220
- * @packageDocumentation
1221
- */
1222
- interface DomainChunk {
1223
- /** The domain language text for this orbital */
1224
- text: string;
1225
- /** Optional name for this orbital (for debugging) */
1226
- name?: string;
1227
- }
1228
- interface MergeResult {
1229
- /** The merged domain language text */
1230
- text: string;
1231
- /** Number of entities merged */
1232
- entityCount: number;
1233
- /** Number of pages merged */
1234
- pageCount: number;
1235
- /** Number of behaviors merged */
1236
- behaviorCount: number;
1237
- }
1238
- /**
1239
- * Merge multiple domain language chunks into a single document.
1240
- *
1241
- * Each chunk can contain:
1242
- * - `# Entities` section with entity definitions
1243
- * - `# Pages` section with page definitions
1244
- * - `# Behaviors` section with behavior/trait definitions
1245
- *
1246
- * The merge combines all sections, maintaining the standard order:
1247
- * 1. Entities
1248
- * 2. Pages
1249
- * 3. Behaviors
1250
- *
1251
- * @example
1252
- * ```typescript
1253
- * const chunks = [
1254
- * { text: '# Entities\n\nA Task is...', name: 'Task' },
1255
- * { text: '# Entities\n\nA User is...', name: 'User' },
1256
- * ];
1257
- * const result = mergeDomainChunks(chunks);
1258
- * // result.text contains both entities merged
1259
- * ```
1260
- */
1261
- declare function mergeDomainChunks(chunks: DomainChunk[]): MergeResult;
1262
- /**
1263
- * Validate that a domain chunk has the expected structure.
1264
- * Returns errors if the chunk is malformed.
1265
- */
1266
- declare function validateDomainChunk(chunk: DomainChunk): string[];
1267
- /**
1268
- * Format a merged result as a summary string
1269
- */
1270
- declare function formatMergeSummary(result: MergeResult): string;
1271
-
1272
- /**
1273
- * Phase 5 — `mergeDocuments(base, overlay)` overlay reducer.
1274
- *
1275
- * The studio questionnaire renders `mergeDocuments(factoryBase,
1276
- * userOverlay)` as its surface — the user edits the overlay; the base
1277
- * never mutates. Server-side, the planner reads the user's persisted
1278
- * overlay and merges it on top of the catalog's `baseDocument` to
1279
- * derive the final `DomainDocument` fed to `translateDomainToParams`.
1280
- *
1281
- * Semantics:
1282
- * - `entities[]`, `pages[]`, `behaviors[]` matched by `name`. The
1283
- * overlay's entry replaces the base's; missing names from one side
1284
- * are kept verbatim from the other.
1285
- * - Within a matched entity / page / behavior, overlay fields win
1286
- * (overlay-replace, not deep-merge). This means a user clearing
1287
- * `fields: []` is honoured rather than silently re-inflating from
1288
- * the base. The questionnaire UI emits partial overlays only for
1289
- * the slots the user touched, so this is the right granularity.
1290
- * - Arrays inside matched entries (`entities[i].fields[]`,
1291
- * `pages[i].sections[]`) are NOT field-level merged — the overlay
1292
- * replaces the base array verbatim when present. For granular
1293
- * additions ("add a field"), the UI authors a `DomainMutation`
1294
- * and applies via `applyMutation` instead of going through
1295
- * `mergeDocuments`.
1296
- * - Top-level `type` is always `'document'`.
1297
- *
1298
- * Pure function — no I/O, no mutation of inputs. Returns a new
1299
- * `DomainDocument`.
1300
- *
1301
- * @packageDocumentation
1302
- */
1303
-
1304
- /**
1305
- * Compose a base `DomainDocument` (factory catalog baseline) with a
1306
- * user-authored overlay (questionnaire answers + edits). Entities,
1307
- * pages, and behaviors are matched by `name`; the overlay replaces
1308
- * any base entry with the same name. Unmatched entries on either side
1309
- * survive unchanged.
1310
- *
1311
- * Idempotent: `mergeDocuments(d, emptyDocument)` returns a deep-copy
1312
- * of `d`. `mergeDocuments(emptyDocument, d)` likewise.
1313
- *
1314
- * @param base The starting document (factory `baseDocument` or
1315
- * organism-level union).
1316
- * @param overlay The user-authored overlay carrying edits.
1317
- * @returns A new merged document; neither input is mutated.
1318
- */
1319
- declare function mergeDocuments(base: DomainDocument, overlay: DomainDocument): DomainDocument;
1320
-
1321
- /**
1322
- * Domain Language Registry
1323
- *
1324
- * Central registry for OrbitalSchema <-> Domain Language mappings.
1325
- * This is the single source of truth for type conversions.
1326
- *
1327
- * When adding a new OrbitalSchema feature:
1328
- * 1. Add type mapping here
1329
- * 2. Formatters/parsers automatically use these mappings
1330
- * 3. Build-time validation ensures coverage
1331
- *
1332
- * @packageDocumentation
1333
- */
1334
-
1335
- /**
1336
- * Field type mapping entry with format/parse functions
1337
- */
1338
- interface FieldTypeMapping {
1339
- /** OrbitalSchema type name */
1340
- schemaType: string;
1341
- /** Domain Language keyword(s) - can be array for aliases */
1342
- domainKeywords: string[];
1343
- /** Format schema field to domain text */
1344
- format: (field: {
1345
- type: string;
1346
- values?: string[];
1347
- relation?: {
1348
- entity: string;
1349
- };
1350
- }) => string;
1351
- /** Parse domain keyword to schema type */
1352
- parse: (keyword: string) => string;
1353
- }
1354
- /**
1355
- * Effect operator mapping entry
1356
- */
1357
- interface EffectMapping {
1358
- /** S-Expression operator name */
1359
- operator: string;
1360
- /** Human-readable domain pattern templates */
1361
- domainPatterns: string[];
1362
- /** Description for documentation */
1363
- description: string;
1364
- }
1365
- /**
1366
- * Guard operator mapping entry
1367
- */
1368
- interface GuardMapping {
1369
- /** S-Expression operator */
1370
- operator: string;
1371
- /** Human-readable domain patterns */
1372
- domainPatterns: string[];
1373
- /** Description */
1374
- description: string;
1375
- }
1376
- /**
1377
- * Complete field type registry with format/parse functions
1378
- */
1379
- declare const FIELD_TYPE_REGISTRY: Record<string, FieldTypeMapping>;
1380
- /**
1381
- * Effect operator registry with human-readable patterns
1382
- */
1383
- declare const EFFECT_REGISTRY: Record<string, EffectMapping>;
1384
- /**
1385
- * Guard operator registry with human-readable patterns
1386
- */
1387
- declare const GUARD_REGISTRY: Record<string, GuardMapping>;
1388
- /**
1389
- * Get all registered field types
1390
- */
1391
- declare function getRegisteredFieldTypes(): string[];
1392
- /**
1393
- * Get all registered effect operators
1394
- */
1395
- declare function getRegisteredEffects(): string[];
1396
- /**
1397
- * Get all registered guard operators
1398
- */
1399
- declare function getRegisteredGuards(): string[];
1400
- /**
1401
- * Check if a field type is registered
1402
- */
1403
- declare function isFieldTypeRegistered(type: string): boolean;
1404
- /**
1405
- * Check if an effect operator is registered
1406
- */
1407
- declare function isEffectRegistered(operator: string): boolean;
1408
- /**
1409
- * Check if a guard operator is registered
1410
- */
1411
- declare function isGuardRegistered(operator: string): boolean;
1412
- /**
1413
- * Get field type mapping
1414
- */
1415
- declare function getFieldTypeMapping(type: string): FieldTypeMapping | undefined;
1416
- /**
1417
- * Get effect mapping
1418
- */
1419
- declare function getEffectMapping(operator: string): EffectMapping | undefined;
1420
- /**
1421
- * Get guard mapping
1422
- */
1423
- declare function getGuardMapping(operator: string): GuardMapping | undefined;
1424
- /**
1425
- * Lookup domain keyword and return schema type
1426
- */
1427
- declare function domainKeywordToSchemaType(keyword: string): string | undefined;
1428
- /**
1429
- * Lookup schema type and return primary domain keyword
1430
- */
1431
- declare function schemaTypeToDomainKeyword(type: string): string | undefined;
1432
- /**
1433
- * Get registry statistics for validation/documentation
1434
- */
1435
- declare function getRegistryStats(): {
1436
- fieldTypes: number;
1437
- effects: number;
1438
- guards: number;
1439
- uiSlots: number;
1440
- };
1441
-
1442
- /**
1443
- * Domain Language Reference — pure function that generates reference docs from the type registry.
1444
- *
1445
- * Separated from generate-docs.ts (CLI script) so it can be compiled and exported.
1446
- */
1447
- /**
1448
- * Generate the complete Domain Language reference document as a string.
1449
- */
1450
- declare function generateDomainLanguageReference(): string;
1451
-
1452
- /**
1453
- * Pure reducer for `DomainMutation` over `DomainDocument`.
1454
- *
1455
- * No I/O. No randomness. Returns a new typed `DomainDocument`
1456
- * (immutable update) so callers can preserve prior state for
1457
- * cross-turn stability. One total switch over the discriminated
1458
- * union — the compiler enforces exhaustiveness via the `never`
1459
- * default branch.
1460
- *
1461
- * Companion to `translateDomainToParams`: the UI/agent emits typed
1462
- * `DomainMutation[]`, the reducer applies them, the translator
1463
- * lowers the result onto factory call sites.
1464
- */
1465
-
1466
- /**
1467
- * Apply one mutation to the document. The original is not modified.
1468
- * Mutations targeting missing entities/pages/behaviors/fields are
1469
- * silently no-ops — callers that care should validate via
1470
- * `findEntity`-style helpers before applying.
1471
- */
1472
- declare function applyMutation(doc: DomainDocument, mut: DomainMutation): DomainDocument;
1473
-
1474
- export { type ASTNode, type CallSiteDiff, type ComparisonCondition, type ComparisonOperator, type DomainBehavior, type DomainChunk, type DomainDocument, type DomainEffect, type DomainEntity, type DomainField, type DomainFieldDefault, type DomainFieldItems, type DomainFieldType, type DomainGuard, type DomainMutation, type DomainPage, type DomainPageAction, type DomainPageSection, type DomainRelationship, type DomainRuleOverlayEntry, type DomainTick, type DomainToSchemaResult, type DomainTransition, EFFECT_REGISTRY, type EffectMapping, type EffectType, EntityPersistence, FIELD_TYPE_REGISTRY, type FactoryCallSite, type FactoryCallSiteParams, type FactoryEntitySignature, type FactoryPageSignature, type FactoryParamValue, type FactorySignature, type FactorySignatureCatalog, type FactorySignatureEntityField, type FactoryTraitSignature, type FieldCheckCondition, type FieldReference, type FieldTypeMapping, GUARD_REGISTRY, type GuardCondition, type GuardMapping, KEYWORDS, Lexer, type LogicalCondition, type LogicalOperator, MULTI_WORD_KEYWORDS, type MappingStore, type MergeResult, type OwnershipOverlayEntry, type ParseError, type ParseResult, type PresentationNavItem, type PresentationOverlay, type RelationshipType, type RuleOverlay, type SchemaFieldType, type SchemaToDomainResult, type SectionMapping, type SourceLocation, type SourceRange, type Token, TokenType, type TraitOverlay, type TraitOverlayEntry, type TraitOverlayListener, TraitScope, type TranslationBinding, type TranslationResult, type TranslationWarning, type UserCheckCondition, applyMutation, applySectionUpdate, computeSchemaHash, convertDomainToSchema, convertEntitiesToDomain, convertPagesToDomain, convertSchemaToDomain, convertTraitsToDomain, createMappingStore, deleteSection, detectChanges, diffFactoryCalls, domainKeywordToSchemaType, findMapping, findMappingByPath, findMappingsByType, formatBehaviorToDomain, formatBehaviorToSchema, formatDomainGuardToSchema, formatEntityToDomain, formatEntityToSchema, formatGuardConditionToDomain, formatGuardToDomain, formatGuardToSchema, formatMergeSummary, formatPageToDomain, formatPageToSchema, formatSchemaEntityToDomain, formatSchemaGuardToDomain, formatSchemaPageToDomain, formatSchemaTraitToDomain, generateDomainLanguageReference, generateSectionId, getEffectMapping, getFieldTypeMapping, getGuardMapping, getRegisteredEffects, getRegisteredFieldTypes, getRegisteredGuards, getRegistryStats, getSchemaPath, hasSchemaChanged, isEffectRegistered, isFieldTypeRegistered, isGuardRegistered, mergeDocuments, mergeDomainChunks, parseBehavior, parseDomainEffect, parseDomainEffects, parseDomainGuard, parseEntity, parseGuard, parsePage, parseSectionId, removeMapping, resolveConflict, schemaEntityToDomainEntity, schemaPageToDomainPage, schemaTraitToDomainBehavior, schemaTypeToDomainKeyword, tokenize, translateDomainToParams, updateMappingRange, updateSchemaHash, upsertMapping, validateDomainChunk };