AWorld Lab
English
  • English
  • Italiano
About
API ReferenceAWorld.orgAWorld Trust
About
API ReferenceAWorld.orgAWorld Trust
AWorld.org
English
  • English
  • Italiano
English
  • English
  • Italiano
  1. Domain Deep-Dives
  • Gamification Fundamentals
    • Engagement for Businesses and Organizations
    • API-first for Gamification
    • Activities, Learning, and Content
    • Missions, Rewards, and Progression
    • Leaderboards and Social Mechanics
  • Engagement Scenarios
    • Employee Engagement and Training
    • Customer Loyalty Program
    • Education Platform
    • Community and App Engagement
  • Domain Deep-Dives
    • Mission Domain
    • Learning Content Domain
    • Reward and Currency Domain
    • Badge Domain
    • Leaderboard Domain
    • Streak Domain
    • Cross-Cutting Patterns
  • Infrastructure & Security
    • Cloud Infrastructure and Architecture
    • Security and Cybersecurity
    • Compliance and Certifications
    • Disaster Recovery and Business Continuity
    • Performance and Scalability
    • Access Methods and Integration
    • Technical Glossary
  1. Domain Deep-Dives

Cross-Cutting Patterns

AWorld Lab's domain services share a set of architectural patterns that recur across missions, streaks, learning paths, rewards, and leaderboards. This document describes each pattern once so that the domain-specific deep-dives can reference it rather than repeat it.

JsonLogic Expression System#

Several fields across the platform accept JsonLogic expressions — JSON-encoded rules that are evaluated at runtime against a context object. This allows clients to define complex conditions, calculations, and filters through configuration alone.

How It Works#

A JsonLogic expression is a JSON object where keys are operators and values are arguments. The platform evaluates the expression against a context object that contains the relevant data for that evaluation point.
// "Is the event's progress equal to COMPLETE?"
{ "===": [{ "var": "event.progress" }, "COMPLETE"] }

// "Award 20 points for HARD quizzes, 10 for MEDIUM, 5 for EASY"
{
  "if": [
    { "===": [{ "var": "event.difficulty" }, "HARD"] }, 20,
    { "===": [{ "var": "event.difficulty" }, "MEDIUM"] }, 10,
    5
  ]
}

// Compound condition
{
  "and": [
    { "===": [{ "var": "event.progress" }, "COMPLETE"] },
    { "===": [{ "var": "event.outcome" }, "SUCCESS"] }
  ]
}
The platform extends the standard JsonLogic library with Math operations (sqrt, pow, min, max, etc.) and Date access.

Where It Is Used#

DomainExpression FieldContext ObjectPurpose
MissionConfigurationmatchCondition{ mission }Filter which events count toward progress
MissionConfigurationincrementExpression{ user, event }Calculate how much progress each event adds
MissionConfigurationtargetAmountExpression{ user, mission }Calculate the completion target
MissionRuleusersMatchCondition{ user }Determine which users are eligible
MissionRulemissionsMatchCondition{ mission }Filter which configurations to instantiate
MissionRuleeventMatchConditionevent dataFilter which events trigger assignment (EVENT mode)
StreakConfigurationmatchCondition{ event }Determine if an event counts toward a streak
StreakRuleusersMatchCondition{ user }Determine which users this rule applies to
StreakRulefreezeCostExpression{ user, streak }Calculate the virtual currency cost to freeze
LearningPathRuleusersMatchCondition{ user, activeAssignments }Determine user eligibility
LearningPathRulelearningPathsMatchCondition{ user, learningPath }Filter which paths to assign
LearningPathRuleinitialVisibilityCondition{ learningPath, index, user }Determine LOCKED or UNLOCKED per path
LearningPathRuleeventMatchConditionevent dataFilter which events trigger UNLOCK
RewardRulematchCondition{ event, previousEvent }Determine if an event qualifies for a reward
RewardRulereward expression{ event }Calculate the reward amount

Important Behaviors#

A static value (e.g., true, 100) is a valid expression — it always returns that value.
Missing fields in the context return null. Expressions should handle this gracefully.
Numeric results are force-cast to numbers; negative values in cost expressions are automatically inverted to ensure a positive cost.
Expressions are stored as opaque JSON — the platform validates JSON syntax but does not validate expression semantics at write time.

Configuration → Rule → Instance Pattern#

Three major domains follow a three-layer hierarchy where a Configuration defines what to track, a Rule defines when and for whom, and an Instance tracks per-user state:
Configuration  (what counts)
      │
      └──▶ Rule  (the rules of the game: who, when, how)
              │
              └──▶ Instance  (per-user or per-group tracking record)
LayerMission DomainStreak DomainLearning Path Domain
ConfigurationMissionConfigurationStreakConfiguration(embedded in LearningPath)
RuleMissionRuleStreakRuleLearningPathRule
InstanceMissionStreakLearningPathAssignment
LogMissionLogStreakLogLearningPathLog
Each layer has its own lifecycle, and changes at the Configuration or Rule level do not retroactively alter existing Instances — they only affect future assignments.

Entity Matching Pattern#

Multiple services use a consistent three-mode matching system to determine which entities are relevant to a rule or configuration:

Match Types#

Match TypeBehaviormatchEntityId Required
INSTANCEMatches a specific entity by ID. Example: completing activity abc123.Yes
ENTITYMatches any entity of the given type. Example: completing any quiz.No
TAGMatches any entity tagged with the given tag. Example: any activity tagged christmas.Yes (the tag ID)

Match Entities by Domain#

DomainAvailable Match Entities
MissionConfigurationActivity, Quiz, Tag
StreakConfigurationMission, Activity, Quiz, Tag
RewardRuleMission, Activity, Quiz, Tag, LearningPath, LearningGroup, Slide
Constraint: When matchType is INSTANCE or TAG, the matchEntityId field is required. When matchType is ENTITY, matchEntityId must be absent.
The TAG match type is particularly powerful — by combining it with a matchCondition JsonLogic expression, you can create highly targeted rules like "only activities tagged christmas that were completed in December".

Timeframe and Scheduling#

Rules and runtime instances share a common timeframe model that controls when they are active.

Timeframe Types#

TypeBehaviortimeframeEndsAt
PERMANENTStarts at timeframeStartsAt, runs indefinitelyNot required
RANGEActive between timeframeStartsAt and timeframeEndsAt, onceRequired
RECURRINGRepeats at a defined cadence between start and end datesRequired

Recurrence#

When timeframeType is RECURRING, the recurrence field defines the reset cadence:
RecurrenceBehavior
DAILYResets every day
WEEKLYResets every week
MONTHLYResets every month
CUSTOMResets according to a cron expression (scheduleCron)
Constraint: scheduleCron is only required when recurrence is CUSTOM. The cron expression uses the standard IANA format.

Timezone Handling#

Timezone TypeBehaviortimeframeTimezone
FIXEDAll users experience transitions at the same absolute timeRequired (IANA timezone, e.g., "Europe/Rome")
USEREach user's transitions are relative to their local timezoneNot required
USER timezone is ideal for daily/weekly rules where fairness requires each user to have the same local boundaries. FIXED timezone is appropriate for global events that must start and end simultaneously for everyone.

Services Using This Pattern#

MissionRule, StreakRule, LearningPathRule, RuntimeLeaderboard — all use the same field names and the same set of valid values.

State Lifecycle#

Entities with a timeframe follow a consistent three-state lifecycle:
              time passes
                 │
    ┌────────────▼────────────┐
    │         PENDING         │  ◀── before timeframeStartsAt
    └────────────┬────────────┘
                 │ timeframeStartsAt reached
                 ▼
    ┌────────────────────────┐
    │         ACTIVE          │  ◀── between start and end
    └────────────┬────────────┘
                 │ timeframeEndsAt reached (not for PERMANENT)
                 ▼
    ┌────────────────────────┐
    │          ENDED          │  ◀── after timeframeEndsAt
    └─────────────────────────┘
PENDING: The entity exists but is not yet operational. It was created ahead of its start time.
ACTIVE: The entity is operational and accepting interactions.
ENDED: The entity's timeframe has passed. Terminal state.
Note: PERMANENT entities never reach ENDED — they remain ACTIVE indefinitely once started.
State transitions are managed by scheduled processes that periodically evaluate each entity's timeframe and update the state accordingly. The calculation is deterministic: given the current time and the timeframe fields, the state can always be derived.

