Context-Oriented Behavioral Programming

Modern systems require programmers to develop code that dynamically adapts to different contexts, leading to the evolution of new context-oriented programming languages. These languages introduce new software-engineering challenges, such as: how to maintain and keep the separation of concerns of the codebase? how to model the changing behaviors? how to verify the system behavior? and more. This paper introduces Context-Oriented Behavioral Programming(COBP) - a novel paradigm for developing context-aware systems, centered on natural and incremental specification of context-dependent behaviors. As the name suggests, we combine behavioral-programming(BP) - a scenario-based modeling paradigm - with context idioms that explicitly specify when scenarios are relevant and what information they need. The core idea is to connect the behavioral model with a data model that represents the context, allowing an intuitive connection between the models via update and select queries. Combining behavioral-programming with context-oriented programming brings the best of the two worlds, solving issues that arise when using each of the approaches in separation. We begin with providing abstract semantics for COBP, laying the foundations for applying reasoning algorithms to context-aware behavioral programs. We then exemplify the semantics with formal specifications of systems, including a variant of Conway's Game of Life. Finally, we present a JavaScript-based implementation of the paradigm and provide two case studies of real-life context-aware systems (one in robotics and another in IoT) that were developed using this tool. Throughout the examples and case studies, we provide design patterns and a methodology for coping with the above challenges.


Introduction
Requirements of context-aware system are often referring to the system context, either by subjecting a requirement to a specific context (e.g., "do not use the elevator during an emergency", "do not use the GPS when battery is low", etc.), or by specifying how the system should interact with the context (e.g., "change to emergency mode upon fire detection", etc.).This work formalizes and generalizes an approach for developing context-aware systems, by combining scenario-based programming with context.Specifically, we propose to add explicit idioms for referencing of context in behavioral programming, as elaborated next.
Behavioral Programming (BP) [21,22] is languageindependent paradigm for programming reactive systems, designed to allow for a natural and incremental specification of behavior.A behavioral program is comprised of a set of scenarios (that say what to do) and anti-scenarios (that say what not to do), that are interwoven to generate a combined reactive system.Each scenario and anti-scenario is specified as a sequential thread of execution that isolates a specific aspect of the system behavior, desirably an individual requirement.An application-agnostic execution mechanism repeatedly collects these scenarios, chooses actions that are consistent with all the scenarios, executes them, and continuously informs them of each selection.We elaborate on BP in Section 2.
In many cases, behaviors are bound to a context.In Chess for example, some behaviors are only relevant whenever there is a check.Behaviors may also interact with the context by querying or changing it.For example, a possible behavior in Chess would be to activate the check context whenever an opponent pieces is threatening the king.Specifying context-aware requirements (i.e., context-dependent requirements and requirements that change the system context) with b-threads -requires explicit, "first-class citizen" idioms for referencing and changing the system context -something that is not defined for BP.In [10] and [11], context idioms were proposed for two implementations of BP, in LSC and in JavaScript (respectively).Using the extended languages with first-class citizen context idioms, they demonstrated how the new idioms allow for a direct specification of context-aware requirements, resulting with a better alignment between the requirements and the specification.In both languages, the context idioms were defined as syntactic sugars to the original language idioms, and translational semantics were proposed for the new idioms.
In this paper, we generalize the approach of [10,11] and present Context-Oriented Behavioral Programming (COBP) -a novel, language-independent paradigm for developing context-aware systems, centered on natural and incremental specification of context-dependent behaviors.Specifically, we propose to add first-class citizen context idioms to BP and define new formal semantics for specifying the relation between the system context and the system behavior.One of the advantages of these formal semantics over the translational semantics of [10,11], is the ability to directly implement the paradigm in different programming languages, rather than relying on existing BP implementations and translating to them.Based on this ability, we also present a JavaScript-based implementation for the paradigm and provide two case-study systems that were developed with it (Sections 8 to 10).
Another approach for integrating context with programming, is the context-oriented programming (COP) paradigm [8].Over the last decade, COP has evolved in a variety of languages and approaches, starting from Costanza and Hirschfeld [8].While there are many variations in the way they handle the contextual data and the relevant behavioral variations, the layers is the most widespread model by far [32].Layers are a language abstraction, grouping definitions of partial methods that implement some fragment of an aspect of the system behavior [8].We compare some of the idioms of COP and COBP in Section 9.
Both in COP and COBP, the system may have two contradicting behaviors, as long as they are bound to different contexts.Consider for example conflicting requirements, overridden by the context, like "vacuum the carpet" and "do not vacuum while someone is asleep".Composing the contexts and the behaviors at runtime, may lead to unpredictable behavior.Thus, both context-oriented approaches require reasoning and formal verification techniques for verifying their software, i.e., that it will function correctly in all contexts and combinations thereof.Since reasoning algorithms depend on having a formal specification of the system, an effort has been made in developing formal semantics for COP (as elaborated in Section 11).For this reason, one of the major purposes of this paper is to generalize the work of [10,11], and define formal semantics for the COBP paradigm.As we demonstrate below, a COBP model that is based on these semantics, allows for applying reasoning techniques with no further input needed, as opposed to some COP implementations that require a manual translation of the code into a formal model.Furthermore, one of the key advantages of scenario-based programming (SBP) [9] in general, and of BP in particular, is the amenability of the software artifacts to formal analysis and synthesis.As we elaborate in Section 11, most of the tools for BP and SBP rely on the mathematically rigorous nature of the semantics in providing tools for running formal analysis and synthesis algorithms.The addition of context improves the modularity of the specification, thus may contribute each of the methods.However, it requires to adapt these approaches, since they are all designed under the assumption that the only protocol between the b-threads is requests, blocking, and triggering of events.Therefore, the formal semantics presented here lay the foundations towards such adaptations.
Outline.Section 2 elaborates on the behavioral programming paradigm and describes its shortcoming when it comes to handling the system context.Section 3 formally defines COBP, giving abstract semantics for the language.Sections 4 to 6 demonstrate how the abstract semantics can be used for formally specifying context-aware systems.In sections 8 to 10 we present a JavaScript-based implementation for COBP and provide two case studies of context-aware systems that were programmed using this implementation.Finally, in Section 11 we discuss reasoning approaches for COP and BP, as well as other approaches for integrating context with modeling and programming.

The Context of this Paper -Behavioral Programming
When creating a system using BP, developers specify a set of scenarios that may, must, or must not happen.Each scenario is a simple sequential thread of execution and is thus called a b-thread.B-threads are normally aligned with system requirements, such as "stop moving" or "turn to target".
The set of b-threads in a model is called a behavioral program (b-program).During run-time, all b-threads participating in a b-program are combined, yielding a complex behavior that is consistent with all said b-threads.As we elaborate below, unlike other paradigms, such as functional programming or object-oriented programming, BP does not force developers to pick a single behavior for the system to use.Rather, the system is allowed to choose any compliant behavior.This allows the run-time to optimize program execution at any given moment, e.g., based on available resources.The fact that all possible system behaviors comply with the b-threads (and thus with the system

Otherwise
Otherwise Otherwise requirements), ensures that whichever behavior is chosen, the system will perform as specified.

Cold Cold Cold
To make these concepts more concrete, we now turn to a tutorial example of a simple b-program, first presented in [22].All of the examples in this paper are specified formally, based on the transition systems that we define in Section 3. JavaScript-based programs are presented in sections 8 to 10.
Consider a system that controls taps of hot and cold water, whose output flows are mixed, with the following requirements: 1.When the system loads, pour some small amount of cold water three times.
2. When the system loads, pour some small amount of hot water three times.
Figure 1 shows a b-program that fulfills these requirements.
It consists of two b-threads, added at the program start-up.The first is responsible for fulfilling requirement #1, and the second fulfills requirement #2.The program's structure is aligned with the system requirements, with a single b-thread for each requirement, requesting, and blocking events at each of their state (the R and B sets).Harel, Marron and Weiss [21] proposed a simple protocol for interweaving the b-threads and executing the model, depicted in Figure 2. B-threads repeatedly execute an internal logic and then synchronize with each other, by submitting a synchronization statement to a central event arbiter.Once all b-threads have submitted their statements, the central event arbiter selects an event that was requested and was not blocked.B-threads that either requested or waited for this event (specified on the edges in our hot-cold example) are resumed, while the rest of the b-threads remain paused for the next cycle.Back to our example, this specification does not dictate the order in which actions are performed since the b-threads do not block events of each other.Thus, any of the following runs are possible: Cold-Cold-Hot-Hot-Cold-Hot, or Cold-Hot-Cold-Hot-Cold-Hot, etc.This contrast with, say,  [22]).B-threads repeatedly execute an internal logic and then synchronize with each other, by submitting a synchronization statement to a central event arbiter.Once all b-threads have submitted their statements, the central event arbiter selects an event that was requested and was not blocked.B-threads that either requested or waited for this event are resumed, while the rest remain paused for the next cycle.
imperative programming languages (e.g., Java, C) that would have to dictate exactly when each action should be performed.Thus, traditional programming paradigms are prone to over specification, while behavioral programming avoids it.
While a specific order of actions was not required originally, in some cases, this behavior may represent a problem.Consider for example an additional requirement that the client requested after running the initial version of the system: 3. Two actions of the same type cannot be executed consecutively.
While we may add a condition before requesting 'Cold' and 'Hot', the BP paradigm encourages us to add a new b-

Cold Hot
Figure 3: A b-thread that ensures that two actions of the same type cannot be executed consecutively, by blocking and additional request of 'Cold' until the 'Hot' is performed, and vice-versa.
thread for each new requirement.Thus we add a b-thread, called Interleave, presented in Figure 3.
The Interleave b-thread ensures that there are no repetitions.It does so by forcing an interleaved execution of the performed actions -'Hot' is blocked until 'Cold' is executed, and then 'Cold' is blocked until 'Hot' is executed.Note that this b-thread can be added and removed without affecting other b-threads.This is an example of a purely additive change, where the system behavior is altered to match a new requirement without affecting the existing behaviors.While not all changes to a b-program are purely additive, many useful changes are, as demonstrated in [21].

The Absence of Context in BP
In this paper, the term context refers to information that can be used to characterize the situation of entities or processes in a system.The term 'context awareness' refers to the system's ability to use context information [1].Examples for context-aware systems are, e.g., adaptive system, ubiquitous systems, and mobile systems, as they all require the ability to change behavior with respect to context.
Consider for instance, a context-aware version of the above hot-cold example, where we have a building with many rooms and taps, and context-dependent requirements define that the system must behave differently, depending on the context, e.g., the type of the room, the person who uses the sink, etc.While it is possible to express all these aspects without explicit reference to context, we will show that direct idioms for working with context allow to reuse the scenarios and to make them more intuitive and aligned with how requirements are defined (which was the main design goal for BP).
All the implementations of BP that we are aware of, do not support direct communication between b-threads (with an exception of LSC that we discuss in Section 11).On the contrary, as elaborated in Section 3.1, the formal semantics of BP define that the only data shared among the b-threads -are the events.Yet, sharing the system context among the b-threads, overrides this definition.Thus, in practice, describing context-aware systems using BP forces the programmer to use some "hacks", such as sharing data using global variables, which violates the formal definition and breaks the ability to formally verify the programs.Another "hack" is to send the entire system context embedded in each event, making a lot of redundant code, and breaking the alignment between the b-threads and the requirements.

Context-Oriented Behavioral Programming
To address this problem, we present Context-Oriented Behavioral Programming (COBP) -an extension to the behavioral-programming paradigm with idioms for explicitly defining contexts and referencing them.As previously noted, this approach was first presented in [10], where the Live Sequence Charts (LSC) language was extended with context idioms, along with a methodology for developing context-aware systems using the extended language.In [11], a similar extension has been made to BPjs -an environment for running behavioral programs written in JavaScript [5].In both cases, the semantics of the languages were defined by translating the context idioms to the existing idioms of LSC and BPjs.In this paper we generalize these extended languages, by defining abstract semantics (rather than translational semantics) and lay the foundations for further research on formal analysis and synthesis.
In COBP, the system state incorporates the context of the system that can be queried and updated.For example, in the context-aware version of the hot-cold system, we may define the context to be the entire building, including the rooms, the taps, the amount of hot/cold units that need to be poured, and any additional required data.We will also define queries on the context such as room with taps and kitchen, that return a list of all rooms with taps and of all kitchens, respectively.A b-thread in COBP is a context-aware b-thread, also called CBT, that is bound to a certain query on the context.Whenever there is a new result to the query, a new 'live copy' of the CBT is spawned, with the query result given as a local variable to the live copy.Thus, we refer to this result as the 'seed' of the live copy.The CBT specifies a behavior that depends on this seed, allowing to use its data and to query and update the context.Back to our extended hot-cold system, we can convert the original three b-threads into CBTs and bind them to the appropriate query (i.e., room with taps).Thus, in a sense this query is not only the context of the requirements, but also the context of these b-threads.The complete example of the extended hot-cold system is given in Section 5.
We now turn to define the abstract semantics of COBP.Since our semantics extend the BP semantics, we begin with recalling the abstract semantics of BP, as defined by [21].

BP Semantics
The definition outline of the BP semantics is as follows: The definition of a labeled transition system (LTS) is given in Definition 1.In Definition 2, b-thread is defined as a labeled transition system in which events in each state can be marked as requested or as blocked.Finally, Definition 3, defines the two basic rules for executing a set of b-threads: (1) An event occurs if and only if it is requested by some b-thread and is not blocked by any b-thread; (2) All bthreads affected by a given event undergo a state transition when the event occurs.
Definition 1 (labeled transition system [26]).A labeled transition system is a quadruple S, E, →, init , where S is a set of states, E is a set of events, → is a subset of S × E × S called a transition relation, and init ∈ S is an initial state.The runs of such a transition system are sequences of the form s 0 , where s 0 = init, and for all i = 1, 2, • • • , s i ∈ S, e i ∈ E, and s i−1 , e i , s i ∈→ (this membership will, from now, be written as s i−1 ei − → s i for shortening and for simplifying the notions).

Definition 2 (behavior thread [21]
).A behavior thread (abbr.b-thread) is a tuple S, E, →, init, R, B , where S, E, →, init forms a labeled transition system, R : S → 2 E is a function that associates each state with the set of events requested by the b-thread when in that state, and B : S → 2 E is a function that associates each state with the set of events blocked by the b-thread when in that state.

Definition 3 (runs of a set of b-threads [21]). The runs of a set of b-threads
is defined as the runs of the labeled transition system S, E, →, init , where e is not blocked (1) and (2)

COBP Semantics
We begin with the definition of a context-aware behavioral program and continue with its execution semantics.In BP, the set of system events is defined as E = n i=1 E i , where E i is the set of events of the i-th b-thread.An alternative definition for E, is to define it globally, as a set of all events that the system may generate and use the same E for all b-threads.While both are semantically identical, we prefer the later since the events are system wide and they are shared among all b-threads (e.g., the same 'hot' event is used by two b-threads in the hot-cold example).

Context-Aware Behavioral Program
A context-aware behavioral program is composed of the context data structure with its management functions (Definitions 4 and 5), together with a set of context-aware b-threads (Definition 6).A context-aware b-thread (CBT) is a behavioral thread that is bound to a certain context (i.e., a query on the context).Our definition for context is inspired by the definition of [1] -information that can be used to characterize the situation of entities or processes in a system.Definition 4 (context, queries, and updates).CTX is a (possibly infinite) set of all possible contexts that the system is designed to be aware of.At any given moment the system is in a context ctx ∈ CTX .The management of the context is done by the sets QUERY and UPDATE, where each member query ∈ QUERY is a function with dom(query) = CTX and each member update ∈ UPDATE is a function from CTX to itself.Finally, ctx init denotes the initial context of the system.

Definition 5 (the effect function).
The connection between the events that the system generates and the updates of the context are defined by the function effect : E → UPDATE that maps events to context update functions.Definition 6 (a context-aware behavior thread (abbr.cbt)).A context-aware behavior thread over an eventset E is a tuple S, →, init, R, B, query , where S, E, → , init, R, B forms a behavior thread, and query ∈ QUERY is a query that the behavior thread is bound to.Here, → is a transition relation contained in S × CTX × range(query) × E × S, meaning that the transition of a contextual bthread may be conditioned on the last event, and also upon the context at the time of the transition and upon a query result.Similarly, R and B are redefined to be S × CTX × range(query) → 2 E .To simplify the notations, we define the functions init(cbt) = init, and query(cbt) = query.

Execution Semantics for A Context-Aware Behavioral Program
In BP, the b-threads are executed, however in COBP, CBTs are not directly executed.Whenever a context becomes active (i.e., there is a new result to the query) -a new live copy (Definition 7) of each of the CBTs that are bound to the context -are spawned, with the result of the query used as the seed of the live copy and passed to it as a local variable.The execution semantics of a context-aware behavioral program (Definition 8) define a new LTS, where its states are composed of the active live copies and the state of the system context.The transition function defines how events are selected, how the context is affected by the selected event, and how live copies are spawned based on changes of the system context.

Definition 7 (a live copy of a context-aware behavior thread). A live copy (instance) of a context-aware
behavior thread is a tuple cbt, s, c where cbt = S, E, →, init, R, B, query is a context-aware behavior thread, s ∈ S, and c ∈ range(query).We refer to c as the seed of the live copy.To simplify the notations, we extend the definition of R and B (see Definition 2) to accept a live copy: R( cbt, s, c ) = R(s) and B( cbt, s, c ) = B(s).

Definition 8 (runs of a set of context-aware b-threads).
The runs of a set of context-aware b-threads over an eventset E, and a cbt-set CBT , is defined as the runs of the LTS S, E, →, init , where: running live copies (based on transition systems) and spawned live copies (based on new query results) .

A Short Discussion
Compared to the BP semantics, these semantics embed the state of the context in the system state and extend the transitions function to support the new state.Since the semantics formally specify the entire system (i.e., context, behavior, and execution mechanism) -reasoning techniques can be applied on the complete system/model with no further input.Moreover, the formal semantics, allow for generating different perspectives of the model, such as: • Context-behavior perspective: Represents relations between contexts and behaviors, such as: "which behaviors are bound to a certain context", "affected by the termination of a certain context", etc.
• Behavior-context perspective: Represents how behaviors affect the context, e.g., which contexts queries can be affected by a certain CBT.
• Context-context perspective: Represents the relation between different contexts, such as: temporal (e.g., contexts day and night cannot be active simultaneously) and structural (e.g., the building context is composed of rooms, a kitchen instance is also a room instance, etc.).
These perspectives (and others), may ease the development process by improving the readability, explainability, and correctness of the model.
Another interesting feature of the semantics is the process of context activation, i.e., adding a result to a query and spawning live copies.We note that only UPDATE functions may change the context, and they are triggered only by the EFFECT function, that is triggered only upon selecting an event.Thus, while live copies are advanced simultaneously, only one UPDATE function can be triggered during a system transition.Changes to the context may yield new results for one or more QUERY functions and upon such a change, all the CBTs that are bound to these queries will spawn live copies simultaneously.For example, once a new room of type kitchen is added to the context (either dynamically using the effect function mechanism or statically by adding it to the initial context), all the CBTs that are bound to the room with taps context and kitchen context spawn live copies simultaneously.This behavior is desired, if there is no special requirement for an order.If there is such a requirement, then the BP and COBP paradigms encourage us to specify this additional requirement with an additional CBT (like the third, interleave b-thread of the hot-cold example).The implementation of the event selection mechanism, that continuously selects a requested and not blocked event, can be either naïve, i.e., select one randomly, or advanced, e.g., by using approaches as priorities, heuristics, reasoning, learning, etc. Again, this behavior is desired assuming that there is no special requirement for ordering the events.Of course, such a degree of parallelism may cause unpredictable behavior, and while the specification may be aligned to the requirements, there may be problems with the requirements themselves.In order to deal with this problem, different reasoning approaches have been proposed for BP, as we elaborate in Section 11.We further demonstrate the process of context activation in the following examples.

System Design
To increase the system modularity and its separation of concerns, we adapt the multilayered architectural pattern for developing COBP systems.We note that according to the above abstract semantics, the CBTs are unaware of the context schema, the UPDATE set, how each q ∈ QUERY is defined, and how the effect functions is defined.All this information is data-related aspects of the system, rather than behavioral.The only interface between the CBTs and the context is the queries' names and the contract of the effect function (i.e., what is the effect of each event).With respect to these insights, we define the layers as following: 1.The business-logic layer (BLL) is the behavioral specification -the set of CBTs that specify the behavior of the system (i.e., the b-program).When developing this layer, the programmer must be aware of which information is accessible from the context (i.e., the queries name and the structure of the result), and how the requested events may affect the environment.
2. The data-access layer (DAL) abstracts the contextrelated decisions for the BLL.The contextual data, as [10] proposed, is stored in a structured dataset (e.g., a relational database) and managed using a dataaccess layer (DAL).The DAL is defined by a "query and command repository" and an effect function.The "query and command repository" manages the contextual data using a high-level query language (e.g., SQL).The context's 'select' queries allow for triggering a stored procedure whenever a record is added or removed from its result (in analogy to "database views"), and the context's 'update' commands update the data as required (by adding, deleting, and changing objects and object relations).Based on the selected event, the effect function uses the 'update' commands for changing the context.To simplify the definitions, we assume that the effect function for all events is defined as the identity function (i.e., it does not change the context), unless explicitly defined otherwise.
3. The application (or service) layer defines the interaction between the BLL and the environment (e.g., a GUI, network messages, etc.).This interaction is already defined in BP by using a publish-subscribe mechanism, where environmental events (or external events) are selected only at a super step, i.e., when there are no more internal events to select.Similarly, the environment may listen to internal events and act upon them (e.g., trigger actuators).
The multilayered architecture facilitates a separation of concerns between the layers, and by binding b-threads to context, we increase the modularity of the behavioral specification and the system.
In the following examples and case studies, we follow this design and separate each implementation to three sections -the DB schema is defined in a Context Specification section, the DAL is defined in a Data-Access Layer section, and the business-logic layer (i.e., the CBTs) is defined in a Behavioral Specification section.

Examples -Motivations and Overview
To demonstrate how context-aware systems can be specified, executed, and verified, using the abstract semantics, we now present two extremely simple examples, that are given here merely for understanding these concepts.Real-life systems developed using a JavaScript implementation of the paradigm, are presented in the case studies below (sections 9, and 10).While the examples here are abstract, we have also implemented them using our JavaScript implementation.The code can be downloaded and executed from https://github.com/bThink-BGU/Papers-2020-COBP-Semantics.
For each of the following examples, we demonstrate its "execution" using the formal semantics, by representing how the context and the live copies changes over time.

Example -The Context-Aware Hot-Cold System
We now demonstrate how the extended hot-cold system can be implemented using the abstract semantics.We begin with describing the system requirements: 1.A building has different room types, such as: kitchen, bathroom, bedroom, living room, hall, etc.
2. Kitchens and bathrooms have a button and a hot and a cold taps.
3. For each room with taps: (a) When the button is pressed, pour some small amount of cold water three times.
(b) When the button is pressed, pour some small amount of hot water three times.
4. In kitchens -two actions of the same type cannot be executed consecutively (to avoid a burn).
We note that requirement #3 defines the desired system behavior in the context of 'room with taps', and requirement #4 defines the desired behavior in the context of 'kitchen'.Requirements #1 and #2 define data constraints on the system, or data aspects of the system.Thus, they define the schema of the system context rather than its behavior.We also note that the system context is static and does not change throughout the lifetime of this system.Yet, requirements that depend on dynamic contexts are possible as well, for example: requirements that depend on personal preferences (e.g., whenever Joe uses the kitchen's taps -pour only two units), room temperature (e.g., do not pour hot water when the room temperature is high), etc.In Section 6 we demonstrate the case of dynamic contexts.

Implementation
We define the possible events of the system to be E = {Push i , Hot i , Cold i : i ∈ N}, where i represents the i-th room, Push i represents pushing the button of room i , and Hot i /Cold i represents pouring hot/cold (respectively) in room i.
• The i-th room in the building is represented by room i = i, type i , where i ∈ N is the room number and type i ∈ RoomType represents the type of the room.
• We define the set of all possible system contexts, CTX , to be {room i : i ∈ N}, a set of all possible rooms in the building.

Data-Access Layer
As noted before, the behavioral requirements depend on two contexts -'room with taps' and 'kitchen'.Therefore, the DAL has two queries on the context: The names of the queries -RoomWithTaps and Kitchen are used by the CBTs as an abstraction for the queries (see below).Thus, future changes to the context specification (e.g., due to additional requirements) will not affect the definitions of the CBTs.

Behavioral Specification (CBTs)
The three b-threads in Section 2 are converted to CBTs, where the hot/cold are bound to the RoomWithTaps context, and the interleave b-thread is bound to the kitchen context:

