ADL 18 · Part III — Expressions, authority, and behavior

0.6.0 reconciled + 0.5.1 detail

AEL — the ADL expression language

ADL 0.6.0 reference · Review draft 1 · November 14, 2026.

Contents · Source map · Evidence

The 0.6 edition note

AEL is shared syntax evaluated in different environments. To understand an expression, identify its consumer, bindings, record snapshot, read authority, and failure handling. A function name being recognized by the engine does not establish that a particular consumer supplies its inputs or permits its reads.

Contexts that must remain distinct

ConsumerRelevant bindings and snapshotBoundary
Ordinary permission expressionActing user and operation-specific record contextClaims configured for policy evaluation are not automatically permission bindings
State transition guardActing user; stored record before applying transition bodyA supplied body cannot change the stored submitter used by the guard
Resource policyrecord, input, user, transition, system, with operation-dependent valuesOn create, the candidate input precedes defaults/hooks in this profile
Policy claim expressionConfigured server-side expression evaluated by supervisorBoolean claim; absence of a referenced claim causes refusal
Journey expressionClosed roots $inputs, $steps, $response, $actor, $journeyAvailability depends on location and control-flow dominance
Declared queryRow fields, $input, and permitted aggregates in selected positionsGoverned by query grammar and field/row authority

This table highlights differences; it is not an exhaustive variable inventory for every consumer. The retained AEL section and the owning feature define the remaining details. In particular, native evaluation of an unknown ordinary identifier and Journey compile-time rejection of an unknown root are different behaviors. The consolidated Journey source’s “Closed AEL” heading is not evidence that all permission and guard evaluators now share Journey’s scope checker.

Guards can use read functions such as exists, count, and lookup in the inspected implementation, under the caller’s readCondition. The policy profile documents a related limit: cross-resource aggregate reads are not a universal application of the target resource’s policies. A successful aggregate evaluation is therefore not evidence of complete policy propagation.

Stored values and effective writes

The calibration example uses user.id != $record.submittedBy in its approval guard. The stored submitter is the comparison target. Later checks on the effective update have a different purpose. Protecting submitter fields against client writes is still necessary; a guard alone is not a field-write policy. The handbook’s recorded HTTP cases exercise attempted provenance forgery and self-review.

Within Journeys, an expression string beginning with $ is evaluated as an expression. Use an explicit $expr wrapper for computed expressions that would otherwise be treated as literal strings. $response is local to the current call’s success/output/failure processing; step results require a valid earlier result on every path. ADL 49 and 51 describe those checks.

The new journey-unknown-input rejection fixture establishes one closed-scope diagnostic. It does not re-execute the inherited arithmetic, truthiness, exact-decimal, date, or aggregate-function matrix. Those observations retain their original baselines, including recorded consumer differences.

Retained reference detail

The numbered sections below are carried from 18-ael.md. Their original baseline and evidence remain attached to the source. Statements about “current” or “checked” behavior in this retained text refer to those original observations unless the edition note explicitly updates them. This is a consolidated draft, not a claim of complete re-verification.

18.1 Scope of this chapter

AEL supplies expressions for validation rules, permissions, transition guards, computed formulas, and other expression-consuming features. This chapter owns expression syntax, values, functions, scope restrictions, target resolution, and engine errors. Each consumer owns when evaluation occurs and what its result does: ADL 19 computed fields, ADL 20 validation, ADL 21 permissions, ADL 22 state machines, and ADL 23 resource rules. An expression cannot infer its available names from its text alone.

The inherited converted chapter (v0.5.0, retired) preserves §§18.1–18.6. Draft 05 §14 governs quoted cross-domain targets, folded aggregate arguments, and the registry-plus-intrinsics inventory. It describes findOne, findMany, lookup, and networkdays as additive implementation prerequisites. The planned cut label in that proposal is historical: all four execute in the compatible Phase-15/16 artifacts checked here.

Current source review is 84ff02ec. Execution uses existing Linux Release artifacts from ../kalos-clone-a, independently identified in the evidence record. Only the documentation adapter was compiled. The preserved Phase-15 guide and delivery report explain implementation choices; the report still contains pending review language, so this draft does not claim an additional Architect countersignature.