Multi-Language and Localization#

All content-bearing entities support multiple languages through a consistent pattern.

Language Fields on the Main Entity#

FieldTypeDescription
defaultLanglanguage codeThe primary language for this entity
langslanguage code[]All supported languages (1 to 10)

Translation Entities#

Translatable content is stored in separate Translation entities rather than embedded in the main entity. Each translation is keyed by the parent entity's ID plus a lang field.
LearningPath (defaultLang: "en", langs: ["en", "it", "fr"])
      │
      ├── LearningPathTranslation (lang: "en", title: "Onboarding", description: "...")
      ├── LearningPathTranslation (lang: "it", title: "Onboarding", description: "...")
      └── LearningPathTranslation (lang: "fr", title: "Intégration", description: "...")
Typical translatable fields include title, description, and image (for language-specific imagery). Each domain defines its own set of translatable fields.

Translation History#

Configuration entities that support audit trails also maintain TranslationHistory records, providing full versioning of translated content.

Services Using This Pattern#

MissionConfiguration, MissionRule, StreakConfiguration, StreakRule, RewardRule, LearningPath, LearningGroup, Quiz, Slide, Activity, VirtualCurrency, RuntimeLeaderboardConfiguration.

Origin and Catalog Sync#

Content and configuration entities track their origin — whether they were created from a catalog template, generated by AI, or defined custom by the client.

Origin Values#

OriginDescription
CATALOGCreated from a pre-built template in the catalog workspace
CUSTOMCreated from scratch by the client
AIGenerated by AI content creation (Learning Paths and Learning Groups only)

Catalog Reference Fields#

When origin is CATALOG, the entity stores a reference back to its catalog source:
Field PatternExample
catalog<Entity>IdcatalogMissionRuleId, learningPathCatalogId, catalogRewardRuleId
syncWithCatalogBoolean — whether to keep the entity in sync with future catalog updates
Constraint: When origin is CATALOG, the catalog reference ID should be set. When origin is CUSTOM, it should be absent.

Services Using This Pattern#

MissionConfiguration, MissionRule, StreakConfiguration, StreakRule, RewardRule, LearningPath, LearningGroup, Quiz, Slide, Activity, VirtualCurrency.

Tag System#

Tags are a foundational cross-cutting mechanism used for categorization, targeting, and segmentation across the entire platform.

Tag Structure#

Each tag is defined by a namespace and variant:
Namespace: the category (e.g., department, region, tier)
Variant: the specific value (e.g., marketing, europe, gold)

Tag Assignments#

Tags can be assigned to virtually any entity — users, activities, quizzes, learning paths, learning groups, slides, mission configurations, mission rules, streak configurations, and streak rules. Each assignment includes a priority value for ordering.

Tags in the Rule Engine#

Tags serve three critical roles in the platform's rule systems:
1.
Entity matching: Rules with matchType: TAG target all entities associated with a specific tag, enabling thematic grouping (e.g., all activities tagged christmas).
2.
User segmentation: usersMatchCondition expressions can reference user tags to target specific user groups.
3.
Group targeting: Group missions and community leaderboards are scoped by tag, enabling team-based and segment-based experiences.

Summary#

PatternPurposeUsed By
JsonLogicDeclarative conditions and calculationsAll rule and configuration entities
Config → Rule → InstanceHierarchical domain modelingMission, Streak, LearningPath
Entity MatchingFlexible event targeting (INSTANCE/ENTITY/TAG)MissionConfig, StreakConfig, RewardRule
Timeframe & SchedulingTemporal boundaries and recurrenceMissionRule, StreakRule, LPRule, Leaderboard
State LifecyclePENDING → ACTIVE → ENDEDAll rule and instance entities
Multi-LanguageLocalized content via Translation entitiesAll content-bearing entities
Origin & CatalogTemplate sourcing and syncAll configuration entities
Tag SystemCategorization, targeting, segmentationCross-cutting across all domains
Modified at 2026-02-24 15:02:19
Previous
Streak Domain
Next
Cloud Infrastructure and Architecture
Built with