Execution Demonstrations
We now demonstrate the execution of the above contextaware b-program.We denote LC X,i as a live copy of CBT X for room i, where X ∈ {Cold, Hot, Int}.We note that while i is a parameter in the definition of the LTS of each CBT, when the live copies are spawned, their seed (i.e., a result to the CBT's query) contains the value of i.
In this example, we assume that there are three rooms: a kitchen, a bathroom, and a bedroom.We define our initial context to be { 1, kitchen , 2, bathroom , 3, bedroom }, and our initial live copies are thus: {LC Cold,1 , LC Hot,1 , LC Int,1 , LC Cold,2 , LC Hot,2 }.Each live copy uses a different subset of events, meaning that the behavior of each room with taps is independent with the behavior of other rooms.Therefore, we note two observations: 1.The interleave CBT is bound to the Kitchen query.
Therefore, upon pushing the buttons of the kitchen and the bathroom, the Hot/Cold events of the kitchen (Cold 1 and Hot 1 ) will be interleaved, and the hot/cold events of the bathroom (Cold 2 and Hot 2 ) will not.
2. There are no constrains on the order of the events between the different rooms.Thus, for example, the following order is possible: P ush 1 , Cold 1 , P ush 2 , Hot 2 , Hot 1 , Hot 2 , Cold 1 , Hot 1 , Cold 2 , Cold 1 , Hot 2 . . .

A Short Discussion
COBP allows for a more succinct code, compared to BP.In this example, we had three CBTs (cold, hot, and interleave) only.A similar BP code will have five b-threads, one for each live copy, with the seed hard-coded in its code.

Example -The Game of Life
The Game of Life, or simply Life, is a zero-player game based on a cellular automaton, devised by Conway in 1970 [12].The game board is an infinite, two-dimensional orthogonal grid of cells, where each cell can be either populated with an individual or unpopulated.Each individual interacts only with its neighbors, that is, individuals that are in one of the eight cells adjacent to it.The initial population of the game, also called a seed, is set by the user.Then, the following four rules are applied to the seed individuals, to generate the population of the first generation: 1. Any individual with fewer than two neighbors -dies -as if by underpopulation.

Any individual with two or three neighbors -lives
on to the next generation.
3. Any individual with more than three neighborsdies -as if by overpopulation.
4. Any three individuals that are the only ones that surrounds an unpopulated cell -reproduce an individual at that cell.
All rules are applied simultaneously to all of the individuals -births and deaths occur simultaneously, at a discrete moment called a tick.The rules are repeatedly applied to create further generations.
We note that each requirement depends on a different context: the context of the first requirement is "individual with fewer than two neighbours", the context of the second requirement is "individual with two or three neighbours", and so on.

Implementation
We define the possible events as E = {die(row, col), reproduce(row, col), tick, tock : row, col ∈ N}, where the events die(row, col) and reproduce(row, col) represent the death and reproduce (respectively) of an individual at the cell row, col , tick represents the state of the system at the beginning moment of a generation, and tock represents the rest of the system states.

Context Specification
• We define the set of all possible system contexts, CTX , to be { Pop, Tick : Pop ⊆ { row, col : row, col ∈ N}, Tick ∈ {0, 1}}, where the population (represented by Pop) is a set of the locations of all living individuals, and Tick = 1 if and only if all of the individuals have finished processing their rules for the current generation, and the rules-processing of the following generation has not yet started.
• The set of all cells that can be reached from the cell row, col in one step, is defined by the function ngb(row, col

Data-Access Layer
As noted before, each requirement is bound to a different context.Therefore, for each context we define a different query, labeling it by the requirement ID: The effect function is: • die(row, col)( Pop, Tick ) = Pop\{ row, col }, Tick , is the effect of the event die(row, col) that removes the individual from the population.
• reproduce(row, col)( Pop, Tick ) = Pop ∪ { row, col }, T ick , is the effect of the event reproduce(row, col) that adds the reproduced individual to the population.

Behavioral Specification (CBTs)
For each rule, we define a context-aware b-thread, called CBT i as the CBT for the i-th rule, where Q i is the definition of its query, and BT i is the definition for its tuple →, init, R, B .

Execution Demonstrations
We now demonstrate the execution of the program with different seed populations.We do that by presenting how the context and the live copies change over the generations.For each generation i, we present the set of the live copies at their initial state, denoted by LC i , and the state of the context at the beginning of the generation, denoted by ctx i .Given name ∈ {1, 2, 3, 4, tick}, we denote LC name, row,col = CBT name , Q name , row, col as the live copy of CBT name where the result of Q name (i.e., the seedc), is row, col .
Two Lonely Individuals.In this example, the seed generation has two individuals that are not neighbors.According to the rules, they must die in the following iteration, i.e., the answer for Q

Example -Evolved Game of Life
While the CBTs for the game rules demonstrate the concept of context, they consist of a single state, thus missing the 'scenario' trait of BP.
Consider for example the following new requirements for the game (in analogy to the Laws of Robotics by Asimov [2]): A. Any three lonely individuals (i.e., individuals with no neighbors) that are the only ones that surround an unpopulated cell -perform the mating dancea complete clockwise circling around the unpopulated cell (depicted in Figure 4).Upon completion, the three reproduce an individual at that cell.
B. Otherwise, the original rules are valid: 1. Any individual with fewer than two neighborsdies -as if by underpopulation.
2. Any individual with two or three neighborslives on to the next generation.
3. Any individual with more than three neighbors -dies -as if by overpopulation.
4. Any three individuals that are the only ones that surrounds an unpopulated cell -reproduce an individual at that cell.
We note that rule A defines a new context-dependent requirement, while B rules only refine the context of the original rules.

Implementation
The mating dance involves eight 'dancing' steps of three lonely individuals around an unpopulated cell row, col , until they complete a circle.We represent the dancing step of the three individuals with the event step(row, col), that is added to the previously defined event-set (in Section 6.1).
One way to implement the B requirements, is to add a condition to each of the CBTs of the original system, that validates that the individual does not participate in a mating dance.We will take a more subtle approach that is made possible by the COBP paradigm.Specifically, since only the context of the original requirements has changed, and the behavior did not, we will use the original CBTs and only change their queries to exclude the case of a mating dance.

Context Specification
No changes.

Data-Access Layer
To simplify Q A , we define the function isLonely that receives a cell and returns true iff it has no neighbors: isLonely(row, col) = true ⇐⇒ (|ngb(row, col) ∩ op| = 0).
Our queries are then: • For each of the original queries in Section 6.1, we add the following constraint to make sure that the individuals do not participate in a mating dance: i, j ∈ Q A : row, col ∈ ngb(i, j).The new queries are: To the the effect function we add an effect for the step(row, col) event, that advances the neighbors to their next dance location:

Behavioral Specification (CBTs)
Since the behavior of the original CBTs did not change, only their context, we only change the query names of the CBTs (i.e., Q 1 will now be Q B1 , Q 2 will now be Q B2 , etc.).We define the following additional CBT for rule A:

Execution Demonstrations
Mating dance and still life.In this example, depicted in Figure 5, we have two patterns.At the bottom of the grid, is the block pattern of the still life type.It is called 'still life' since it does not change over generations.The second pattern is our new dancing pattern.We demonstrate the run for three generations, presenting only the initial state of each generation.The dance starts and completes during the first generation.Since the individuals of the block pattern do not change over generations, at each generation a new live copy of CBT B2 is generated for each one of them.Thus, for simplification, we denote the individuals as block = { 5, 0 , 5, 1 , 6, 0 , 6, 1 }, and their live copies as LC block = {LC B2, 5,0 , LC B2, 5,1 , LC B2, 6,0 , LC B2, 6,1 }.

A Short Discussion
Our initial definition for requirement A did not require that the three individuals will be lonely.When we implemented and run the last example, we observed a bug -in some cases, during the mating dance, the individuals have been duplicated and each copy stepped into a different cell.We added an assertion that checks this run property, and because of the formal semantics of the COBP paradigm, we were able to verify the existence of the bug.Moreover, we were able to find an initial seed that causes the bugwhen the three cells are ordered in a vertical or a horizontal line, then they are neighbors of two unpopulated cells (i.e., from the two sides of the line).In fact, we discovered that the bug was in the requirements which is why we changed them to three lonely individuals.

Case Studies -Motivation and Overview
We now turn to present two case studies of two different industrial fields -robotics and the internet-ofthings.In both case studies we developed the systems using a JavaScript implementation of the COBP paradigm, called COBPjs [11].This implementation is based on BPjs -an environment for running behavioral programs written in JavaScript [5].
The purposes of these case studies are: to present a possible implementation for the paradigm and a possible syntax for the abstract semantics; to present interesting implementation details and design patterns; and to demonstrate real-life use cases where the paradigm may excel other paradigms, both context oriented and not.To keep the focus of this paper, we only discuss the key differences between our implementation and possible implementations in other paradigms and languages.Additional aspects are discussed in Section 11.
The contextual data in COBPjs is stored in a relational database (an in-memory SQLite database1 ) and managed by a data-access layer (DAL) using the Hibernate ORM framework 2 .In analogy to "database views", the context's 'select' queries allow for triggering a stored procedure whenever a record is added or removed from its result (i.e., announcing the changes via events and spawning live copies upon new records) .The context's 'update' commands update the data as required (by adding, deleting, and changing objects and object relations).Query and update commands are accessed by their IDs in the business-logic layer (i.e., the behavioral specification defined by the CBTs), leaving the context-related implementation decisions to the lower layer (i.e., the DAL and the DB).

Case Study -Robotic Operating System (ROS)
Modern autonomous robots, such as smart manipulators and self-driving cars and drones, run many parallel tasks such as obstacle avoidance, exploration, mapping, and navigation.Concurrently, they also need to plan ahead, do fault detection, and preserve their integrity.Many service applications such as, e.g., home-assistance robots, surveillance robotics, inspection, rescue robotics, or entertainment robotics are require to achieve several goals at the same time.The goals may conflict one with the others, and the significance of a task is frequently context dependent.For instance, in a car, avoiding a far obstruction may be of little significance relative to achieving a nearby target position.
In this case study, we demonstrate how COBP can be used for developing decision-making components in ROSbased robotic systems.The Robot Operating System (ROS) framework aims to simplify the task of creating complex and robust robot behavior.At the lowest level, ROS offers a message passing interface that provides an inter-process communication.On top of it, common robot-specific libraries and tools are supplied to get the robot up and running quickly.While ROS simplifies the task of developing robots, it does not include built-in tools for developing the complex and robust robot behaviors.Thus, decisionmaking components are developed in various ways, such as coded using imperative languages (e.g., C++ or Python); modeled using third-party libraries, such as behavior-tree The Robot has to move around the world without hitting the walls.
libraries (e.g., http://wiki.ros.org/decision_making);or, learned by means of artificial intelligence [25].Behavior tree is a plan execution, describing the system behavior by switching between a finite set of tasks [6].They are popular among robots developers and they are considered as a "very efficient way of creating complex systems that are both modular and reactive" [6].While that may be true, some behaviors are defined more easily by describing what must not happen.Consider for example a robot, designed to do tasks while avoiding obstacles, or ignoring certain actions when the battery is low.Adding such conditions may cause the tree to grow unwieldy.Refactoring conditions as hierarchy nodes, or composing multiple trees, address the size problem, but may cause additional problems as complex nodes and undesired behaviors.
To better capture the idea of how COBP can be used for developing robots, we have implemented a COBP version of the decision-making component, taken from the official ROS tutorial (see http://wiki.ros.org/turtlebot3_simulations).The component defines how to move the robot around, while avoiding collision with the walls (see Figure 6).Part of the tutorial code for this decision-making component is presented in Listing 1, written in C++.This specific implementation raises many questions: Is it readable?Is it understandable?Can we easily adjust the code upon new requirements (e.g., do not turn right more than three times in a row)?Can we reuse this code for different tasks (e.g., if we wish to both avoid walls and reach four coordinates in a certain order)?While there are better practices for implementing this robot, a context-oriented approach has several advantages such as: a higher level of modularity of the behavioral specification (i.e., behaviors are bound to contexts); a better alignment to the requirements, a better agility (i.e., changing the context of a requirement only changes the context of the b-thread, a separation of concerns between the behavior and the data structure, etc.); and more.

Implementation
The possible events are {move(l, a), scan( d 1 , • • • , d 360 ), CTX .Ended(q, c)}, where move represents moving the robot forward with a linear velocity of l and rotating it in with an angular velocity of a, scan represents the distances from the robots to obstacles in 360 degrees, and CTX .Ended declares that c is no longer the answer to query q (i.e., the context c has ended).

Context Specification
Since this problem is extremely simple, the context schema (that defines CTX ) is specified by a single table, called robot, with four attributes -an id (primary key), and three numbers, called oAhead, oLeft, and oRight, that represent the distance from the robot to an obstacle in that direction (if there is no obstacle, the value is infinite).Since there is only one robot, the table will contain only one row, though it supports more.

Data Access Layer
QUERY and UPDATE are defined in Table 1.The effect function of the scan event triggers a call to the update function SetObstacles with the relevant data -

Behavioral Specification (CBTs)
The code in Listing 2 is the COBPjs implementation for the decision-making component.The "Movement" CBT specifies the possible moves of the robot, by constantly requesting to move forward, turn right, or turn left.The last three CBTs block linear and angular movements in case the movement will cause the robot to collide an obstacle.Each of these CBTs is bound to an obstacle query (i.e., ObstacleAhead, ObstacleLef t, and ObstacleRight) and block the movement until the context ends.We note that the scan event is triggered by ROS and is not presented in this code.The execution engine of BPjs orchestrate the live copies, driving the robot around while avoiding the walls.

A Short Discussion
The COBPjs implementation demonstrates several advantages of the paradigm.
• Context activation vs. behavior: The "Avoid obstacles" CBTs block the movement towards an obstacle as long as the context lasts.Another option to break the 'blocking' is to wait for other movements, for example: bp.sync({ block: move(0, 1.5), waitFor: [move(0, -1.5),move(0.3,0)] }); This implementation is a bad practice since it breaks the context abstraction.There is a difference between the triggers and the sequences of events that led for activating/deactivating the context, and the behavior of a system during the context.Consider for example a new requirement that specifies that the robot can move backwards as well.In this case, the context will end, however the live copy that waits for other, specific movements -will remain blocked.
• Verification: The block idiom may lead to deadlocks in BP and COBP programs.For example, if our robot will reach a corner while facing it -all of the possible moves will be blocked and our program will reach a deadlock.This bug, of course, is in the requirements, and can be solved by, e.g., allowing to move backwards.Yet, in more complex systems it might not be trivial to detect such deadlocks.Furthermore, the dynamic changes of the context may lead to additional unpredicted behaviors, a problem that is shared with the COP paradigm as well (elaborated in Section 11).BPjs (and thus, also COBPjs) has a verification tool that we used to detect the deadlock.The tool enable to traverse the state space of the program and validate certain assertions, for instance that the system is deadlock free.The input of this tool is the program, and a set of assertions to validate.Once a violation is detected, the trace of events that led to the violation is returned to the user for inspection.In Section 11, we compare the performance of this tool to the performance of a similar tool on non-BP program.
• Higher level of incrementallity and agility: The context idioms allow for adding new variations of the behavior under different contexts, thus improving the agility of the program.Consider for example a new requirement: "when the battery is low, the robot must reach the nearest power socket for recharging", or "if the robot has a package to deliver, it must first take it from the source location and then take it to its destination".Handling such requirements after the system is developed using a non-context-oriented approach, requires normally a redesign of the code.
The COBP paradigm on the other hand, allows us to add these behavioral variation without changing the current CBTs, as demonstrated in Listing 3. The code assumes some changes to the schema -adding a batteryLevel attribute to the robot table and two new tables, called Target and Delivery.In addition, there are changes to the DAL -adding queries and command for retrieving and manipulating the data of the new schema, as well as updating the effect function for triggering the new UPDATE commands.
differences though, reveal the some of the key differences between the two paradigms (that we discuss here and in Section 11): -Code organization: One of the challenges in the design of context-aware systems is organizing code of crosscutting aspects [32].Contextdependent behaviors are often aspects that crosscut the application logic.While the partial methods in COP handle the aspects of the contextdependent behaviors, the other method parts (of these partial methods) may handle other aspects.Thus, it is difficult to organize the codebase without compromising the maintainability and the separation of concerns.In COBP, the alignment between the requirements and the specification, allows for a natural organization of the codebase.The queries are aligned to the contexts of the requirements (in our case study: robot, obstacles, etc.), and the CBTs are aligned to the requirements.
-Layer/Context activation: In COP, the layer activation mechanism handles the composition of the partial methods of the activated layers.Such a composition is hard to handle since it is crucial to define (and when possible, to reason) the calling order of the partial methods since it may affect the behavior (as elaborated in Section 11).As explained above, this process is formalized in COBP.If the requirements do not imply a certain order of activation -then any order can take place.On the other hand, if there is a requirement that explicitly defines an order of events, then we will have a dedicated CBT that will handle this requirement.

Case Studies -Smart Building
In this case study, we demonstrate how COBP can be used for developing reactive IoT systems, by implementing the example of [10] in COBPjs.We first list a set of requirements for a smart-building system and implement it.Next, we introduce additional requirements and refine the system specification, demonstrating the flexibility and agility offered by the paradigm.
The initial requirements are as follows: Physical: R1) The room types include offices, kitchens, and restrooms; R2) Each room has a motion detector and a smart light; R3) An Office has a smart air-conditioner; R4) Events are emitted when a motion starts or stops.Behavioral: R5) In all rooms, the light should be turned on once a motion is detected, and should be turned off if there is no motion detection for three minutes; R6) In office rooms, the air-conditioner should be turned on once a motion is detected, and should be turned off if there is no motion detection for three minutes; R7).In emergency, lights that are on must not be turned off.
We begin with identifying the context of the requirements, observing that while requirements R5 and R6 specify that the behavior depends on motion detection, the actual context of these requirements is that the room is empty/nonempty.Moreover, using a motion sensor for detecting occupancy is only one option that may change over time.Thus, we change these requirements slightly to depend on the occupancy of the rooms -In X, the Y should be turned on when there is someone in the room and turned off when the room is empty (X is rooms/office rooms and Y is light/air-conditioner, depending on the requirement).We also add the following requirement: R8 A room is considered as empty if and only if it has no movement for more than three minutes.Listing 3: Additional CBTs for the two new requirements: "when the battery is low, the robot must reach the nearest power socket for recharging", or "if the robot has a package to deliver, it must first take it from the source location and then take it to its destination".

