Skip to content

feat(craft): add the template registry - #28

Merged
innkuika merged 1 commit into
craft/engine-functionsfrom
craft/engine-registry
Dec 3, 2026
Merged

innkuika merged 1 commit into
craft/engine-functionsfrom
craft/engine-registry

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Blueprint: craft/blueprints/features/craft_template_registry.blueprint.md.
  • Registration: TemplateRegistry takes 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.
  • Introspection: hasWidget, hasWidgetArg, hasFunction, hasFunctionArg, hasArg, meta and runtimeVersion, plus symbol references such as Location.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.
  • Dependency gating: a library declares optional imports and widget, function and argument requirements, for the whole library or per component. The registry computes which libraries and components are available: libraries that import each other are available together, unavailability carries through imports, and only available components are offered to the agent.
  • Tests: 42 conformance cases in craft/conformance/craft/craft_template_registry.yaml, plus unit tests.
  • Not in this PR: catalog JSON schemas for the agent (they're A2UI-specific, so they move to the A2UI integration PR), and load-time constant folding (a pure optimization).

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:

  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +258 to +264
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,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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,
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +279 to +287
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,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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,
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above: the roots are always converted values. meta(path:) works on metadata registered from jsonDecode.

Comment on lines +154 to +162
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',
);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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',
);
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, renamed in the latest push so the name parameter used later in _check isn't shadowed.

Comment on lines +167 to +175
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',
);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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',
);
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, renamed in the latest push.

@innkuika
innkuika force-pushed the craft/engine-registry branch from 9e7473a to 392184f Compare November 23, 2026 21:00
@innkuika
innkuika force-pushed the craft/engine-registry branch from 392184f to 3d27bb1 Compare November 23, 2026 22:05
@innkuika
innkuika force-pushed the craft/engine-registry branch from 3d27bb1 to a8d738d Compare November 23, 2026 23:19
@innkuika
innkuika marked this pull request as ready for review November 24, 2026 23:11
@innkuika
innkuika requested a review from ditman November 24, 2026 23:11
@innkuika
innkuika force-pushed the craft/engine-registry branch from a8d738d to f1b02b7 Compare December 1, 2026 19:56
@innkuika
innkuika added this pull request to stack #51 December 1, 2026 19:57
@innkuika
innkuika force-pushed the craft/engine-registry branch from f1b02b7 to f7619cc Compare December 1, 2026 20:35

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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:

  1. setHostFunctions skips library-name validation when functions is empty (template_registry.dart): _qualify(library, const {}) produces an empty map, so FunctionRegistry never runs _checkHostKey. Calling setHostFunctions(coreLibrary, const {}) or passing a reserved-word library name silently succeeds and marks that library as provided. Included a reproducer inline.
  2. readSymbol leaks mutable references into _PrimitiveSnapshot.meta (template_registry.dart): Unlike meta(...) (which runs through Evaluator → toValue), readSymbol returns maps/lists straight from _PrimitiveSnapshot.meta, allowing callers (or host functions in #29) to mutate the registry's snapshot in place. Also a tiny duplicate resolveImported lookup in readSymbol.
  3. Post-stack barrel tightening reminder (lib/a2ui_craft.dart): Per our agreement on #23, please include src/dependencies.dart and src/template_registry.dart in the post-stack barrel-tightening PR (#39 still leaves both as bare wildcards).
  4. Minor nit (dependencies.dart): LibraryDependencies._check reports 'requires' as the ArgumentError parameter name even when the invalid self-qualified WidgetRequirement came from components (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.)

Comment on lines +121 to +131
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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.

Comment on lines +244 to +256
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +176 to +187
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',
);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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'),
    ),
  );
});

@innkuika
innkuika force-pushed the craft/engine-registry branch from f7619cc to 6520285 Compare December 2, 2026 19:58
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>
@innkuika
innkuika force-pushed the craft/engine-registry branch from 6520285 to 1eb08b2 Compare December 3, 2026 02:07
innkuika added a commit that referenced this pull request Dec 3, 2026
…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.
@innkuika
innkuika merged commit 680b08d into main Dec 3, 2026
21 checks passed
@innkuika
innkuika deleted the craft/engine-registry branch December 3, 2026 18:59
innkuika added a commit that referenced this pull request Dec 3, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants