Repository navigation
feat(craft): add the template registry - #28
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements the template_registry feature, introducing the blueprint, conformance test cases, and the Dart implementation for managing template libraries, host functions, introspection, and component availability. The review feedback highlights critical runtime type-matching issues in template_registry.dart where matching against Map<String, Object> and List is too restrictive for common Dart types. Additionally, it identifies variable shadowing in dependencies.dart where loop variables shadow the _check method's parameter.
| current = switch ((current, part)) { | ||
| (final Map<String, Object> map, final String key) => map[key], | ||
| (final List<Object> list, final int index) | ||
| when index >= 0 && index < list.length => | ||
| list[index], | ||
| _ => null, | ||
| }; |
There was a problem hiding this comment.
Matching against Map<String, Object> and List<Object> is overly restrictive and will fail at runtime if the map or list is typed as Map<String, dynamic>, Map<String, Object?>, or List<Object?> (which are very common in Dart). Using Map<Object?, Object?> and List<Object?> ensures compatibility and consistency with evaluator.dart.
| current = switch ((current, part)) { | |
| (final Map<String, Object> map, final String key) => map[key], | |
| (final List<Object> list, final int index) | |
| when index >= 0 && index < list.length => | |
| list[index], | |
| _ => null, | |
| }; | |
| current = switch ((current, part)) { | |
| (final Map<Object?, Object?> map, final String key) => map[key], | |
| (final List<Object?> list, final int index) | |
| when index >= 0 && index < list.length => | |
| list[index], | |
| _ => null, | |
| }; |
There was a problem hiding this comment.
The metadata is converted to Map<String, Object>/List<Object> at registration (_PrimitiveSnapshot.of → toValue), and _functionMeta builds those types directly, so these patterns always match. Tested with metadata passed as raw jsonDecode output.
| current = switch (current) { | ||
| final Map<String, Object> map => map[segment], | ||
| final List<Object> list when _index.hasMatch(segment) => | ||
| switch (int.tryParse(segment)) { | ||
| final int index when index < list.length => list[index], | ||
| _ => null, | ||
| }, | ||
| _ => null, | ||
| }; |
There was a problem hiding this comment.
Matching against Map<String, Object> and List<Object> is overly restrictive and will fail at runtime if the map or list is typed as Map<String, dynamic>, Map<String, Object?>, or List<Object?>. Using Map<Object?, Object?> and List<Object?> ensures compatibility and consistency with evaluator.dart.
| current = switch (current) { | |
| final Map<String, Object> map => map[segment], | |
| final List<Object> list when _index.hasMatch(segment) => | |
| switch (int.tryParse(segment)) { | |
| final int index when index < list.length => list[index], | |
| _ => null, | |
| }, | |
| _ => null, | |
| }; | |
| current = switch (current) { | |
| final Map<Object?, Object?> map => map[segment], | |
| final List<Object?> list when _index.hasMatch(segment) => | |
| switch (int.tryParse(segment)) { | |
| final int index when index < list.length => list[index], | |
| _ => null, | |
| }, | |
| _ => null, | |
| }; |
There was a problem hiding this comment.
Same as above: the roots are always converted values. meta(path:) works on metadata registered from jsonDecode.
| for (final LibraryName name in optional) { | ||
| if (!imports.contains(name)) { | ||
| throw ArgumentError.value( | ||
| name, | ||
| 'optional', | ||
| 'An optional library must be an import of the library', | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
The loop variable name shadows the parameter LibraryName name of the _check method. Renaming the loop variable to optionalName avoids shadowing and improves code clarity.
| for (final LibraryName name in optional) { | |
| if (!imports.contains(name)) { | |
| throw ArgumentError.value( | |
| name, | |
| 'optional', | |
| 'An optional library must be an import of the library', | |
| ); | |
| } | |
| } | |
| for (final LibraryName optionalName in optional) { | |
| if (!imports.contains(optionalName)) { | |
| throw ArgumentError.value( | |
| optionalName, | |
| 'optional', | |
| 'An optional library must be an import of the library', | |
| ); | |
| } | |
| } |
There was a problem hiding this comment.
Agreed, renamed in the latest push so the name parameter used later in _check isn't shadowed.
| for (final String name in components.keys) { | ||
| if (!exported.contains(name)) { | ||
| throw ArgumentError.value( | ||
| name, | ||
| 'components', | ||
| 'Requirements can only be declared for an exported declaration', | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
The loop variable name shadows the parameter LibraryName name of the _check method. Renaming the loop variable to componentName avoids shadowing and improves code clarity.
| for (final String name in components.keys) { | |
| if (!exported.contains(name)) { | |
| throw ArgumentError.value( | |
| name, | |
| 'components', | |
| 'Requirements can only be declared for an exported declaration', | |
| ); | |
| } | |
| } | |
| for (final String componentName in components.keys) { | |
| if (!exported.contains(componentName)) { | |
| throw ArgumentError.value( | |
| componentName, | |
| 'components', | |
| 'Requirements can only be declared for an exported declaration', | |
| ); | |
| } | |
| } |
There was a problem hiding this comment.
Agreed, renamed in the latest push.
9e7473a to
392184f
Compare
392184f to
3d27bb1
Compare
3d27bb1 to
a8d738d
Compare
a8d738d to
f1b02b7
Compare
f1b02b7 to
f7619cc
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 Clean, well-structured registry implementation — the largest-fixed-point availability solver, imported-only introspection scoping, atomic registration rejections, and 42 conformance cases align tightly with the blueprint.
Approving to keep the stack moving — please address the items below (and the inline comments) in a follow-up PR down the line:
setHostFunctionsskips library-name validation whenfunctionsis empty (template_registry.dart):_qualify(library, const {})produces an empty map, soFunctionRegistrynever runs_checkHostKey. CallingsetHostFunctions(coreLibrary, const {})or passing a reserved-word library name silently succeeds and marks that library as provided. Included a reproducer inline.readSymbolleaks mutable references into_PrimitiveSnapshot.meta(template_registry.dart): Unlikemeta(...)(which runs throughEvaluator→toValue),readSymbolreturns maps/lists straight from_PrimitiveSnapshot.meta, allowing callers (or host functions in #29) to mutate the registry's snapshot in place. Also a tiny duplicateresolveImportedlookup inreadSymbol.- Post-stack barrel tightening reminder (
lib/a2ui_craft.dart): Per our agreement on #23, please includesrc/dependencies.dartandsrc/template_registry.dartin the post-stack barrel-tightening PR (#39still leaves both as bare wildcards). - Minor nit (
dependencies.dart):LibraryDependencies._checkreports'requires'as theArgumentErrorparameter name even when the invalid self-qualifiedWidgetRequirementcame fromcomponents(test inline).
(Noted that live-registration listener notifications are already queued in #39 and catalog JSON schema derivation is intentionally scoped to #31, so those are left out here.)
| standard: const <String, LocalFunction>{}, | ||
| host: _qualify(library, functions), | ||
| ); | ||
| _functionLibraries[library] = Map<String, LocalFunction>.of(functions); | ||
| _rebuildHostFunctions(); | ||
| } | ||
|
|
||
| /// Removes the host functions of [library]; returns whether it had any | ||
| /// registration. | ||
| bool removeHostFunctions(LibraryName library) { | ||
| if (_functionLibraries.remove(library) == null) return false; |
There was a problem hiding this comment.
🤖 setHostFunctions skips library-name validation whenever functions is empty: _qualify(library, const {}) produces an empty map, so FunctionRegistry iterates 0 entries and never calls _checkHostKey.
Because Requirement 8 explicitly supports registering an empty host-function library to mark a library name as provided, setHostFunctions(coreLibrary, const {}) or setHostFunctions(LibraryName(['switch']), const {}) currently succeeds and inserts an invalid library into _functionLibraries (making _provides(coreLibrary, ...) return true even with no core primitive library registered).
Reproducer:
test('setHostFunctions rejects invalid library names even when empty', () {
final TemplateRegistry registry = TemplateRegistry();
expect(
() => registry.setHostFunctions(coreLibrary, const <String, LocalFunction>{}),
throwsArgumentError,
);
expect(
() => registry.setHostFunctions(
const LibraryName(<String>['switch']),
const <String, LocalFunction>{},
),
throwsArgumentError,
);
});Validating library directly (e.g., passing a synthetic probe key like '$library${qualifierSeparator}_' or exposing a library-name check from FunctionRegistry) ensures empty-map registrations enforce the same rules as non-empty ones.
| ResolvedName() => _primitiveMeta(from, reference.symbol), | ||
| UnresolvedName() => switch (_function(from, reference.symbol)) { | ||
| final LocalFunction function => _functionMeta(function), | ||
| null => null, | ||
| }, | ||
| }; | ||
| return _read(meta, reference.parts); | ||
| } | ||
|
|
||
| /// [root] read part by part: a string part reads a map's key, an integer | ||
| /// part a list's index; absent when a part reads nothing. | ||
| static Object _read(Object? root, Iterable<Object> parts) { | ||
| Object? current = root; |
There was a problem hiding this comment.
🤖 readSymbol returns _read(meta, reference.parts) directly without copying, which hands out live mutable references to _PrimitiveSnapshot.meta.
Unlike meta(...) (whose return value is deep-copied by toValue in Evaluator._call), Evaluator returns evaluator.symbols!(library, node) as-is. Mutating a Map or List returned from readSymbol(...) or evaluate(SymbolReference(...)) (or inside a host function in #29) mutates the registry's internal metadata snapshot, breaking Requirement 1 ("The registry MUST use the names and metadata as they were when the library was registered").
Reproducer:
test('mutating readSymbol output does not corrupt registered metadata', () {
final TemplateRegistry registry = TemplateRegistry()
..setPrimitiveLibrary(
_core,
_Primitives(<String, Map<String, Object?>>{
'Text': <String, Object?>{'args': <String, Object?>{'text': true}},
}),
);
final Map<String, Object> args = _probe(registry, 'Text.args') as Map<String, Object>;
args['injected'] = true;
expect(_probe(registry, 'hasWidgetArg(widget: "Text", arg: "injected")'), isFalse);
});Wrapping the return value with toValue(_read(meta, reference.parts)) (or freezing _PrimitiveSnapshot.meta as deeply unmodifiable at registration) closes the leak.
Minor cleanup while touching this method: the ResolvedName() arm calls _primitiveMeta(from, reference.symbol), which runs resolver.resolveImported a second time; matching ResolvedName(isPrimitive: true, :final LibraryName library, name: final String bare) directly avoids the redundant lookup.
| export 'src/rfw/model.dart'; | ||
| export 'src/rfw/text.dart'; | ||
| export 'src/standard_functions.dart'; | ||
| export 'src/template_registry.dart'; |
There was a problem hiding this comment.
Reminder for the post-stack barrel-tightening pass agreed in #23: please include src/dependencies.dart (line 21) and src/template_registry.dart when switching lib/a2ui_craft.dart to explicit show lists (#39 still leaves both as bare wildcards). Explicit exports make public API additions easy to track across the stack and let us decide intentionally whether conformance-oriented methods like Requirement.toJson() or helper constants belong on the main barrel.
| for (final HostRequirement r in <HostRequirement>[ | ||
| ...requires, | ||
| for (final List<HostRequirement> c in components.values) ...c, | ||
| ]) { | ||
| if (r is WidgetRequirement && splitQualifiedName(r.name).$1 == name) { | ||
| throw ArgumentError.value( | ||
| r.name, | ||
| 'requires', | ||
| 'A widget requirement cannot name the library itself', | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
🤖 Nit: when a self-qualified WidgetRequirement comes from components rather than requires, ArgumentError.value(r.name, 'requires', ...) still reports 'requires' as the parameter name. Checking requires and components in separate loops (or passing the source field name) gives a more accurate error.
Drop-in regression test for test/template_registry_test.dart:
test('self-qualified widget requirement in components names components in ArgumentError', () {
final TemplateRegistry registry = TemplateRegistry();
final RemoteWidgetLibrary lib = parseLibraryFile('export widget Card = Text();');
expect(
() => registry.setTemplateLibrary(
const LibraryName(<String>['ui']),
lib,
dependencies: const LibraryDependencies(
components: <String, List<HostRequirement>>{
'Card': <HostRequirement>[WidgetRequirement('ui::Card')],
},
),
),
throwsA(
isA<ArgumentError>().having((ArgumentError e) => e.name, 'name', 'components'),
),
);
});f7619cc to
6520285
Compare
Adds the craft_template_registry feature to craft/packages/a2ui_craft: the set of libraries and host functions an engine offers templates, introspection against it, and dependency gating of the components offered to the agent. - lib/src/template_registry.dart: TemplateRegistry registers, replaces and removes template libraries, primitive libraries (kept as a copy of their names and metadata, which must be values) and host function libraries (bare names registered as lib::name, checked like FunctionRegistry keys); rejected registrations change nothing. It owns the NameResolver and builds each library's function table: the standard functions, the introspection functions answering for that library (hasWidget, hasWidgetArg, hasFunction, hasFunctionArg, hasArg, meta, runtimeVersion, appVersion) and the host functions. It classifies and evaluates values and reads symbol references (Name.args.x) from primitive or function metadata. Introspection resolves names among the calling library's imports only, so a template's own stand-ins never count. Every registration drops derived results. - lib/src/dependencies.dart: LibraryDependencies (optional imports, and widget/function/argument requirements for the library and for single components), copied and checked at registration (optional entries must be imports, component keys exported declarations, and no widget requirement may be qualified with the library's own name), and the availability reports. Availability is the largest fixed point: a library needs its required imports provided (an imported template library only while it is available) and its requirements met; a component also needs its own. hasWidget sees only available components. offeredComponents is what may be presented to the agent. - lib/src/evaluator.dart: Evaluator takes an optional SymbolReader; without one, symbol references stay notEvaluated. - craft/blueprints/features/craft_template_registry.blueprint.md specifies all of it; functions now points to it for symbol references and says it adds the 8 introspection functions to the 28 standard functions; the module layer table and codebase blueprint are updated. - craft/conformance/craft/craft_template_registry.yaml holds 42 cases, each a sequence of registration steps on one registry with evaluation, classification, availability and offered-component queries; test/conformance/template_registry_test.dart runs them, and test/template_registry_test.dart covers metadata that is not a value, null in metadata, the copies taken at registration (primitive metadata and dependency declarations) and per-library tables. - Conformance: the update_registry action and the F-CRAFT-REG-01 to 09 feature IDs. Taken from the prototype (template_registry.dart, dependencies.dart and the introspection functions in functions.dart): the registry's role, the introspection set and its scoping through imported-only resolution, symbol lookup (primitive first, then function), and required vs optional imports. Changed: requirements on widgets, functions and arguments, per component, replace the manifest's optional list alone; availability carries through imported template libraries; function metadata is only its parameters; meta paths read list indexes only in canonical decimal (any size); metadata and dependency declarations are copied and checked at registration. Left out: installing the default template libraries, native component replacement, load-time specialization (a pure optimization), stable sizes, host-supplied function metadata, and catalog schemas derived from args usage (catalog.dart), which move to craft_a2ui_integration because the schema shapes and the binder's setX setters are A2UI's. Co-authored-by: Yegor <yegor.jbanov@gmail.com>
6520285 to
1eb08b2
Compare
…talogs, Wasm tests
From writing the examples and the getting-started guide:
- Building blocks: TextInput, Select and DatePicker draw their `label` above
the field (label style, disabled color, tapping it focuses the field; the
field keeps its semantics name, and its text and focus when the label
comes or goes). Select options may be `{label, value}` pairs. The example
app and the docs drop their `Text` workarounds.
- templateCatalog reports a catalog made with no components, with the reason
(`emptyCatalogReason`: no template library yet, not a template library, no
exported declaration, none available): to `onEmpty`, else to
FlutterError.reportError and a failing assertion in debug builds.
- Parser: positions at a line break, and at the end of a source that is
empty or ends with one, are at column 1 instead of 0; specified in
craft_text_format, conformance cases pin the columns.
- TemplateRegistry keeps an unmodifiable deep copy of each template library
(open nit from #28), switch keys included, and gives back a new copy of it
with `templateLibrary`, so source positions set on what is read back don't
move the positions it reports; `templateLibraryNames` lists them.
- The conformance harness loads its files under dart2wasm (Node's fs via
process.getBuiltinModule); CI runs the engine tests compiled to Wasm, and
the building blocks tests compiled to Wasm in Chrome. No engine case is
skipped there; web_skips.dart would list one, with its reason.
- dart2wasm 3.14 traps when a switch over an `Object?` matches string
constants against a value of another type: `primitiveArg` (metadata such
as `false`) and `decodeExtent` (every numeric size) test for a String
first.
- fix_format.sh passes dart format's page width and trailing comma style, so
it no longer reads analysis_options.yaml and warns about unresolved
`package:` includes when no `pub get` ran.
- Example app: a dark theme; cards have no opaque background, captions use
the host's text color, and errors use it too next to a red icon, since no
one red reaches 4.5:1 on both themes; badge colors darkened to 4.5:1. A
test checks every text (4.5:1, 3:1 when large) and icon (3:1) in both
themes, for every flight status.
…talogs, Wasm tests
From writing the examples and the getting-started guide:
- Building blocks: TextInput, Select and DatePicker draw their `label` above
the field (label style, disabled color, tapping it focuses the field; the
field keeps its semantics name, and its text and focus when the label
comes or goes). Select options may be `{label, value}` pairs. The example
app and the docs drop their `Text` workarounds.
- templateCatalog reports a catalog made with no components, with the reason
(`emptyCatalogReason`: no template library yet, not a template library, no
exported declaration, none available): to `onEmpty`, else to
FlutterError.reportError and a failing assertion in debug builds.
- Parser: positions at a line break, and at the end of a source that is
empty or ends with one, are at column 1 instead of 0; specified in
craft_text_format, conformance cases pin the columns.
- TemplateRegistry keeps an unmodifiable deep copy of each template library
(open nit from #28), switch keys included, and gives back a new copy of it
with `templateLibrary`, so source positions set on what is read back don't
move the positions it reports; `templateLibraryNames` lists them.
- The conformance harness loads its files under dart2wasm (Node's fs via
process.getBuiltinModule); CI runs the engine tests compiled to Wasm, and
the building blocks tests compiled to Wasm in Chrome. No engine case is
skipped there; web_skips.dart would list one, with its reason.
- dart2wasm 3.14 traps when a switch over an `Object?` matches string
constants against a value of another type: `primitiveArg` (metadata such
as `false`) and `decodeExtent` (every numeric size) test for a String
first.
- fix_format.sh passes dart format's page width and trailing comma style, so
it no longer reads analysis_options.yaml and warns about unresolved
`package:` includes when no `pub get` ran.
- Example app: a dark theme; cards have no opaque background, captions use
the host's text color, and errors use it too next to a red icon, since no
one red reaches 4.5:1 on both themes; badge colors darkened to 4.5:1. A
test checks every text (4.5:1, 3:1 when large) and icon (3:1) in both
themes, for every flight status.
Description
Adds the template registry to the Craft engine core: where a host registers template libraries, primitive libraries and host functions, how templates ask what the host supports, and which components may be offered to the agent. Stacked on #27. Same three parts as the other engine PRs: a blueprint, conformance cases and the code.
craft/blueprints/features/craft_template_registry.blueprint.md.TemplateRegistrytakes template libraries, primitive libraries (with metadata) and host functions (lib::name). It owns the name resolver and the function tables, and drops cached results on every change. A rejected registration leaves the registry unchanged.hasWidget,hasWidgetArg,hasFunction,hasFunctionArg,hasArg,metaandruntimeVersion, plus symbol references such asLocation.args.latLong. They answer from the calling library's imports, so they report what the host provides, not a template's own stand-ins. This is how a template adapts to hosts with different capabilities.craft/conformance/craft/craft_template_registry.yaml, plus unit tests.The introspection functions come from yjbanov/a2ui_craft at
aece53f, hence the co-author. An independent review checked the blueprint against the tests and the code, including mutations.Next: the runtime (expanding templates into primitives, local state, events).
Pre-launch Checklist
One time:
For this PR:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).