Implementation
The possible events of the system are {on(r, d), off (r, d), motionDetected(r), roomIsEmpty(r), roomIsNonempty(r), CTX .Ended(q, c)}, where on and off are used to turn on/off a device d in room r (i.e., light or air-conditioner), motionDetected is an external event that is pushed to the system by the motion sensor of room r, roomIsEmpty/ roomIsNonempty are used to declare that room r is empty/nonempty (respectively), and CTX .Ended declares that c is no longer the answer to query q (i.e., the context c has ended).

Context Specification
We begin with specifying the contexts in mind, in light of the given requirements.In our view, everything may be included in as context data, ranging from physical entities to logical ones.We define the following entities: originating from R1: Building, Room, Kitchen, Office, Restroom; originating from R5 and R6: the isEmpty attribute of Room; and originating from R7: Emergency.We further define the devices entities, i.e., MotionSensor, SmartLight (R2), and AirConditioner (R3).We then define the relationships among the different entities.Of course this is just one of the ways to define the schema for these requirements.Figure 7 presents the resulting context schema.In devising the context schema, we adopt the UML class diagram notation.Other languages may be used as well.
Once the context schema is designed, we populate it with the initial predefined data.That is, adding the building and the rooms to the database and associating the rooms to buildings, as well as, binding the devices to the specific rooms.