Statements labelled observed or implementation limit describe that evidence, not amendments to a governing language rule. A passing assertion that reproduces a defect is not a conformance success. ADL 2 owns these distinctions.

18.2 Values and operators

An AEL expression produces a JSON-shaped value: number, string, boolean, null, array, or object. There are no statements, assignments, or general-purpose loops in the expression grammar. Use quoted YAML strings where YAML would otherwise interpret punctuation; the code blocks below are AEL fragments.

round(hours * rate, 2)
{label: 'billable', values: [1, 2, 3]}
hours > 0 ? 'positive' : 'empty'

Strings accept single or double quotes. Parentheses group expressions; square brackets construct arrays or index values; braces construct object literals. Bare names are context lookups. Missing ordinary names evaluate to null in the checked native engine. Resource-target names have the stricter resolution rules in §18.7.

18.2.1 Precedence and evaluation

The following order is from tightest to loosest. Use parentheses when combining conditionals, null coalescing, and logical expressions.

GroupOperators and formsMeaning
Postfix., ?., [index], function callsRead a member/index or invoke a function
Unary!, unary -Truth negation and numeric negation
Multiplicative*, /, %Multiply, divide, remainder
Additive+, -Add/concatenate and subtract
Relational<, <=, >, >=, inCompare or test membership
Equality==, !=, ===, !==Equality spellings; see the identity limitation below
Logical AND&&Evaluate the right operand only if the left is truthy
Logical OR||Evaluate the right operand only if the left is falsey
Null coalescing??Evaluate the right operand only if the left is null
Conditionalcondition ? yes : noEvaluate only the selected arm

&& and || return operand values, not necessarily booleans. The checked results are 0 && missing() → 0, 'yes' || missing() → 'yes', and 0 ?? 9 → 0. A conditional’s unused arm is not evaluated.

Native truth testing treats null, false, zero, the empty string, and an empty array as false. Nonempty strings, including '0', and objects, including {}, are true. Consumer limit: the current state-machine guard wrapper treats an empty array as true instead; §18.6 records the actual transition.

18.2.2 Numeric conversion, equality, and access

The checked parser stores numeric literals as floating-point values. It does not provide the exact integer/decimal contract of an ADL field merely because a field has an exact numeric type; see ADL 10. The expression 9007199254740992 == 9007199254740993 evaluates true in the native engine because these literals lose their distinction.

+ concatenates when either operand is a string. Thus '2' + 3 returns '23', while '2' - 1 returns 1. Arithmetic conversion rejects '2x' - 1 with error 1102. Division by zero produces error 1104.

