/
index.html
1666 lines (1549 loc) · 67.6 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>nools</title>
<link rel="stylesheet" href="./assets/css/bootstrap.min.css">
<link rel="stylesheet" href="./assets/css/prettify.css">
<style type="text/css">
/*.subnav-inner {*/
/*width: 100%;*/
/*height: 36px;*/
/*background-color: #EEE;*/
/*background-repeat: repeat-x;*/
/*background-image: -moz-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, whiteSmoke), color-stop(100%, #EEE));*/
/*background-image: -webkit-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*background-image: -ms-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*background-image: -o-linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#f5f5f5', endColorstr = '#eeeeee', GradientType = 0);*/
/*background-image: linear-gradient(top, whiteSmoke 0%, #EEE 100%);*/
/*-webkit-border-radius: 4px;*/
/*-moz-border-radius: 4px;*/
/*border-radius: 4px;*/
/*}*/
/*.subnav .nav > li > a:hover {*/
/*color: black !important;*/
/*}*/
/*.subnav .nav li.dropdown .dropdown-toggle .caret,*/
/*.subnav .nav li.dropdown.open .caret {*/
/*border-top-color: #999 !important;*/
/*border-bottom-color: #999 !important;*/
/*}*/
/*.subnav-fixed {*/
/*position: fixed;*/
/*width : 90%;*/
/*margin-right: auto;*/
/*margin-left: auto;*/
/*top: 40px;*/
/*left: 0;*/
/*right: 0;*/
/*z-index: 1020;*/
/*border-color: #D5D5D5;*/
/*border-width: 0 0 1px;*/
/*-webkit-border-radius: 0;*/
/*-moz-border-radius: 0;*/
/*border-radius: 0;*/
/*-webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);*/
/*-moz-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);*/
/*box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);*/
/*filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);*/
/*}*/
/*.navbar .nav .dropdown-menu {*/
/*max-height: 500px;*/
/*overflow: auto;*/
/*}*/
</style>
<style type="text/css">
body {
padding: 90px;
}
.subnav{
margin-top: 40px;
margin-right: auto;
margin-left: auto;
z-index: 1000;
}
.dropdown-menu{
max-height: 500px;
overflow-y: auto;
}
@media (max-width:979px) {
.subnav{
margin-top: auto;
}
}
</style>
<link rel="stylesheet" href="./assets/css/bootstrap-responsive.min.css">
<script type="text/javascript">
var init = (function () {
"use strict";
var processScroll = (function () {
var curr = null, prev = null;
return function (nav) {
var $win = $(window);
$('.subnav').each(function () {
var nav = $(this);
var navTop = $win.width() < 980 ? 0 : nav.offset().top - 40;
var scrollTop = $win.scrollTop();
if (scrollTop >= navTop && curr != nav) {
if(curr){
curr.removeClass('subnav-fixed')
prev = curr;
}
curr = nav;
curr.addClass('subnav-fixed')
} else if (curr == nav && scrollTop <= navTop) {
curr.removeClass('subnav-fixed');
prev.addClass('subnav-fixed');
curr = prev;
}else{
nav.removeClass('subnav-fixed');
}
});
};
})();
return function () {
window.prettyPrint && prettyPrint();
$(".collapse").collapse();
var $window = $(window);
//$(".subnav").affix ();
// fix sub nav on scroll
// processScroll();
// $(window).on('scroll', processScroll)
}
})();
</script>
</head>
<body onload="init()">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"> </span>
</a>
<a href="./index.html" class="brand">nools</a>
<div class="nav-collapse">
<ul class="nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Docs<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="./examples.html">Examples</a></li>
<li><a href="./History.html">Change Log</a></li>
</ul>
</ul>
<ul class="nav pull-right">
<li class="divider-vertical"></li>
<li><a href="https://github.com/C2FO/nools" target="#github" class="pull-right">github</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<a name="top"></a>
<div class="container">
<p><a href="https://travis-ci.org/C2FO/nools"><img src="https://travis-ci.org/C2FO/nools.png" alt="Build Status"></a></p>
<p><a href="https://ci.testling.com/C2FO/nools"><img src="https://ci.testling.com/C2FO/nools.png" alt="browser support"></a></p>
<h1>Nools</h1>
<p>Nools is a <a href="http://en.wikipedia.org/wiki/Rete_algorithm">rete</a> based rules engine written entirely in javascript.</p>
<h1>Installation</h1>
<pre class='prettyprint linenums lang-js'><code>npm install nools</code></pre>
<p>Or <a href="https://raw.github.com/C2FO/nools/master/nools.js">download the source</a> (<a href="https://raw.github.com/C2FO/nools/master/nools.min.js">minified</a>)</p>
<h1>Usage</h1>
<ul>
<li>Flows<ul>
<li><a href="#flow">Defining A Flow</a></li>
<li><a href="#session">Sessions</a></li>
<li><a href="#facts">Facts</a><ul>
<li><a href="#facts-assert">Assert</a></li>
<li><a href="#facts-retract">Retract</a></li>
<li><a href="#facts-modify">Modify</a></li>
<li><a href="#get-facts">Retrieving Facts</a></li>
</ul>
</li>
<li><a href="#firing">Firing</a></li>
<li><a href="#disposing">Disposing</a></li>
<li><a href="#removing-flow">Removing A Flow</a></li>
<li><a href="#removing-flows">Removing All Flows</a></li>
<li><a href="#checking-for-flow">Checking If A Flow Exists</a></li>
<li><a href="#agenda-groups">Agenda Group</a><ul>
<li><a href="#agenda-groups-focus">Focus</a></li>
<li><a href="#agenda-groups-auto-focus">Auto Focus</a></li>
</ul>
</li>
<li><a href="#conflict-resolution">Conflict Resolution</a></li>
</ul>
</li>
<li><a href="#defining-rule">Defining Rules</a><ul>
<li><a href="#rule-structure">Structure</a></li>
<li><a href="#rule-salience">Salience</a></li>
<li><a href="#rule-scope">Scope</a></li>
<li><a href="#constraints">Constraints</a><ul>
<li><a href="#custom-contraints">Custom</a></li>
<li><a href="#not-constraint">Not</a></li>
<li><a href="#or-constraint">Or</a></li>
<li><a href="#from-constraint">From</a></li>
<li><a href="#exists-constraint">Exists</a></li>
</ul>
</li>
<li><a href="#action">Actions</a><ul>
<li><a href="#action-async">Async Actions</a></li>
</ul>
</li>
<li><a href="#globals">Globals</a></li>
<li><a href="#import">Import</a></li>
</ul>
</li>
<li><a href="#browser-support">Browser Support</a></li>
<li><a href="#fib">Fibonacci</a></li>
</ul>
<h2>Resources</h2>
<ul>
<li><a href="https://groups.google.com/forum/#!forum/nools">Nools Google group</a></li>
<li><a href="http://c2fo.github.io/nools/examples.html">Examples</a><ul>
<li><a href="http://c2fo.github.io/nools/examples/browser/conways_2d.html">Conways 2D</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/conways_3d.html">Conways 3D</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/sudoku.html">Sudoku</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/fibonacci.html">Fibonacci</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/manners.html">Miss Manners</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/waltzDb.html">Waltz DB</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/sendMoreMoney.html">Send More Money</a></li>
<li><a href="http://c2fo.github.io/nools/examples/browser/diagnose.html">Diagnosis</a></li>
</ul>
</li>
<li><a href="https://github.com/C2FO/nools/tree/master/test">Tests</a></li>
</ul>
<p><a name="flow"></a></p>
<h2>Defining a flow</h2>
<p>When using nools you define a <strong>flow</strong> which acts as a container for rules that can later be used to get
a <strong>session</strong></p>
<h3>Programmatically</h3>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var nools = require("nools");
var Message = function (message) {
this.text = message;
};
var flow = nools.flow("Hello World", function (flow) {
//find any message that start with hello
flow.rule("Hello", [Message, "m", "m.text =~ /^hello\\sworld$/"], function (facts) {
facts.m.text = facts.m.text + " goodbye";
this.modify(facts.m);
});
//find all messages then end in goodbye
flow.rule("Goodbye", [Message, "m", "m.text =~ /.*goodbye$/"], function (facts) {
console.log(facts.m.text);
});
});</code></pre>
<p>In the above flow definition 2 rules were defined</p>
<ul>
<li>Hello<ul>
<li>Requires a Message</li>
<li>The messages's <code>text</code> must match the regular expression <code>/^hello\\sworld$/</code></li>
<li>When matched the message's <code>text</code> is modified and then we let the engine know that we modified the message.</li>
</ul>
</li>
<li>Goodbye<ul>
<li>Requires a Message</li>
<li>The messages's <code>text</code> must match the regular expression <code>/.*goodbye$/</code>(anything that ends in goodbye)</li>
<li>When matched the resulting message is logged.</li>
</ul>
</li>
</ul>
<h3>DSL</h3>
<p>You may also use the <code>nools</code> rules language to define your rules.</p>
<p>The following is the equivalent of the rules defined programmatically above.</p>
<pre class='prettyprint linenums lang-js'><code>define Message {
text : '',
constructor : function(message){
this.text = message;
}
}
//find any message that starts with hello
rule Hello {
when {
m : Message m.text =~ /^hello(\s*world)?$/;
}
then {
modify(m, function(){this.text += " goodbye";});
}
}
//find all messages then end in goodbye
rule Goodbye {
when {
m : Message m.text =~ /.*goodbye$/;
}
then {
console.log(m.text);
}
}</code></pre>
<p>To use the flow</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var flow = nools.compile(__dirname + "/helloworld.nools"),
Message = flow.getDefined("message");</code></pre>
<h3>Flow Events</h3>
<p>Each flow can have the following events emitted.</p>
<ul>
<li><code>assert (fact)</code> - emitted when facts are asserted</li>
<li><code>retract (fact)</code> - emitted when facts are retracted</li>
<li><code>modify (fact)</code> - emitted when facts are modified</li>
<li><code>fire (name, rule)</code> - emitted when an activation is fired.</li>
</ul>
<pre class='prettyprint linenums lang-js'><code>session.on("assert", function(fact){
//fact was asserted
});
session.on("retract", function(fact){
//fact was retracted
});
session.on("modify", function(fact){
//fact was modifed
});
session.on("fire", function(name, rule){
//a rule was fired.
});</code></pre>
<h3><code>nools.compile</code></h3>
<p>The compile method accepts the following parameters</p>
<ul>
<li><code>source|path</code> - The first argument must either be a path that ends in <code>.nools</code> or a string which is the source of the rules that you wish to compile.</li>
<li><code>options?</code><ul>
<li><code>name</code> : This is the name of the flow. You can use this name to look up the flow by using <code>nools.getFlow</code>.</li>
<li><code>define</code> : A hash of Classes that should be aviable to the rules that you are compiling.</li>
<li><code>scope</code>: A hash of items that should be available to rules as they run. (i.e. a logger)</li>
</ul>
</li>
<li><code>cb?</code> - an options function to invoke when compiling is done.</li>
</ul>
<p><strong>Example</strong></p>
<pre class='prettyprint linenums lang-js'><code>rule "person name is bob" {
when {
p : Person p.name == 'bob';
}
then {
logger.info("Found person with name of bob");
retract(p);
}
}</code></pre>
<p>In the above rules file we make use of a Person class and a logger. In order for nools to properly reference the Class and logger you must specify them in your options.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var flow = nools.compile("personFlow.nools", {
define: {
//The person class the flow should use
Person: Person
},
scope: {
//the logger you want your flow to use.
logger: logger
}
});</code></pre>
<p>You may also compile source directly.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var noolsSource = "rule 'person name is bob' {"
+ " when {"
+ " p : Person p.name == 'bob';"
+ " }"
+ " then {"
+ " logger.info('Found person with name of bob');"
+ " retract(p);"
+ " }"
+ "}";
var flow = nools.compile(noolsSource, {
define: {
//The person class the flow should use
Person: Person
},
scope: {
//the logger you want your flow to use.
logger: logger
},
name: 'person name is bob'
});</code></pre>
<p><a name="session"></a></p>
<h2>Working with a session</h2>
<p>A session is an instance of the flow that contains a working memory and handles the assertion, modification, and retraction of facts from the engine.</p>
<p>To obtain an engine session from the flow invoke the <code>getSession</code> method.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var session = flow.getSession();</code></pre>
<p><a name="facts"></a></p>
<h2>Working with facts</h2>
<p>Facts are items that the rules should try to match.</p>
<p><a name="facts-assert"></a></p>
<h3>Assert</h3>
<p>To add facts to the session use <code>assert</code> method.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">session.assert(new Message("hello"));
session.assert(new Message("hello world"));
session.assert(new Message("goodbye"));</code></pre>
<p>As a convenience any object passed into <strong>getSession</strong> will also be asserted.</p>
<p><strong>Note</strong> assert is typically used pre engine execution and during the execution of the rules.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">flow.getSession(new Message("hello"), new Message("hello world"), new Message("goodbye"));</code></pre>
<p><a name="facts-retract"></a></p>
<h3>Retract</h3>
<p>To remove facts from the session use the <code>retract</code> method.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var m = new Message("hello");
//assert the fact into the engine
session.assert(m);
//remove the fact from the engine
session.retract(m);</code></pre>
<p><strong>Note</strong> <code>retract</code> is typically used during the execution of the rules.</p>
<p><a name="facts-modify"></a></p>
<h3>Modify</h3>
<p>To modify a fact use the <code>modify</code> method.</p>
<p><strong>Note</strong> modify will not work with immutable objects (i.e. strings).</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">
var m = new Message("hello");
session.assert(m);
m.text = "hello goodbye";
session.modify(m);</code></pre>
<p><strong>Note</strong> <code>modify</code> is typically used during the execution of the rules.</p>
<p><a name="get-facts"></a></p>
<h3>Retrieving Facts</h3>
<p>To get a list of facts currently in the session you can use the <code>getFacts()</code> method exposed on a session.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">session.assert(1);
session.assert("A");
session.assert("B");
session.assert(2);
session.getFacts(); //[1, "A", "B", 2];</code></pre>
<p>You may also pass in a <code>Type</code> to <code>getFacts</code> which will return facts only of the given type.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">session.assert(1);
session.assert("A");
session.assert("B");
session.assert(2);
session.getFacts(Number); //[1, 2];
session.getFacts(String); //["A", "B"];</code></pre>
<p><a name="firing"></a></p>
<h2>Firing the rules</h2>
<p>When you get a session from a <strong>flow</strong> no rules will be fired until the <strong>match</strong> method is called.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var session = flow.getSession();
//assert your different messages
session.assert(new Message("goodbye"));
session.assert(new Message("hello"));
session.assert(new Message("hello world"));
//now fire the rules
session.match(function(err){
if(err){
console.error(err.stack);
}else{
console.log("done");
}
})</code></pre>
<p>The <strong>match</strong> method also returns a promise that is resolved once there are no more rules to activate.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">session.match().then(
function(){
console.log("Done");
},
function(err){
//uh oh an error occurred
console.error(err.stack);
});</code></pre>
<h2>Fire until halt</h2>
<p>You may also run the engine an a "reactive" mode which will continue to match until <code>halt</code> is invoked.</p>
<p>In the following example the rules engine continues to evaluate until the counter reaches <code>10000</code>. If you remove the "counted to high" rule then the engine would run indefinitely.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">
define Counter {
count: 0,
constructor: function(count){
this.count = count;
}
}
//We reached our goal
rule "I can count!" {
when {
$ctr: Counter $ctr.count == 10000;
}
then{
console.log("Look ma! I counted to " + $ctr.count);
halt();
}
}
//no counter was asserted so create one
rule "not count" {
when {
not($ctr: Counter);
}
then{
console.log("Imma gonna count!");
assert(new Counter(1));
}
}
//A little status update
rule "give them an update" {
when{
$ctr: Counter $ctr.count % 1000 == 0 {count: $count}
}
then{
console.log("Imma countin...");
modify($ctr, function(){this.count = $count + 1;});
}
}
//just counting away
rule count {
when{
$ctr: Counter {count: $count}
}
then{
modify($ctr, function(){
this.count = $count + 1;
});
}
}</code></pre>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">flow.getSession().matchUntilHalt(function(err){
if(err){
console.log(err.stack);
return;
}
//halt finally invoked
});</code></pre>
<p><code>matchUntilHalt</code> also returns a promise.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">flow.getSession().matchUntilHalt()
.then(
function(){
//all done!
},
function(err){
console.log(err.stack);
}
);</code></pre>
<p><a name="disposing"></a></p>
<h2>Disposing of the session</h2>
<p>When working with a lot of facts it is wise to call the <code>dispose</code> method which will purge the current session of
all facts, this will help prevent the process from growing a large memory footprint.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">session.dispose();</code></pre>
<p><a name="removing-flow"></a></p>
<h1>Removing a flow</h1>
<p>To remove a defined flow from <code>nools</code> use the <code>deleteFlow</code> function.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var myFlow = nools.flow("flow");
nools.deleteFlow("flow"); //returns nools for chaining
nools.getFlow("flow"); //undefined</code></pre>
<p>You may also remove a flow using the <code>FlowContainer</code> object returned from nools.flow;</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var myFlow = nools.flow("flow");
nools.deleteFlow(myFlow); //returns nools for chaining
nools.getFlow("flow"); //undefined</code></pre>
<p><a name="removing-flows"></a></p>
<h1>Removing All Flows</h1>
<p>To remove all flow from <code>nools</code> use the <code>deleteFlows</code> function.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var myFlow = nools.flow("flow");
nools.deleteFlows(); //returns nools for chaining
nools.getFlow("flow"); //undefined</code></pre>
<p><a name="checking-for-flow"></a></p>
<h1>Checking If A Flow Exists</h1>
<p>To check if a flow currently is registering with <code>nools</code> use the <code>hasFlow</code> function;</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var myFlow = nools.flow("flow");
nools.hasFlow("flow"); //true</code></pre>
<p><a name="agenda-groups"></a></p>
<h2>Agenda Groups</h2>
<p>Agenda groups allow for logical groups of rules within a flow.</p>
<p>The agenda manages a <code>stack</code> of <code>agenda-groups</code> that are currently in focus. The default <code>agenda-group</code> is called <code>main</code> and all rules that do not have an <code>agenda-group</code> specified are placed into the <code>main</code> <code>agenda-group</code>.</p>
<p>As rules are fired and a particular <code>agenda-group</code> runs out of activations then that <code>agenda-group</code> is popped from the internal <code>agenda-group</code> stack and the next one comes into focus. This continues until <code>focus</code> is explicitly called again or the <code>main</code> <code>agenda-group</code> comes into focus.</p>
<p><strong>Note</strong> Once an agenda group loses focus it must be re-added to the stack in order for those activations to be focused again.</p>
<p>To add a rule to an agenda-group you can use the <code>agendaGroup</code> option.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">this.rule("Hello World", {agendaGroup: "ag1"}, [Message, "m", "m.name == 'hello'"], function (facts) {
this.modify(facts.m, function () {
this.name = "goodbye";
});
});
this.rule("Hello World2", {agendaGroup: "ag2"}, [Message, "m", "m.name == 'hello'"], function (facts) {
this.modify(facts.m, function () {
this.name = "goodbye";
});
});</code></pre>
<p>Or in the dsl</p>
<pre class='prettyprint linenums lang-js'><code>rule "Hello World" {
agenda-group: "ag1";
when{
m : Message m.name === 'hello';
}
then{
modify(m, function(){
this.name = "goodbye";
});
}
}
rule "Hello World 2" {
agenda-group: "ag2";
when{
m : Message m.name === 'goodbye';
}
then {
modify(m, function(){
m.name = "hello";
});
}
}</code></pre>
<p>In the above rules we have defined two agenda-groups called <code>ag1</code> and <code>ag2</code></p>
<p><a name="agenda-groups-focus"></a></p>
<h3>Focus</h3>
<p>When running your rules and you want a particular agenda group to run you must call <code>focus</code> on the session of the flow and specify the <code>agenda-group</code> to add to the stack.</p>
<pre class='prettyprint linenums lang-js'><code>//assuming a flow with the rules specified above.
var fired = [];
flow.getSession(new Message("hello"))
.focus("ag1")
.on("fire", function (ruleName) {
fired.push(ruleName);
})
.match(function () {
console.log(fired); //[ 'Hello World' ]
});</code></pre>
<p>Or you can add multiple <code>agenda-groups</code> to the focus stack.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var fired1 = [], fired2 = [];
flow
.getSession(new Message("goodbye"))
.focus("ag1")
.focus("ag2")
.on("fire", function (ruleName) {
fired1.push(ruleName);
})
.match(function () {
console.log("Example 1", fired1); //[ 'Hello World', 'Hello World2' ]
});
flow
.getSession(new Message("hello"))
.focus("ag2")
.focus("ag1")
.on("fire", function (ruleName) {
fired3.push(ruleName);
})
.match(function () {
console.log("Example 2", fired2); //[ 'Hello World', 'Hello World2' ]
});</code></pre>
<p>Notice above that the <strong>last</strong> <code>agenda-group</code> focused is added to the array first.</p>
<p><a name="agenda-groups-auto-focus"></a></p>
<h3>Auto Focus</h3>
<p>Sometimes you may want an <code>agenda-group</code> to <code>auto-focus</code> whenever a certain rule is activated.</p>
<pre class='prettyprint linenums lang-js'><code>this.rule("Bootstrap", [State, "a", "a.name == 'A' && a.state == 'NOT_RUN'"], function (facts) {
this.modify(facts.a, function () {
this.state = 'FINISHED';
});
});
this.rule("A to B",
[
[State, "a", "a.name == 'A' && a.state == 'FINISHED'"],
[State, "b", "b.name == 'B' && b.state == 'NOT_RUN'"]
],
function (facts) {
this.modify(facts.b, function () {
this.state = "FINISHED";
});
});
this.rule("B to C",
{agendaGroup: "B to C", autoFocus: true},
[
[State, "b", "b.name == 'B' && b.state == 'FINISHED'"],
[State, "c", "c.name == 'C' && c.state == 'NOT_RUN'"]
],
function (facts) {
this.modify(facts.c, function () {
this.state = 'FINISHED';
});
this.focus("B to D");
});
this.rule("B to D",
{agendaGroup: "B to D"},
[
[State, "b", "b.name == 'B' && b.state == 'FINISHED'"],
[State, "d", "d.name == 'D' && d.state == 'NOT_RUN'"]
],
function (facts) {
this.modify(facts.d, function () {
this.state = 'FINISHED';
});
});</code></pre>
<p>Or using the dsl</p>
<pre class='prettyprint linenums lang-js'><code>rule Bootstrap {
when{
a : State a.name == 'A' && a.state == 'NOT_RUN';
}
then{
modify(a, function(){
this.state = 'FINISHED';
});
}
}
rule 'A to B' {
when{
a : State a.name == 'A' && a.state == 'FINISHED';
b : State b.name == 'B' && b.state == 'NOT_RUN';
}
then{
modify(b, function(){
this.state = 'FINISHED';
});
}
}
rule 'B to C' {
agenda-group: 'B to C';
auto-focus: true;
when{
b: State b.name == 'B' && b.state == 'FINISHED';
c : State c.name == 'C' && c.state == 'NOT_RUN';
}
then{
modify(c, function(){
this.state = 'FINISHED';
});
focus('B to D')
}
}
rule 'B to D' {
agenda-group: 'B to D';
when{
b: State b.name == 'B' && b.state == 'FINISHED';
d : State d.name == 'D' && d.state == 'NOT_RUN';
}
then{
modify(d, function(){
this.state = 'FINISHED';
});
}
}</code></pre>
<p>In the above rules we created a state machine that has a rule with <code>auto-focus</code> set to true.</p>
<p>This allows you to not have to specify <code>focus</code> when running the flow.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var fired = [];
flow
.getSession(
new State("A", "NOT_RUN"),
new State("B", "NOT_RUN"),
new State("C", "NOT_RUN"),
new State("D", "NOT_RUN")
)
.on("fire", function (name) {
fired.push(name);
})
.match()
.then(function () {
console.log(fired); //["Bootstrap", "A to B", "B to C", "B to D"]
});</code></pre>
<p><a name="conflict-resolution"></a></p>
<h2>Conflict Resolution</h2>
<p>When declaring a flow it is defined with a default conflict resolution strategy. A conflict resolution strategy is used to determine which rule to activate when multiple rules are ready to be activated at the same time.</p>
<h3>Resolution Strategies</h3>
<ul>
<li><code>salience</code> - sort activations on the specified <a href="#rule-salience"><code>salience</code></a>. (<strong>NOTE</strong> The default salience of a rule is 0).</li>
<li><code>activationRecency</code> - sort activations on activation recency. This is a <code>LIFO</code> strategy the latest activation takes precedence.</li>
<li><code>factRecency</code> - sort activations based on <code>fact</code> recency. Each time a fact is <code>asserted</code> or <code>modified</code> its recency is incremented.</li>
<li><code>bucketCounter</code> - sort activations on the internal <code>bucket</code> counter. The bucket counter is incremented after an activation is fired and the internal <code>workingMemory</code> is altered.</li>
</ul>
<p>The default conflict resolution strategy consists of <code>salience</code> and <code>activationRecency</code>.</p>
<h3>Examples</h3>
<p><strong>Example 1</strong></p>
<pre class='prettyprint linenums lang-js'><code>//activation 1
{
salience: 0,
activationRecency: 1
}
//activation 2
{
salience: 0,
activationRecency: 2
}</code></pre>
<p>In the above example activation 2 would be fired since it is the most recent activation and the rule salience is the same.</p>
<p><strong>Example 2</strong></p>
<pre class='prettyprint linenums lang-js'><code>//activation 1
{
salience: 1,
activationRecency: 1
}
//activation 2
{
salience: 0,
activationRecency: 2
}</code></pre>
<p>In this example activation 1 would fire because it has a greater salience</p>
<h3>Overidding The Default Strategy</h3>
<p>To override the default strategy you can use the <code>conflictResolution</code> method on a flow.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">
var flow = nools.flow(/**define your flow**/);
flow.conflictResolution(["salience", "factRecency", "activationRecency"]);</code></pre>
<p>The combination of <code>salience</code>, <code>factRecency</code>, and <code>activationRecency</code> would do the following.</p>
<ol>
<li>Check if the salience is the same, if not use the activation with the greatest salience.</li>
<li>If salience is the same check if fact recency is the same. The fact recency is determined by looping through the facts in each activation and until two different recencies are found. The activation with the greatest recency takes precendence.</li>
<li>If fact recency is the same check the activation recency.</li>
</ol>
<p><strong>Example 1</strong></p>
<pre class='prettyprint linenums lang-js'><code>//activation 1
{
salience: 2,
factRecency: [1,2,3],
activationRecency: 1
}
//activation 2
{
salience: 1,
factRecency: [1,2,4],
activationRecency: 2
}</code></pre>
<p>In this example activation 1 would fire because it's salience is the greatest.</p>
<p><strong>Example 2</strong></p>
<pre class='prettyprint linenums lang-js'><code>//activation 1
{
salience: 1,
factRecency: [1,2,3],
activationRecency: 1
}
//activation 2
{
salience: 1,
factRecency: [1,2,4],
activationRecency: 2
}</code></pre>
<p>In Example 2 activation 2 would fire because of the third recency entry.</p>
<p><strong>Example 3</strong></p>
<pre class='prettyprint linenums lang-js'><code>//activation 1
{
salience: 2,
factRecency: [1,2,3],
activationRecency: 1
}
//activation 2
{
salience: 1,
factRecency: [1,2,3],
activationRecency: 2
}</code></pre>
<p>In Example 3 activation 2 would fire because <code>salience</code> and <code>factRecency</code> are the same but activation 2's activation recency is greater.</p>
<p><a name="defining-rule"></a></p>
<h1>Defining rules</h1>
<p><a name="rule structure"></a></p>
<h2>Rule structure</h2>
<p>Lets look at the "Calculate" rule in the <a href="#fib">Fibonacci</a> example</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript"> //flow.rule(type[String|Function], constraints[Array|Array[[]]], action[Function]);
flow.rule("Calculate", [
//Type alias pattern store sequence to s1
[Fibonacci, "f1", "f1.value != -1", {sequence:"s1"}],
[Fibonacci, "f2", "f2.value != -1 && f2.sequence == s1 + 1", {sequence:"s2"}],
[Fibonacci, "f3", "f3.value == -1 && f3.sequence == s2 + 1"],
[Result, "r"]
], function (facts) {
var f3 = facts.f3, f1 = facts.f1, f2 = facts.f2;
var v = f3.value = f1.value + facts.f2.value;
facts.r.result = v;
this.modify(f3);
this.retract(f1);
});</code></pre>
<p>Or using the nools DSL</p>
<pre class='prettyprint linenums lang-js'><code>rule Calculate{
when {
f1 : Fibonacci f1.value != -1 {sequence:s1};
f2 : Fibonacci f2.value != -1 && f2.sequence == s1 + 1 {sequence:s2};
f3 : Fibonacci f3.value == -1 && f3.sequence == s2 + 1;
}
then {
modify(f3, function(){
this.value = f1.value + f2.value;
});
retract(f1);
}
}</code></pre>
<p><a name="rule-salience"></a></p>
<h3>Salience</h3>
<p>Salience is an option that can be specified on a rule giving it a priority and allowing the developer some control over conflict resolution of activations.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">this.rule("Hello4", {salience: 7}, [Message, "m", "m.name == 'Hello'"], function (facts) {
});
this.rule("Hello3", {salience: 8}, [Message, "m", "m.name == 'Hello'"], function (facts) {
});
this.rule("Hello2", {salience: 9}, [Message, "m", "m.name == 'Hello'"], function (facts) {
});
this.rule("Hello1", {salience: 10}, [Message, "m", "m.name == 'Hello'"], function (facts) {
});</code></pre>
<p>Or using the DSL</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">rule Hello4 {
salience: 7;
when {
m: Message m.name == 'hello';
}
then {}
}
rule Hello3 {
salience: 8;
when {
m: Message m.name == 'hello';
}
then {}
}
rule Hello2 {
salience: 9;
when {
m: Message m.name == 'hello';
}
then {}
}
rule Hello1 {
salience: 10;
when {
m: Message m.name == 'hello';
}
then {}
}</code></pre>
<p>In the above flow we define four rules each with a different salience, when a single message is asserted they will fire in order of salience (highest to lowest).</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">var fired = [];
flow1
.getSession(new Message("Hello"))
.on("fire", function (name) {
fired.push(name);
})
.match()
.then(function(){
console.log(fired); //["Hello1", "Hello2", "Hello3", "Hello4"]
});</code></pre>
<p><a name="rule-scope"></a></p>
<h3>Scope</h3>
<p>Scope allows you to access function from within your rules.</p>
<p>If you are using vanilla JS you can use the <code>scope</code> option when defining your rule.</p>
<pre class='prettyprint linenums lang-js'><code class="lang-javascript">
this.rule("hello rule", {scope: {isEqualTo: isEqualTo}},
[
["or",
[String, "s", "isEqualTo(s, 'hello')"],
[String, "s", "isEqualTo(s, 'world')"]
],
[Count, "called", null]
],
function (facts) {
facts.called.called++;
});</code></pre>
<p>If you are using the dsl.</p>
<pre class='prettyprint linenums lang-js'><code>function matches(str, regex){
return regex.test(str);
}
rule Hello {
when {
m : Message matches(m.text, /^hello\s*world)?$/);
}
then {
modify(m, function(){
this.text += " goodbye";
})
}
}
rule Goodbye {
when {