Data Access Layer
QUERY and UPDATE are defined in Table 2.The effect of the motionDetected event updates the timestamp of the last movement by calling UpdateMovement.The effect of roomIsEmpty and roomIsNonempty trigger a call to the corresponding update commands -RoomIsEmpty and RoomIsNonempty.

Behavioral Specification (CBTs)
The behavioral specification is given in Listing As development evolves, new requirements may arise.In our example these include: Physical: R9) Smart speakers are installed in all rooms (in addition to R2 devices); R10) Workers can be identified in the system (e.g., by a RF tag or a Bluetooth device), while visitors cannot.Behavioral: R11) If a worker enters a room, announce her name in the room's speaker; R12) During an emergency, turn on all lights.
To cope with these requirements, we can add object types that represent new aspects of the context.To the schema, we add a Smart Speaker data type (similarly to the other devices) (R9) and a Worker data type, both associated with Room (see Figure 8).To the DAL we add commands for marking and un-marking that a worker has entered a room (R11) (similar to the room occupancy update commands).We also modify the effect function for triggering them.For getting a view of all workers that are inside a room (R10), we add the WorkerInARoom query, defined as SELECT * FROM worker WHERE id IS NOT NULL.Finally, we add the following CBTs: two for detecting entrance/leaving of workers (and triggering the appropriate marking/unmarking command using the effect function) (R10, R11); one for turning the lights on during an emergency (R12) (similar to the Emergency CBT in Listing 4; and one for announcing the worker name (demonstrated in Listing 5) (R11).
Thanks to the incrementality feature of BP, no changes to the previous specification are needed, we only added elements to the schema, to the query and command repository, and to the behavioral specification.

A Short Discussion
Separation of concerns.To determine the occupancy of a room, we created two CBTs that kept the isEmpty attribute updated.It should be noted that there is simpler way to determine the occupancy -remove the isEmpty attribute and the update commands (RoomIsEmpty and RoomIsNonempty) and change the queries EmptyRoom and NonemptyRoom to:  While this solution is simpler and more concise, it breaks the separation of concern and defines behavioral aspects in the data layer.Consider for example a change in the requirements, where the occupancy is determined by two sensors (i.e., to improve accuracy), and the thresholds for the sensors are different during working hours.By adding the isEmpty attribute for declaring the occupancy, we achieve a better separation of concerns, thus improving the agility of the system.
Encapsulation.One experience in developing COBP systems yielded an encapsulation rule of thumb.The specification of what to do while a context is active, should be separated from the logic of determining that a context should be activated/deactivated.The activation/deactivation logic should be encapsulated in dedicated CBTs.Consider the Empty/Nonempty Room, where additional behaviors are desired when the room is not empty (e.g., resuming the music, opening the shutters, etc.).We could have add many more behaviors that are bound to the Nonemptyroom query, and allow future changes to the activation/deactivation mechanism.[10,11] that we generalize here, there is no prior work on context for BP.Yet, there are are two, somewhat related works that we discuss here.
The work on BP began with scenario-based programming (SBP), a way to create executable specifications of reactive systems, introduced through the language of live sequence charts (LSC) and its Play-Engine implementation [9,20].While BP allows for behavioral specification only, the LSC language includes idioms for both behavioral and data specifications.The lifelines represent objects, possibly with data properties, allowing to share data among scenarios.A lifeline can either refer to a concrete object, or define a binding expression that is evaluated at runtime, meaning that a live-copy of the chart is instantiated whenever there is a new answer to the binding expression.Indeed [10] exploited this trait for defining the context idioms as syntactic sugars of dynamic binding.Moreover, the Play-Engine specification splits each chart to a prechart and a main chart, where the prechart describes events (and conditions), that when they occur (or are satisfied), the system will attempt to execute the specification in the main chart.Thus, binding a chart to a context can be achieved by defining the context query inside the prechart area.While these two traits (dynamic binding and prechart) allow for sharing data among scenarios, we identify three major limitations of using them directly, compared to using explicit context idioms.First, for achieving an alignment between charts and context-aware requirements, the language must include explicit "first-class citizen" idioms for referencing and changing the system context.Second, there is a tight coupling in LSC between the data specification and the behavioral specification, where changes to data structure require changes to the charts.In our case, any change to a context query requires changing all the bound charts.The context idioms proposed here and in [10], allow for a better separation-of-concerns by splitting the context-related design from the behavioral design, using the multilayered architectural pattern.Finally, the two traits are available for LSC only, while the COBP semantics we define here extend these ideas to other scenario-based languages.
Atir et al. [3] proposed to use the dynamic binding trait  for extending LSC with idioms for specifying hierarchies between scenarios.Using hierarchies, they were able to abstract parts of the behaviors to different charts and activate them from several places.Atir et al. did not refer to context specification, however in some cases, context can be viewed (and implemented) as hierarchy.The COBP paradigm and the semantics we define here, extends this idea to other context types.

Synthesis and Reasoning
A recent literature review [29], argued that the industry is currently concerned with the quality assurance of contextaware software systems (i.e., that the software will not fail upon context changes), while failing to cover aspects of functional assurance.The problem with covering all the possible variations of context during testing execution is not feasible.This is where formal methods and reasoning techniques may excel.
As we explained in Section 1, COP and COBP share the need for applying reasoning techniques on their model, in order to cope with unpredictable behavior that may occur due to the dynamic adaptation to context conditions.In fact, the BP paradigm faces this problem as well, due to the distributed nature of the paradigm, resulting with many tailored reasoning techniques that we now elaborate on.
Starting from the pioneering work of Harel, Kugler and Pnueli [17], most of the synthesis and analysis tools for BP and SBP rely on the mathematically rigorous nature of the semantics in providing tools for running formal analysis and synthesis algorithms [5, 14-16, 18, 19, 23, 31].There are different approaches for verifying behavioral code: 1. Harel et al. [17] translated the model to SMV [30] and analyzed the equivalent SMV model.The method allows for symbolic model-checking that relies on a robust verification framework, though it requires a translation that may not be either sound or complete.
2. Bar-Sinai, Weiss and Shmuel [5] presented a verification tool for BPjs, that avoids the translation by directly traversing the state space of the program, as in NASA's JavaPathFinder (JPF) [27].The method only allows for explicit model-checking.The advantage, however, is that it allows for model-checking any code because it uses the JavaScript interpreter in its state-space traversal.Bar-Sinai [4] compared the performance of this method to the performance of JPF (also summarized in Table 3).To compare, they verified with both tools different programs with various number of b-threads.JPF verified the program as a standard, non-BP program, therefore looking at all thread interleaving options, while BPjs only counted synchronization points as states.Not surprisingly, the JPF verification process was much longer, taking 85 seconds to verify a program containing three b-threads, visiting 438,568 states.While trying to verify a program with six b-threads, JPF ran out of memory after 8:31 minutes.BPjs was able to verify a program containing 10,000 b-threads in 10:67 minutes.
3. [15] used a hybrid approach that assumes that state explosion only comes from the b-threads composition, rather than their individual size.Given that, the space of each b-thread can be translated to a model, used by a model-checker for analyzing the composition of the b-threads.This method allows for a robust verification framework without manually creating a translator, though it only applies to systems with small b-threads (in terms of number of states).
4. Maoz and Ringert [28] used a tool for direct specification of models using SMV-like languages.They presented a case study of developing a software controller for a forklift robot using GR(1) [31] synthesis tools.Their main observation is that extensions of the specification language with auxiliary variables and higher-level specification patterns support writing specifications with better confidence.On the other hand, with growing specification size, understanding reasons for synthesized behavior and for unrealizability turned out to be a major challenge.
The addition of context to the model improves the modularity of the model, thus may contribute each of the methods.However, this addition requires an adaptation of each of the above approaches since all are designed under the assumption that the only protocol between b-threads is requests, blocking, and triggering of events.In practice, when people use BP with shared data they know that the model-checking technologies will not be applicable to their models.The formal COBP semantics presented here enable the change of this, by adding mechanisms to encode the state of the context data so that the model-checker is aware of the new form of inter-thread communication.
In the rest of this section, we discuss reasoning techniques for COP.Some COP implementations do not have formal semantics, thus applying reasoning techniques requires a partial translation of the actual code to some formal language.Other COP implementations allow for developing the system in a modular manner, where part of the system is specified formally (i.e., the layer-activation constraints), and the rest is defined using the underlying programming-language constructs (e.g., Java, Python, etc.).
In both cases, formal methods and the proposed reasoning techniques can be applied only to the part of the system that is formally specified.Moreover, since COP languages differ both in syntax and semantics, each of the following approaches is applicable only to some of the languages.
Costanza and D'Hondt [7] extended the ContextL language with declarative constraints on layers.The extension simplifies the enforcement of the constraints and allows the programmer to interactively fulfill unmet constraints.The authors of EventECJ proposed to manually specify transition-rules between different contexts with finite-state automata [24].Another solution, presented for Subjective-C, proposed to use a DSL for expressing layer dependencies [13].A modular approach has been proposed in [33], where layer interfaces define a contract between the layers and the classes.Each layers must implement one or more layer interfaces, and each class allows layer interfaces.The layer implementation means that the behavior of the layer satisfies the the layer interfaces it implements, and allowing an interface layer means that the class satisfies the specifications for the allowed layer interface.This change allows for applying a modular reasoning in the layer activation mechanism for composing the partial methods in the activated layer.

Figure 1 :
Figure 1: A b-program that pour 'Cold' and 'Hot' water three times each, that consists of a single b-thread for each requirement.The b-threads are executed simultaneously, requesting, and blocking events at each of their state (the R and B sets).At each execution iteration, an arbiter selects an event that is requested by one of the b-threads and is not blocked by any of them and advances the b-threads according to the selection.Since the b-threads in this example do not block events of each other, the order of the 'Cold' and 'Hot' events is arbitrary.

Figure 2 :
Figure 2: The life cycle of a b-program (adapted from[22]).B-threads repeatedly execute an internal logic and then synchronize with each other, by submitting a synchronization statement to a central event arbiter.Once all b-threads have submitted their statements, the central event arbiter selects an event that was requested and was not blocked.B-threads that either requested or waited for this event are resumed, while the rest remain paused for the next cycle.

Figure 4 :
Figure 4: A mating dance.The three, lonely red individuals surround the unpopulated cell at the center.At each of the following eight generations, the three individuals will move one step along the arrows, from one cell to another, until returning to their original position, completing the mating dance.Then, they will reproduce an individual at the center cell.

Figure 5 :
Figure 5: The individuals (in red) at the beginning of the first three generation of the extended Game of Life example.For each cell/individual that one of the rules is valid for -the rule number is stated.The block pattern is at the bottom of the grid, and the mating-dance pattern is at the top of the grid at generation 0. The dancing takes place during generation 0, and at the end of the dance, a new individual is spawned at cell 1, 1 .
Figure 6: The TurtleBot3 World (credit: http:// emanual.robotis.com).The Robot has to move around the world without hitting the walls.

Figure 7 :
Figure 7: The context schema for the smart-building case study.Both the physical entities and the logical ones are represented in the schema.

Figure 8 :
Figure 8: Schema for the new requirements The a result of the Delivery query has two properties of type Target: source and target.

Table 2 :
4. The first two CBTs, Light : On/Off , are bound to queries Empty− Room and NonemptyRoom (respectively), handling R5.The next two CBTs, Airconditioner : On/Off , are bound to the EmptyOffice and NonemptyOffice queries (respectively), handling R6.R7 is handled in the Emergency : Lights CBT, and finally, the last two CBTs, Mark room as empty/nonempty handle R8.The "query and command" repository for the smart building case study.
Listing 4: The COBPjs version of the code in Listing 1.The last call to bp.registerCBT has an additional parameter, compared to the others, for providing the seconds parameter to the NoMovement query.To the best of our knowledge, besides of the work of

Table 3 :
A comparison between the performance of BPjs verification tool and NASA's JavaPathFinder (JPF).The formal semantics allow BPjs to count count as states only synchronization points, whereas JPF must look at all thread interleaving options.