Ruling R8 (kalos#476). Division yields an integer when the quotient is exact and a fractional value otherwise. 10 / 2 is 5, not 5.0; 7 / 2 is 3.5. The same rule governs avg().

Ruling R16 (kalos#748) extends this to every arithmetic operator. R8 settled division and left the rest, so 10 / 2 was 5 and 2 * 3 was 6.0 — two answers from one expression, with no rule an author could predict from. That scoping is withdrawn:

2 * 3    ->  6          2 + 3    ->  5          10 - 4  ->  6
17 % 5   ->  2          -5       ->  -5         10 / 2  ->  5

The rule is about the result, not the operands: 10 / 4 is 2.5 and 10 / 5 is 2, and 2.5 * 2 is 5 because the answer has no fractional part even though an operand did. Division is not integer division — nothing is truncated, and 7 / 2 does not yield 3.

sum(), min() and max() follow the rule alongside avg(). They are not operators; they are included because sum([1,2,3]) returning 6.0 beside avg([1,2,3]) returning 2 is the same asymmetry R16 withdraws, inside one family of functions and often inside one expression.

The rounding family follows the rule too (kalos#800): floor(2.5) is 2, ceil(2.5) is 3, round(2.4) is 2, and so do abs, pow, clamp, mod and toNumber. That was not a style question — adl-ref had normalized all eight since R8 while the C++ engine had not, so the two implementations disagreed on every one of them.

The transcendental functions are not covered. sqrt(4) is 2.0, and so are log, exp, sin, cos and tan. Both implementations agree there, and these results are fractional by nature.

This is observable, not cosmetic. The value reaches JSON, where 5 and 5.0 serialize differently and a consumer comparing against 5 sees one and not the other; it reaches string interpolation, where a computed label reads 6 items rather than 6.0 items; and it reaches an exact-typed field, where a fractional value is a validation failure — a document computing quantity * unitCount into an integer field hit exactly that. An author could not previously predict which they would get, because the section showed a result and never stated a rule.

Identity limitation: the conversion presents === and !== as identity operators, but the current parser maps them to == and !=. Do not depend on a separate strict-identity test. Native cross-type equality is also sensitive to JSON string rendering: '1' == 1 is false, '1.0' == 1 is true, and 'false' === false is true. These are checked implementation differences, not a JavaScript compatibility promise.

in tests array membership using JSON equality, object-key membership for a string key, or substring membership for strings. '1' in [1] is false; 'x' in {x: 1} and 'bc' in 'abcd' are true.

Both missing.name and missing?.name return null in the checked engine. The inherited distinction in which ordinary dot access errors on null is not implemented. Member access neither fetches a relationship nor resolves an ADL address. Array indexing is zero-based and supports negative indices: [1,2,3][-1] returns 3. Object indexing accepts string keys. A string is not an indexable array in this implementation; use the string functions.

18.3 Functions

Function names are case-sensitive. The complete generated function reference gives signatures, separate value/target arities and scopes, and one checked example for every current name. Its JSON companion retains source ownership, exact fixture contexts, native observations, and independent modeller results.

The current union is 102 registry functions + 14 evaluator intrinsics − five overlapping names = 111 functions. Draft 05 §14.4’s 101 + 11 − 5 = 107 is a historical baseline before the four named additions. Counting only registered functions misses lazy evaluator operations; adding both counts without deduplicating sum, avg, min, max, and count counts the overloads twice.

SourceLibrary responsibilities
plugins/adl/src/ael/functions.cppString, numeric, ordinary array, conversion, and type functions
plugins/adl/src/ael/functions_date.cppDates, clock functions, and networkdays
plugins/adl/src/ael/functions_adl.cppIdentity, state, field, operation, query, and exists functions
plugins/adl/src/ael/evaluator.cppHigher-order functions and resource-target dispatch, including the five aggregate overloads

The catalog names and links all four sources. A name mentioned in an older function survey but absent from this union is not thereby a promised function. For example, global AEL coalesce(null, 2) fails with 1103. The lightweight computed evaluator’s support for coalesce is a separate fallback contract.

18.3.1 Array values and lambdas

Value aggregates operate on values already in the expression context. sum([1,2,3]) returns 6, avg([1,2,3]) returns 2, and count([1,2,3]) returns 3. avg follows R8: avg([1,2,3]) is 2 because the quotient is exact, and avg([1,2]) is 1.5. Under R16 sum, min and max follow the same rule — sum([1,2,3]) is 6, not 6.0, and sum([1.5, 2]) is 3.5. min and max accept an array or numeric arguments. Resource aggregates are different overloads, described in §18.7.

Draft 05 reconciliation: §14.2 says the array overloads already take two arguments. Current registered sum, avg, and count each take one; sum(items, true) fails with 1104. Apply a condition with filter before aggregating an array. Native sum(['1','2']) produces a type error; do not assume the target aggregate’s permissive conversion applies to arrays.

FormResult
map(array, x => expression)A new array of mapped values
filter(array, x => condition)Elements whose condition is truthy
find(array, x => condition)First matching element, or null
every(array, x => condition)Whether every element satisfies the condition
some(array, x => condition)Whether any element satisfies the condition
reduce(array, (acc, x) => expression[, initial])Successively accumulated value
sum(filter([1, 2, 3], x => x > 1))
map([1, 2, 3], x => x * 2)
reduce([1, 2, 3], (acc, x) => acc + x, 0)

Lambda parameters shadow outer names; other variables remain visible from the parent context. These are evaluator intrinsics, so the lambda is not eagerly evaluated as an ordinary argument. Use one parameter except for reduce’s accumulator and element. An omitted reduction initial value is null, not an implicit first array element.

Implementation limits: a second parameter in map([1,2], (x,i) => i) is unbound and yields [null,null]. Extra function arguments can be ignored: map([1,2], x => x + 1, notAFunction()) returns [2,3] without calling the third argument. A standalone lambda is not a first-class native value. The catalog’s arity metadata describes intended forms, not complete rejection coverage.

18.3.2 String, date, and clock details

The catalog is the full function inventory; a few distinctions affect common formulas. replace('a-a', 'a', 'b') returns 'b-a': it replaces the first occurrence. Date differences are signed in argument order: diffDays(d1,d2) truncates whole days toward zero, whereas diffHours(d1,d2) retains fractional hours. A negative half-day returns 0 from diffDays; a negative six-and-a-half hours returns -6.5 from diffHours. Both modeller and native engine agree on these controls at the reviewed revision.

addMonths('2026-01-31', 1) clamps to '2026-02-28', and adding a year to 2024-02-29 clamps to 2025-02-28. Implementation difference: generic dateAdd('2026-01-31', 1, 'month') still normalizes overflow to '2026-03-03'. Do not substitute it for addMonths at month boundaries. An impossible date such as day('2026-02-29') produces 1102.

Date functions accept a date (YYYY-MM-DD) or an ISO 8601 datetime (YYYY-MM-DDTHH:MM:SS, optionally with fractional seconds and a zone: Z, +HH:MM, +HHMM or +HH, or -). A zone offset is converted to UTC, not ignored, so '2026-10-01T15:30:00+05:00' is 10:30 UTC, and a datetime with no zone is read as UTC. A malformed zone is a type error. Results keep the input’s shape: a date comes back as a date, and a datetime comes back as ISO 8601 UTC with its Z, to the second: addDays('2026-10-01T10:00:00Z', 1) is '2026-10-02T10:00:00Z'. This is the form a datetime field accepts and now() returns (#1079, #1086). An hour, minute or second unit applied to a date makes a datetime: dateAdd('2026-10-01', 3, 'hours') is '2026-10-01T03:00:00Z'. To present a date in another format, use formatDate or the domain’s localization.dateFormat; the stored and wire format stays ISO 8601.

Clock and random functions depend on the evaluation environment. The examples assert result shapes or ranges rather than fixed values. The checked date strings do not establish daylight-saving, locale, or Unicode-string portability. networkdays is specified separately in §18.8.

18.4 Scopes

The language-facing scopes remain Validation, Permission, Guard, and Computed. Scope belongs to an evaluation; a compiled expression can be reused in another context. Function permission and the actual values/handlers supplied by a consumer are separate requirements.

Function family/formValidationPermissionGuardComputed
Ordinary string, numeric, date, array, type, and higher-order functionsYesYesYesYes
Identity and state functionsNoYesYesNo
Field functions: field, hasField, fieldChanged, oldValue, newValueYesNoYesNo
Operation predicates: isCreate, isUpdate, isDeleteYesYesYesNo
query and existsYesNoNoNo
Resource count/sum/avg/min/max, findOne/findMany/lookupYesNoNoYes, but require a handler

Native FnScope::All is an internal default/bit mask, not a fifth authoring scope. In the checked engine, runtime scope violations return 1105. Registry-only preflight checks can miss intrinsic target restrictions; consumer-specific enforcement is described in §18.6.

18.4.1 Names supplied by the consuming operation

The following table records the current consuming implementation. It is more specific than the broad scope table: a scope does not manufacture a variable or query handler merely because a function can use it.

ConsumerExplicit bindings and bare-name fallbackQuery support
Resource validation rule$this merged candidate, $old, $op, and $record for the outer candidate; bare fields fall back to $thisHandler installed for rules identified as using queries/targets
Field custom validatorScalar $value and field-name $fieldDoes not receive the resource-rule record context
Permission expressionuser, record, op, and owner-field metadataNo query handler; bare fields do not fall back to record
State transition guard$record, $this, record, and user; bare fields fall back to $thisNo query handler
Ordinary computed field$this and record; bare fields fall back to $this; no caller identity/requestNo query handler in the checked computed engine

Use record.hours in a permission and hours or $this.hours in a resource validation rule. The actual permission test record.hours <= 8 allows the four-hour row; its bare-field variant hours <= 8 denies. The inherited permission fallback claim is not implemented.

The inherited permission contract supplies an empty record for create/list; record-dependent predicates cannot stand in for per-record checks there. field() is not an allowed Permission function at all, even though older prose discussed its absent-record result. inState is scope-permitted but needs the record. State functions inspect conventional status/state fields. canTransition needs an explicit transitions array; the current guard wrapper does not install that array or from metadata. Scope permission alone does not make it an authoritative transition check.

A custom field validator using $value >= 0 accepts the checked positive hours value. The otherwise identical $this.hours >= 0 variant fails the write. Do not copy a resource-rule expression into that narrower context without adapting its bindings.

Computed handler debt: the evaluator permits target functions in Computed scope, but ordinary computed fields supply neither domain resolution nor a query handler. A parsed formula using a quoted findOne target yields null through fallback in the checked read. The Phase-15 guide records this as Refactor-ComputedHandler; catalogue availability does not resolve that debt. Rules and other consumers must likewise be assessed at their own call sites.

18.5 Limits

The inherited chapter calls four limits universally enforced. Current engine defaults and the checked boundaries are more precise:

BoundaryDefault and observed behavior
Expression source size4,096 UTF-8 bytes; 4,096 passes, 4,097 fails with 1108
Evaluated AST depth32; a chain of 32 unary negations passes, 33 fails with 1107
Higher-order array size10,000 elements per call; 10,001 fails with 1104 before short-circuit evaluation
Compiled-expression cache512 entries; bounded cache, clear, and disabled-cache controls checked

The public AelEngineOptions exposes all four values. This does not imply that every YAML consumer exposes a configuration key for them. Forty pairs of parentheses pass the native engine: grouping itself is not an evaluated AST node. The inherited “call and nesting depth” wording therefore overstates what the current limit bounds. Multibyte strings consume more than one byte per character; 2,047 é characters plus quotes use 4,096 bytes.

The cache implementation uses LRU eviction. This chapter executes capacity, repeat, clear, and disable controls; it does not claim a concurrency or performance benchmark. Target aggregation does not use the higher-order array cap: a fixture handler returning 10,001 rows is counted as 10,001.

18.5.1 The current host query cap changes aggregate results

AEL delegates data access to a host callback. The current shared ADL query handler issues equality-filtered reads with LIMIT 1000 and no ordering clause. Target aggregate conditions are evaluated after those rows are fetched.

Observed limitation: the disposable suite contains 1,001 matching rows, each with one hour. A validation rule summing that target admits an invoice with budget 1,000, because only 1,000 rows reach the expression. A direct SQL control confirms 1,001 stored hours. A true predicate is therefore not proof of a complete cross-record invariant at this host boundary.

Since kalos_adl 0.120.0 (#1372 B1) the five target aggregates are answered by the store over every row when the condition is one of: text or key equality, in with a list of strings, integer equality, number ordering, boolean equality, date comparison with a YYYY-MM-DD value, a test against null, or these joined by &&, || and !. The limitation above then no longer applies: the same suite refuses the invoice. Any other condition (decimal or money equality, text ordering, a function call on a column) keeps the capped row path. Declare an index on the condition’s columns; the total is computed on every write that fires the rule.

Account for the host cap when designing query-backed validation. This chapter provides no paging syntax, complete-scan guarantee, query timeout guarantee, or concurrent-write serialization contract. findOne and lookup also have no stable “first” row when several rows qualify. These limitations belong alongside the query examples, not just in an operational footnote.

18.6 Failure

Separate expression parsing, static target validation, function-scope checking, and runtime evaluation. A document being admitted does not establish that each embedded expression can run.

Stage/controlChecked outcome
Engine compile of hours +Syntax error 1101
Document validation rule hours +Document admitted; first create fails validation
Document validation rule with old three-argument target aggregateRejected with AEL_AGGREGATE_ARITY and the owning rule path
Permission exists('Entry', {})Rejected at document parse with scope error 1105
Unknown function in a validation or permission expressionSyntax/static validation may pass; invoking it fails
Target function in a Permission engine contextRegistry-only context check passes; evaluator rejects with 1105
Quoted pinned targetStatic validation passes; target evaluation rejects with 1111
Quoted target in an ordinary computed formulaDocument admitted; read falls back to null

The parser’s AEL post-pass rejects selected target/address diagnostic codes. It retains ordinary syntax errors for runtime handling and excludes computed formula fields from that walk. compile() itself parses syntax; it is not the full validate() target check. The inherited promise that all malformed or out-of-scope expressions fail on submission is not supported.

18.6.1 Engine diagnostics and consumer responses

Engine codeMeaningRepresentative checked trigger
1101Syntax errorIncomplete binary expression
1102Type errorInvalid arithmetic conversion or array aggregate input
1103Reference/function errornotAFunction()
1104Runtime errorDivision by zero, array limit, callback failure
1105Security/scope errorDisallowed function or missing query handler
1107Depth exceededEvaluated unary chain beyond the configured depth
1108Expression too longSource byte length beyond the configured limit
1109AEL_UNRESOLVED_NAMELocal target absent from context, record fields, and current domain
1110AEL_AGGREGATE_ARITYLegacy aggregate shape or wrong target kind
1111AEL_ADDRESS_INVALIDMalformed, non-resource/non-field, or unsupported pinned target
1112AEL_TARGET_UNAVAILABLEActive-target/import resolution fails in the host

1106 has no named helper in the reviewed error header. The four target errors carry their uppercase name as the leading message token. Resource operations may wrap those errors rather than expose the numeric engine code as their top-level API code. ADL 31 owns the complete error contract.

ConsumerChecked request consequence
Resource validation422 VALIDATION_ERROR; false rule uses validation_rule, evaluation failure uses expression_error in rule details; no row written
Permission403 FORBIDDEN for an unknown function, a bare absent field comparison, or an unusable target
Transition guard403 GUARD_FAILED for malformed syntax or disallowed query; transition refused
Computed fieldRead remains 200; lightweight fallback may return a value or null

Computed fallback is not synonymous with null: coalesce(null, 7) produces 7, 1 / 0 produces 0, and an unknown function or unavailable target produces null in the checked computed host. These silent results differ from the standalone AEL failures.

The guard wrapper has another observed discrepancy: [] approves a transition, although the AEL engine’s truth test says an empty array is false. Use explicit boolean conditions and retain this as an implementation defect; the result does not redefine AEL truthiness. Callback/store failure in validation remains an expression error, not an empty query result: dropping the target table causes the next invoice create to fail.

18.7 Resource targets and aggregate overloads

ADL 7 owns address grammar and pins; ADL 8 owns import declarations. AEL consumes their identities; it does not add network locations or relationship traversal to ordinary member access.

18.7.1 Quote an address; leave a local name bare

Draft 05 §14 distinguishes a literal quoted address from a context variable or local resource name. These are expression fragments:

sum(items)
sum(Entry.hours, employee == $record.employee)
sum('adl.workshop.times.Entry.hours', employee == $record.employee)
count('adl.workshop.times.Entry', hours > 0)

For an unquoted local target, resolution tries the context variable, then a field of the current record, then a resource in the current domain, and stops. It never scans other active domains for a matching bare name. A context Entry = [9,1] makes sum(Entry) a value aggregate returning 10 without a query. A record field Entry = [2,3] similarly yields 5. An explicitly null context binding still shadows the resource and causes the array operation to fail; it does not fall through to resource lookup.

Current local resource matching is case-insensitive. Use the declared spelling for clarity. A missing Ghost target raises AEL_UNRESOLVED_NAME before the handler is called.

The target-taking aggregate/finder dispatcher recognizes a literal quoted full address. count('Entry') is not the bare-resource form and fails with AEL_ADDRESS_INVALID. count(adl.workshop.times.Entry) is ordinary chained member evaluation, not a quoted target. Assigning an address string to a variable likewise does not turn count(address) into a target operation.

Compatibility exception: query and exists are registered functions that receive evaluated string arguments. They retain quoted local-name support, such as query('Entry', {employee: 'alice'}), resolving only in the current domain. They also accept a variable holding a full address string. Do not generalize that exception to aggregate or finder syntax.

18.7.2 Fold the field into the target

FormTarget kindResult when nothing matches
count(resource[, condition])Resource0
sum(resource.field[, condition])Field0
avg(resource.field[, condition])Fieldnull
min(resource.field[, condition])Fieldnull
max(resource.field[, condition])Fieldnull

Replace the old three-argument form sum(Entry, 'hours', employee == 'alice') with sum(Entry.hours, employee == 'alice'). For another domain, quote the full field address. The old form is rejected with AEL_AGGREGATE_ARITY. sum('adl.workshop.times.Entry') has the wrong target kind, as does count('adl.workshop.times.Entry.hours').

The optional condition is evaluated against each fetched row. Its child context rebinds $this to that row while retaining $record as the outer validated candidate. Thus employee == $record.employee compares a queried row’s employee with the new invoice’s employee. Use the explicit outer binding when names overlap.

Name-precedence limit: inherited explicit context variables remain ahead of row-field fallback. An outer variable named employee shadows the fetched row’s bare employee; the checked filter then counts zero instead of the two Alice rows. Within a predicate, $this.employee avoids that ambiguity.

The target numeric fold accepts numbers, booleans, and numeric string prefixes; it ignores missing/null and unusable values. In the checked handler fixture, '12x', '5.5', true, 'bad', and null sum to 18.5. This permissive implementation is not the strict array-aggregate contract. Store proper numeric data rather than depending on its prefix conversion.

18.7.3 Host access and availability

Target aggregates and finders need an installed query handler in Validation or Computed scope. query(resourceString, filterObject) returns the matching array and exists(resourceString, filterObject) tests whether any row exists; both are Validation-only. An allowed scope with no handler still fails.

The checked shared handler resolves the current domain or an active registry domain and uses its physical table/column facts. Sibling domains in a suite work in the executed billing example. A target in another suite needs the current Phase-16 import read grant: merely activating both domains does not authorize the query. The unimported cross-suite control fails with AEL_TARGET_UNAVAILABLE.

Current runtime targets must be unpinned; a syntactically valid address pin passes static validation but is refused during evaluation. This is an explicit implementation limitation, not removal of pin syntax from ADL 7.

AEL does not fetch external documents, traverse remote sites, or grant write authority through a query expression. The host’s equality filter and 1,000-row cap apply before a target aggregate’s AEL condition. The chapter’s handler evidence does not establish that resource permissions, named scopes, or relationship-include filters are applied to these internal reads.

18.8 The four additive functions

The current native union includes all four Draft 05 additions. Three are target intrinsics; networkdays is registered in the date library. The Python modeller at this revision reports 1103 for all four; its rejection is a tool coverage limit, not evidence that the native implementation lacks them.

18.8.1 findOne and findMany

findOne('adl.workshop.times.Entry', employee == 'alice')
findMany('adl.workshop.times.Entry', hours > 2)

Both accept a resource target and optional row condition, with the same resolution, scope, bindings, and handler constraints as count. findOne returns the first matching row or null; findMany returns all matching fetched rows or []. “All” is bounded by the host’s fetched set. There is no ordering argument, and the native shared query has no ORDER BY. Neither operation enforces uniqueness or expands relationships.

18.8.2 lookup

lookup('adl.workshop.times.Entry.code', 'B')
lookup('adl.workshop.times.Entry.code', 'B', 'hours')

The first argument is a field target: the lookup key. The second is the value to match. The optional third argument is a field-name string to project from the first returned row. The examples return row 2 and 6, respectively.

The dispatcher sends {code: 'B'} to the handler as an equality filter; it does not scan every row with a lambda. No matching row, or a missing projected field, yields null. Multiple matches use the handler’s first row without a uniqueness check. A nonarray callback result also currently becomes null for lookup, while count reports an error for the same malformed callback shape; this is a retained implementation inconsistency.

18.8.3 networkdays

networkdays('2026-09-07', '2026-09-11')
networkdays('2026-09-07', '2026-09-11', ['2026-09-09'])

networkdays(start, end[, holidays]) counts Monday–Friday dates inclusively at both ends, excluding holiday dates. The examples yield 5 and 4. Reversing the endpoints gives a signed negative count: Friday through Monday in the reversed example returns -5. A weekend-only interval returns 0.

It is available in all four scopes and needs no query handler. Invalid endpoints yield null. Duplicate holiday dates count once; malformed holiday entries are ignored. A nonarray third argument is currently ignored entirely: the single string '2026-09-09' gives 5, not 4. Supply an array of valid date strings rather than relying on that permissive behavior. Business hours, regional holiday calendars, and alternative weekend definitions are not parameters of this function.

18.9 Complete examples and verification

The following is the complete checked worklog.yaml. Its inherited grammar uses adl: "0.5.0"; domain version and language version remain separate strings.

adl: "0.5.0"
domain:
  name: worklog
  version: "1.0.0"
  resources:
    Entry:
      object:
        id:
          type: integer
          primaryKey: true
        employee:
          type: string
        hours:
          type: decimal
        rate:
          type: decimal
        status:
          type: string
          default: draft
      computed:
        total:
          type: decimal
          formula: round(hours * rate, 2)
      validation:
        hoursInRange:
          rule: hours >= 0 && hours <= 24
          message: Hours must be between 0 and 24
      stateMachine:
        field: status
        initial: draft
        states:
          draft:
            transitions:
              approve:
                to: approved
                guard: hours > 0 && hasRole('reviewer')
          approved: {}
      permissions:
        create:
        - '*'
        read:
        - '*'
        update:
        - '*'
        delete:
        - '*'
        get: hasRole('reviewer') || record.hours <= 8

The disposable request sequence submits the definition, creates a four-hour entry at rate 25, and reads total: 100. A 30-hour create fails validation. An author cannot approve the entry; a reviewer can, and the stored status becomes approved. These are actual AppContext actions with synthetic caller metadata, not an HTTP/authentication integration test. Broad fixture permissions exist to isolate the expressions and are not an authorization template.

For cross-domain validation, the complete workshop suite uses the times member and the billing member. The suite declares adl: "0.5.1"; its member documents inherit that context. The billing rule is the following fragment:

withinBudget:
  rule: sum('adl.workshop.times.Entry.hours', employee == $record.employee) <= budget
  message: Submitted budget is below recorded hours

With stored hours 4 and 6 for Alice and 2 for Bob, Alice’s budget 8 fails, Alice’s budget 12 passes, and Bob’s budget 3 passes. A separate 1,001-row control demonstrates the cap limitation in §18.5.1. Deliberate rejection and deferred-failure YAML inputs are listed in the examples directory; they are not accepted-grammar examples.

From the clone-b repository root, reproduce the documented artifact pairing with the existing compiler dependencies and Python/modeller environment:

python3 docs/adl-v0.5.1-vol-1-adl/examples/18-ael/verify.py --build-root ../kalos-clone-a/build

The script checks the ADL library hash, uses compatible archived c8cd9d7c headers, compiles only the documentation adapter, and writes results to a new temporary directory. It does not rebuild production artifacts or mutate an existing application store. A changed library requires reviewing the header/artifact pairing before updating the guard.

The verification record contains 268 adapter cases, 587 assertions, 245 independent modeller projections, twelve CLI/modeller commands, and 231 passing focused tests. It also preserves all request inputs, callback calls, errors, outputs, hashes, and source provenance. The full 111-name catalog is generated from these observations.

The baseline document passes native CLI and modeller checks. Their results diverge for deferred validation syntax, permission queries, and computed targets. The single-document CLI cannot load suite members at its validation entry point; the adapter supplies and executes them. The modeller accepts the suite while warning about unknown keys and does not resolve its members. Modeller acceptance, syntax acceptance, and host enforcement remain independent evidence layers throughout this chapter.

End of Chapter 18.