theprogrammablemind 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -1,5 +1,7 @@
1
1
  const { Semantics, Semantic } = require('./src/semantics')
2
2
  const { Generators, Generator } = require('./src/generators')
3
+ const { Config } = require('./src/config')
4
+ const { loadInstance, ErrorReason, listable, setupArgs, gs, processContext, getObjects, setupProcessB, processContextsB } = require('./src/configHelpers')
3
5
  const DigraphInternal = require('./src/digraph_internal')
4
6
  const Digraph = require('./src/digraph')
5
7
  const { project } = require('./src/project')
@@ -10,36 +12,10 @@ const _ = require('lodash')
10
12
  const stringify = require('json-stable-stringify')
11
13
  const Lines = require('./lines')
12
14
  const flattens = require('./src/flatten')
13
- const { appendNoDups, InitCalls, updateQueries, safeNoDups, stableId } = require('./src/helpers')
15
+ const { appendNoDups, InitCalls, updateQueries, safeNoDups, stableId, where } = require('./src/helpers')
14
16
  const runtime = require('./runtime')
15
17
  const sortJson = runtime.sortJson
16
18
 
17
- function where (goUp = 2) {
18
- const e = new Error()
19
- const regexForm1 = /\((.*):(\d+):(\d+)\)$/
20
- const regexForm2 = /at (.*):(\d+):(\d+)$/
21
- const lines = e.stack.split('\n')
22
- let line
23
- let match
24
- for (line of lines.slice(1)) {
25
- // if (!(line.includes('config.js:') || line.includes('client.js:') || line.includes('<anonymous>'))) {
26
- if (!(line.includes('config.js:') || line.includes('client.js:'))) {
27
- match = regexForm1.exec(line) || regexForm2.exec(line)
28
- if (!match) {
29
- continue
30
- }
31
- break
32
- }
33
- }
34
- // const line = e.stack.split("\n")[goUp];
35
- // const match = regexForm1.exec(line) || regexForm2.exec(line)
36
- if (match) {
37
- return `${match[1]}:${match[2]}`
38
- } else {
39
- return 'running in browser'
40
- }
41
- }
42
-
43
19
  const getConfig_getObjectsCheck = (config, testConfig) => {
44
20
  let testConfigName = config.name
45
21
  if (testConfig.testModuleName) {
@@ -47,7 +23,13 @@ const getConfig_getObjectsCheck = (config, testConfig) => {
47
23
  }
48
24
  const checks = (testConfig.checks && testConfig.checks.objects) || []
49
25
  if (Array.isArray(checks)) {
50
- return { [testConfigName]: checks }
26
+ const kmToChecks = { [testConfigName]: checks.filter( (check) => !check.km ) }
27
+ for (const check of checks) {
28
+ if (check.km) {
29
+ kmToChecks[check.km] = config.km(check.km).testConfig.checks.objects
30
+ }
31
+ }
32
+ return kmToChecks
51
33
  } else {
52
34
  return checks
53
35
  }
@@ -102,164 +84,6 @@ const vimdiff = (actualJSON, expectedJSON, title) => {
102
84
  }
103
85
  }
104
86
 
105
- const listable = (hierarchy) => (c, type) => {
106
- if (!c) {
107
- return false
108
- }
109
- if (hierarchy.isA(c.marker, type)) {
110
- return true
111
- }
112
- if (c.marker === 'list') {
113
- for (const t of c.types) {
114
- if (hierarchy.isA(t, type)) {
115
- return true
116
- }
117
- }
118
- }
119
- return false
120
- }
121
-
122
- const isA = (hierarchy) => (child, parent) => {
123
- if (!child || !parent) {
124
- return false
125
- }
126
- if (child.marker) {
127
- child = child.marker
128
- }
129
- if (parent.marker) {
130
- parent = parent.marker
131
- }
132
- return hierarchy.isA(child, parent)
133
- }
134
-
135
- const asList = (context) => {
136
- if (context.marker === 'list') {
137
- return context
138
- }
139
- return {
140
- marker: 'list',
141
- types: [context.marker],
142
- value: [context]
143
- }
144
- }
145
-
146
- class ErrorReason extends Error {
147
- constructor (context) {
148
- super(JSON.stringify(context))
149
- this.reason = context
150
- }
151
- }
152
-
153
- const setupArgs = (args, config, logs, hierarchy, uuidForScoping) => {
154
-
155
- // callId
156
- args.calls = new InitCalls(args.isInstance ? `${args.isInstance}#${config.name}` : config.name)
157
- if (global.theprogrammablemind && global.theprogrammablemind.loadForTesting) {
158
- args.calls = new InitCalls(Object.keys(global.theprogrammablemind.loadForTesting)[0])
159
- }
160
- args.km = (name) => config.getConfig(name)
161
- args.api = (name) => config.getConfig(name).api
162
- args.error = (context) => {
163
- throw new ErrorReason(context)
164
- }
165
- args.kms = config.getConfigs()
166
- args.config = config
167
- args.hierarchy = hierarchy
168
- args.isA = isA(hierarchy)
169
- args.listable = listable(hierarchy)
170
- args.asList = asList
171
- args.retry = () => { throw new RetryError() }
172
- args.fragments = (query) => config.fragment(query)
173
- args.breakOnSemantics = false
174
- args.theDebugger = {
175
- breakOnSemantics: (value) => args.breakOnSemantics = value
176
- }
177
- if (!logs) {
178
- }
179
- args.log = (message) => logs.push(message)
180
-
181
- args.addAssumedScoped = (args, assumed) => {
182
- const addAssumed = (args, ...moreAssumed) => {
183
- return { ...args, assumed: Object.assign({}, assumed, (args.assumed || {}), ...moreAssumed) }
184
- }
185
-
186
- args.s = (c) => config.getSemantics(logs).apply(args, c)
187
- args.g = (c, a = {}) => {
188
- return config.getGenerators(logs).apply(addAssumed(args, a), c, a)
189
- }
190
- args.gp = (c, a = {}) => {
191
- return config.getGenerators(logs).apply(addAssumed(args, a, { paraphrase: true, isResponse: false, response: false }), c, { paraphrase: true, isResponse: false, response: false })
192
- }
193
- args.gr = (c, a = {}) => {
194
- return config.getGenerators(logs).apply(addAssumed(args, a, { paraphrase: false, isResponse: true }), { ...c, paraphrase: false, isResponse: true })
195
- }
196
- args.e = (c) => {
197
- return config.getEvaluator(args.s, args.calls, logs, c)
198
- }
199
- args.gs = gs(args.g)
200
- args.gsp = gs(args.gp)
201
- args.gsr = gs(args.gr)
202
- }
203
- // for semantics
204
- args.addAssumedScoped(args, {})
205
-
206
- const getAPI = (uuid) => {
207
- if (config && config.getAPI) {
208
- return config.getAPI(uuid)
209
- }
210
- }
211
- const getAPIs = (uuid) => {
212
- if (config && config.getAPIs) {
213
- return config.getAPIs(uuid)
214
- }
215
- }
216
- args.getUUIDScoped = (uuid) => {
217
- return {
218
- api: getAPI(uuid),
219
- apis: getAPIs(uuid)
220
- }
221
- }
222
- config.getAddedArgs(args)
223
-
224
- Object.assign(args, args.getUUIDScoped(uuidForScoping || config.uuid))
225
- /*
226
- if (uuidForScoping) {
227
- Object.assign(args, args.getUUIDScoped(uuidForScoping))
228
- }
229
- */
230
- // sets args for all the API. that make a copy so the args must be fully setup by here except for scoped
231
- config.setArgs(args)
232
- }
233
-
234
- const gs = (g) => (contexts, separator, lastSeparator) => {
235
- if (!Array.isArray(contexts)) {
236
- debugger
237
- throw new Error('Expected a list')
238
- }
239
-
240
- let s = ''
241
- if (!separator) {
242
- separator = ' '
243
- }
244
- if (!lastSeparator) {
245
- lastSeparator = separator
246
- }
247
- let nextSeparator = ''
248
- for (let i = 0; i < contexts.length; ++i) {
249
- const context = contexts[i]
250
- const value = g(context)
251
- if (i > 0) {
252
- if (i === contexts.length - 1) {
253
- nextSeparator = lastSeparator
254
- } else {
255
- nextSeparator = separator
256
- }
257
- }
258
- s += nextSeparator + value
259
- }
260
- return s
261
- }
262
-
263
87
  const matching = (actual, expected) => {
264
88
  if (!deepEqual(stringify(sortJson(actual, { depth: 25 })), stringify(sortJson(expected, { depth: 25 })))) {
265
89
  return false
@@ -284,56 +108,18 @@ const analyzeMetaData = (right, wrong) => {
284
108
  return []
285
109
  }
286
110
 
287
- const processContexts = (contexts, params) => {
111
+ const processContexts = async (contexts, params) => {
288
112
  const contextsPrime = []
289
113
  const generated = []
290
114
  const logs = []
291
115
  for (const context of contexts) {
292
- const result = processContext(context, Object.assign({}, params, { logs }))
116
+ const result = await processContext(context, Object.assign({}, params, { logs }))
293
117
  contextsPrime.push(result.context)
294
118
  generated.push(result.generated)
295
119
  }
296
120
  return { contexts: contextsPrime, generated, logs }
297
121
  }
298
122
 
299
- const getObjects = (objects) => {
300
- return (uuid) => {
301
- if (objects && objects.namespaced) {
302
- return objects.namespaced[uuid]
303
- }
304
- return objects
305
- }
306
- }
307
-
308
- const processContext = (context, { objects = {}, config, logs = [] }) => {
309
- const generators = config.getGenerators(logs)
310
- const semantics = config.getSemantics(logs)
311
-
312
- // map to hash
313
- config = config || {}
314
- if (config.config) {
315
- config = config
316
- }
317
-
318
- const response = {} // NA but passed in
319
- // generators = new Generators(generators.map((g) => new Generator(normalizeGenerator(g))))
320
- // semantics = new Semantics(semantics.map((g) => new Semantic(normalizeSemantic(g))))
321
- const hierarchy = new DigraphInternal((config.config || {}).hierarchy || [])
322
-
323
- const args = { objects, response, getObjects: getObjects(objects) }
324
- setupArgs(args, config, logs, hierarchy)
325
-
326
- context = semantics.apply(args, context)
327
- const generated = generators.apply(args, context)
328
- const assumed = { paraphrase: true, response: false, isResponse: false }
329
- const paraphrases = generators.apply({ ...args, assumed }, context, { paraphrase: true, response: false, isResponse: false })
330
- let responses = []
331
- if (context.isResponse) {
332
- responses = generated
333
- }
334
- return { context, generated, paraphrases, responses }
335
- }
336
-
337
123
  const convertToStable = (objects) => {
338
124
  if (true) {
339
125
  return objects
@@ -425,136 +211,6 @@ const overlaps = (r1, context) => {
425
211
  return false
426
212
  }
427
213
 
428
- const setupContexts = (rawContexts) => {
429
- let first = true
430
- const contexts = []
431
- contexts.push({ marker: 'controlStart', controlRemove: true })
432
- for (const context of rawContexts) {
433
- if (first) {
434
- first = false
435
- } else {
436
- contexts.push({ marker: 'controlBetween', controlRemove: true })
437
- }
438
- contexts.push(context)
439
- }
440
- contexts.push({ marker: 'controlEnd', controlRemove: true })
441
- return contexts
442
- }
443
-
444
- const processContextsB = ({ config, hierarchy, semantics, generators, json, isTest, isInstance, instance, query, data, retries, url, commandLineArgs }) => {
445
- // TODO fix this name to contextsPrime
446
- const contextsPrime = []
447
- const generatedPrime = []
448
- const paraphrasesPrime = []
449
- const paraphrasesParenthesizedPrime = []
450
- const generatedParenthesizedPrime = []
451
- const responsesPrime = []
452
- const contexts = setupContexts(json.contexts)
453
-
454
- const objects = config.get('objects')
455
- const args = { objects, isResponse: true, response: json, isTest, isInstance, getObjects: getObjects(objects), instance }
456
- if (!json.logs) {
457
- json.logs = []
458
- }
459
- setupArgs(args, config, json.logs, hierarchy)
460
- const toDo = [...contexts]
461
- args.insert = (context) => toDo.unshift(context)
462
- let overlap, lastRange
463
- config.debugLoops = commandLineArgs && commandLineArgs.debugLoops
464
- while (toDo.length > 0) {
465
- const context = toDo.shift()
466
- args.calls.next()
467
- let contextPrime = context
468
- context.topLevel = true
469
- try {
470
- if (json.has_errors) {
471
- throw new Error('There are errors in the logs. Run with the -d flag and grep for Error')
472
- }
473
- const generateParenthesized = isTest || (commandLineArgs && commandLineArgs.save)
474
- if (!config.get('skipSemantics')) {
475
- const semantics = config.getSemantics(json.logs)
476
- try {
477
- contextPrime = semantics.apply(args, context)
478
- } catch (e) {
479
- if (e.message == 'Maximum call stack size exceeded') {
480
- const mostCalled = semantics.getMostCalled()
481
- e.message += `\nThe most called semantic was:\nnotes: ${mostCalled.notes}\nmatch: ${mostCalled.matcher.toString()}\napply: ${mostCalled._apply.toString()}\n`
482
- }
483
- // contextPrime = semantics.apply(args, { marker: 'error', context, error: e })
484
- if (isInstance) {
485
- console.log('error', e.error)
486
- }
487
- contextPrime = semantics.apply(args, {
488
- marker: 'error',
489
- context,
490
- text: e ? e.toString() : 'not available',
491
- reason: e.reason,
492
- error: e.stack || e.error
493
- })
494
- }
495
- }
496
- if (contextPrime.controlRemove) {
497
- continue
498
- }
499
- let assumed = { isResponse: true }
500
- const generated = contextPrime.isResponse ? config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed) : ''
501
- let generatedParenthesized = []
502
- if (generateParenthesized) {
503
- config.parenthesized = true
504
- generatedParenthesized = contextPrime.isResponse ? config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed) : ''
505
- config.parenthesized = false
506
- }
507
- // assumed = { paraphrase: true, response: false };
508
- assumed = { paraphrase: true, isResponse: false, response: false }
509
- if (generateParenthesized) {
510
- config.parenthesized = false
511
- }
512
- const paraphrases = config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed)
513
- let paraphrasesParenthesized = []
514
- if (generateParenthesized) {
515
- config.parenthesized = true
516
- paraphrasesParenthesized = config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed)
517
- config.parenthesized = false
518
- }
519
- contextsPrime.push(contextPrime)
520
- generatedPrime.push(generated)
521
- paraphrasesPrime.push(paraphrases)
522
- if (generateParenthesized) {
523
- paraphrasesParenthesizedPrime.push(paraphrasesParenthesized)
524
- generatedParenthesizedPrime.push(generatedParenthesized)
525
- }
526
- if (contextPrime.isResponse) {
527
- responsesPrime.push(generated)
528
- } else {
529
- responsesPrime.push('')
530
- }
531
-
532
- // add results to processed list
533
- config.config.objects.processed = config.config.objects.processed || []
534
- config.config.objects.processed = config.config.objects.processed.slice(0, 5)
535
- config.config.objects.processed.unshift({ context: contextPrime, paraphrases: paraphrases, paraphrasesParenthesized, generatedParenthesized, responses: responsesPrime })
536
- } catch (e) {
537
- if (Array.isArray(e)) {
538
- e = {
539
- errors: e
540
- }
541
- }
542
- e.context = contextPrime
543
- if (e.logs) {
544
- e.logs = e.logs.concat(json.logs)
545
- } else {
546
- e.logs = json.logs
547
- }
548
- e.metadata = json.metadata
549
- if (json.trace) {
550
- e.trace = json.trace
551
- }
552
- throw e
553
- }
554
- }
555
- return { contextsPrime, generatedPrime, paraphrasesPrime, paraphrasesParenthesizedPrime, generatedParenthesizedPrime, responsesPrime }
556
- }
557
-
558
214
  const doWithRetries = async (n, url, queryParams, data) => {
559
215
  if (!queryParams) {
560
216
  queryParams = ''
@@ -589,93 +245,6 @@ const doWithRetries = async (n, url, queryParams, data) => {
589
245
  }
590
246
  }
591
247
 
592
- const setupProcessB = ({ config, initializer, allowDelta = false } = {}) => {
593
- const key = config._key
594
-
595
- const data = Object.assign({ key, version: '3' }, { uuid: config._uuid })
596
- if (allowDelta && config.allowDelta && config.hasDelta()) {
597
- // console.log('config', config)
598
- data.delta = config.delta()
599
- } else {
600
- config.toData(data)
601
- // Object.assign(data, config.config)
602
- }
603
-
604
- // config.toServer(data)
605
-
606
- if (data.namespaces) {
607
- for (const uuid of Object.keys(data.namespaces)) {
608
- const km = config.configs.find((km) => km.uuid === uuid)
609
- data.namespaces[uuid].name = km.name
610
- }
611
- }
612
-
613
- // const generators = new Generators((data.generators || []).map((g) => new Generator(normalizeGenerator(g))))
614
- delete data.generators
615
- // const semantics = new Semantics((data.semantics || []).map((g) => new Semantic(normalizeSemantic(g))))
616
- delete data.semantics
617
- const hierarchy = new DigraphInternal((config.config || {}).hierarchy || [])
618
-
619
- return {
620
- data,
621
- // generators,
622
- // semantics,
623
- hierarchy
624
- }
625
- }
626
-
627
- // instance template loadTemplate
628
- const loadInstance = (config, instance) => {
629
- const transitoryMode = global.transitoryMode
630
- global.transitoryMode = false
631
-
632
- if (instance && (instance.associations || instance.learned_contextual_priorities)) {
633
- if (!config.config.retrain) {
634
- if (instance.associations) {
635
- config.addAssociations(instance.associations)
636
- }
637
- if (instance.learned_contextual_priorities && instance.learned_contextual_priorities.length > 0) {
638
- config.addPriorities(instance.learned_contextual_priorities)
639
- }
640
- }
641
- }
642
-
643
- const { /* data, generators, semantics, */ hierarchy } = setupProcessB({ config })
644
- // for (const results of (instance.resultss || [])) {
645
- for (const i in (instance.resultss || [])) {
646
- const results = instance.resultss[i]
647
- if (results.extraConfig) {
648
- // config.addInternal(results, useOldVersion = true, skipObjects = false, includeNamespaces = true, allowNameToBeNull = false)
649
- const uuid = config.nameToUUID(instance.name)
650
- // used to do a CLONE
651
- config.addInternal(instance.template.configs[i], { uuid, addFirst: true, handleCalculatedProps: true })
652
- } else if (results.apply) {
653
- const objects = config.get('objects')
654
- const args = { objects, getObjects: getObjects(objects) }
655
- if (instance.configs) {
656
- args.isInstance = `instance${i}`
657
- args.instance = instance.configs[i]
658
- }
659
-
660
- const uuid = config.nameToUUID(instance.name)
661
- setupArgs(args, config, config.logs, hierarchy, uuid)
662
- results.apply(args)
663
- } else {
664
- if (results.skipSemantics) {
665
- config.config.skipSemantics = results.skipSemantics
666
- }
667
- const args = { config, hierarchy, json: results, commandLineArgs: {} }
668
- args.isInstance = `instance${i}`
669
- args.instance = ''
670
- processContextsB(args)
671
- if (results.skipSemantics) {
672
- config.config.skipSemantics = null
673
- }
674
- }
675
- }
676
- global.transitoryMode = transitoryMode
677
- }
678
-
679
248
  const throwErrorHandler = (error) => {
680
249
  throw error
681
250
  }
@@ -692,7 +261,7 @@ const _process = async (config, query, { initializer, commandLineArgs, credentia
692
261
  // ensure same start state
693
262
  try {
694
263
  if (writeTests) {
695
- config.rebuild()
264
+ await config.rebuild()
696
265
  const objects = getObjects(config.config.objects)(config.uuid)
697
266
  }
698
267
  } catch (error) {
@@ -728,12 +297,14 @@ const _process = async (config, query, { initializer, commandLineArgs, credentia
728
297
  associations: []
729
298
  }
730
299
 
300
+ let startCounter = 0
731
301
  while (true) {
732
302
  if (queries.length === 0) {
733
303
  break
734
304
  }
735
305
 
736
306
  data.utterance = queries[0]
307
+ data.start_counter = startCounter
737
308
  let json = await doWithRetries(retries, url, queryParams, data)
738
309
  let resetData = false
739
310
  if (json.code == 'NOT_IN_CACHE') {
@@ -755,6 +326,7 @@ const _process = async (config, query, { initializer, commandLineArgs, credentia
755
326
  }
756
327
  }
757
328
  json.contexts = json.results
329
+ startCounter= json.end_counter + 1
758
330
  delete json.results
759
331
  if (json.status !== 200) {
760
332
  throw json
@@ -764,7 +336,7 @@ const _process = async (config, query, { initializer, commandLineArgs, credentia
764
336
  start = runtime.performance.performance.now()
765
337
  }
766
338
  const { contextsPrime, generatedPrime, paraphrasesPrime, paraphrasesParenthesizedPrime, generatedParenthesizedPrime, responsesPrime } =
767
- processContextsB({ isTest, config, hierarchy, json, commandLineArgs /*, generators, semantics */ })
339
+ await processContextsB({ isTest, rebuildingTemplate, config, hierarchy, json, commandLineArgs /*, generators, semantics */ })
768
340
  if (isTest) {
769
341
  end = runtime.performance.performance.now()
770
342
  clientSideTime = end - start
@@ -792,6 +364,7 @@ const _process = async (config, query, { initializer, commandLineArgs, credentia
792
364
  response.generatedParenthesized = response.generatedParenthesized.concat(generatedParenthesizedPrime)
793
365
  response.responses = response.responses.concat(responsesPrime)
794
366
  queries = queries.slice(1)
367
+
795
368
  }
796
369
  }
797
370
 
@@ -819,7 +392,6 @@ const getConfigForTest = (config, testConfig) => {
819
392
  }
820
393
  const configForTest = {}
821
394
  for (const key of Object.keys(includes)) {
822
- // configForTest[key] = config.config[key]
823
395
  if (key === 'words') {
824
396
  const words = config.config.words
825
397
  configForTest.words = {
@@ -829,7 +401,14 @@ const getConfigForTest = (config, testConfig) => {
829
401
  }
830
402
 
831
403
  const literals = config.config.words.literals
404
+ let includesWord = (word) => true
405
+ if (Array.isArray(includes.words)) {
406
+ includesWord = (word) => includes.words.includes(word)
407
+ }
832
408
  for (const key in literals) {
409
+ if (!includesWord(key)) {
410
+ continue
411
+ }
833
412
  const defs = []
834
413
  for (const def of literals[key]) {
835
414
  // TODO handle thie uuids the right way
@@ -838,15 +417,23 @@ const getConfigForTest = (config, testConfig) => {
838
417
  configForTest.words.literals[key] = defs
839
418
  }
840
419
 
841
- const patterns = config.config.words.patterns
420
+ const patterns = config.config.words.patterns || []
842
421
  configForTest.words.patterns = patterns.map((pattern) => Object.assign({}, pattern, { uuid: undefined }))
843
422
 
844
- const hierarchy = config.config.words.hierarchy
423
+ const hierarchy = config.config.words.hierarchy || []
845
424
  configForTest.words.hierarchy = hierarchy.map((hierarchy) => Object.assign({}, hierarchy, { uuid: undefined }))
846
425
  } else if (key === 'operators') {
847
- configForTest.operators = config.config.operators.map((operator) => Object.assign({}, operator, { uuid: undefined }))
426
+ let include = (operator) => true
427
+ if (Array.isArray(includes.operators)) {
428
+ include = (operator) => includes.operators.includes(operator.pattern)
429
+ }
430
+ configForTest.operators = config.config.operators.filter( include ).map((operator) => Object.assign({}, operator, { uuid: undefined }))
848
431
  } else if (key === 'bridges') {
849
- configForTest.bridges = config.config.bridges.map((bridge) => Object.assign({}, bridge, { uuid: undefined }))
432
+ let include = (operator) => true
433
+ if (Array.isArray(includes.bridges)) {
434
+ include = (bridge) => includes.bridges.includes(bridge.id)
435
+ }
436
+ configForTest.bridges = config.config.bridges.filter(include).map((bridge) => Object.assign({}, bridge, { uuid: undefined }))
850
437
  } else {
851
438
  configForTest[key] = config.config[key]
852
439
  }
@@ -856,8 +443,12 @@ const getConfigForTest = (config, testConfig) => {
856
443
 
857
444
  const runTest = async (config, expected, { args, verbose, testConfig, debug }) => {
858
445
  const test = expected.query
446
+ if (args.query && args.query != test) {
447
+ // no run this
448
+ return
449
+ }
859
450
  // initialize in between test so state is not preserved since the test was adding without state
860
- config.rebuild()
451
+ await config.rebuild()
861
452
  const errorHandler = (error) => {
862
453
  if (error.metadata) {
863
454
  const priorities = analyzeMetaData(expected.metadata, error.metadata)
@@ -1003,7 +594,7 @@ const runTests = async (config, testFile, juicyBits) => {
1003
594
  }
1004
595
 
1005
596
  const saveTest = async (testFile, config, test, expected, testConfig, saveDeveloper) => {
1006
- config.rebuild()
597
+ await config.rebuild()
1007
598
  const objects = getObjects(config.config.objects)(config.uuid)
1008
599
  console.log(test)
1009
600
  const result = await _process(config, test, { isTest: true })
@@ -1024,11 +615,11 @@ const saveTestsHelper = async (testFile, config, tests, todo, testConfig, saveDe
1024
615
  return
1025
616
  }
1026
617
  const test = todo.pop()
1027
- config.rebuild()
618
+ await config.rebuild()
1028
619
  const result = await saveTest(testFile, config, test, tests[test], testConfig, saveDeveloper)
1029
620
  // initialize in between test so state is not preserved since the test was adding without state
1030
621
  // config.initialize({force: true})
1031
- config.rebuild()
622
+ await config.rebuild()
1032
623
  return saveTestsHelper(testFile, config, tests, todo, testConfig, saveDeveloper)
1033
624
  }
1034
625
 
@@ -1315,6 +906,7 @@ const rebuildTemplate = async ({ config, target, previousResultss, startOfChange
1315
906
  associations: [],
1316
907
  learned_contextual_priorities: []
1317
908
  }
909
+ config.fragmentsBeingBuilt = []
1318
910
  const looper = async (configs) => {
1319
911
  if (configs.length === 0) {
1320
912
  finish()
@@ -1322,14 +914,15 @@ const rebuildTemplate = async ({ config, target, previousResultss, startOfChange
1322
914
  }
1323
915
  const { property, hierarchy, query: queryOrExtraConfig, previousResults, initializer, skipSemantics } = configs.shift()
1324
916
  // queries are strings or { query: "blah", development: true/false }
1325
- if (typeof queryOrExtraConfig === 'string' || queryOrExtraConfig.query) {
917
+ if (typeof queryOrExtraConfig === 'string' || queryOrExtraConfig.query || queryOrExtraConfig.isFragment) {
1326
918
  let query = queryOrExtraConfig
919
+ let isFragment = queryOrExtraConfig.isFragment
1327
920
  if (typeof queryOrExtraConfig === 'string') {
1328
921
  query = { query }
1329
922
  }
1330
- config.config.skipSemantics = skipSemantics
923
+ config.config.skipSemantics = skipSemantics && !isFragment
1331
924
  const transitoryMode = global.transitoryMode
1332
- if (property == 'fragments') {
925
+ if (isFragment || property == 'fragments') {
1333
926
  global.transitoryMode = true
1334
927
  }
1335
928
  if (hierarchy) {
@@ -1347,7 +940,7 @@ const rebuildTemplate = async ({ config, target, previousResultss, startOfChange
1347
940
  if (previousResults && previousResults.query == query.query) {
1348
941
  results = previousResults
1349
942
  prMessage = ' Using previous results. use -rtf for a hard rebuild of everything on the server side.'
1350
- loadInstance(config, { resultss: [results] })
943
+ await loadInstance(config, { resultss: [results] })
1351
944
  } else {
1352
945
  results = await _process(config, query.query, { initializer, rebuildingTemplate: true })
1353
946
  }
@@ -1358,18 +951,22 @@ const rebuildTemplate = async ({ config, target, previousResultss, startOfChange
1358
951
  if (results.contexts.length > 1) {
1359
952
  console.log(`query "${query.query}". There is ${results.contexts.length} contexts in the results. Make sure its producing the results that you expect.`)
1360
953
  throw new Error(`query "${query.query}". There is ${results.contexts.length} contexts in the results. Make sure its producing the results that you expect.`)
1361
- } else if (results.paraphrases[0] != query.query) {
954
+ } else if (results.paraphrases[0].toLowerCase() !== query.query.toLowerCase()) {
1362
955
  console.log(`query "${query.query}". The paraphrase is different from the query "${results.paraphrases[0]}".${prMessage}`)
1363
956
  } else {
1364
- console.log(`query "${query.query}".${prMessage}`)
957
+ console.log(`query ${isFragment ? 'fragment' : ''}"${query.query}".${prMessage}`)
1365
958
  }
1366
959
  global.transitoryMode = transitoryMode
1367
960
  config.config.skipSemantics = null
1368
961
  results.query = query.query
962
+ results.isFragment = isFragment
1369
963
  results.skipSemantics = skipSemantics
1370
964
  results.development = query.development
1371
965
  results.key = { query: query.query, hierarchy }
1372
966
  accumulators[property].push(results)
967
+ if (isFragment) {
968
+ config.fragmentsBeingBuilt.push({ query: query.query, contexts: results.contexts })
969
+ }
1373
970
  accumulators.associations = accumulators.associations.concat(results.associations)
1374
971
  accumulators.learned_contextual_priorities = accumulators.learned_contextual_priorities.concat(results.learned_contextual_priorities)
1375
972
  await looper(configs)
@@ -1383,8 +980,8 @@ const rebuildTemplate = async ({ config, target, previousResultss, startOfChange
1383
980
  const initFunction = queryOrExtraConfig
1384
981
  const objects = config.get('objects')
1385
982
  const args = { objects, getObjects: getObjects(objects) }
1386
- setupArgs(args, config, config.logs, hierarchy)
1387
- initFunction(args)
983
+ setupArgs(args, config, config.logs, config.hierarchy)
984
+ await initFunction(args)
1388
985
  accumulators[property].push({ apply: queryOrExtraConfig })
1389
986
  await looper(configs)
1390
987
  } else {
@@ -1408,6 +1005,7 @@ const rebuildTemplate = async ({ config, target, previousResultss, startOfChange
1408
1005
  }
1409
1006
 
1410
1007
  const finish = () => {
1008
+ config.fragmentsBeingBuilt = []
1411
1009
  const instanceName = `${target}.instance.json`
1412
1010
  console.log(`Writing instance file ${instanceName}`)
1413
1011
  const stabilizeAssociations = (associations) => {
@@ -1496,11 +1094,16 @@ const checkTest = (testConfig) => {
1496
1094
  }
1497
1095
 
1498
1096
  const knowledgeModuleImpl = async ({
1097
+ includes,
1098
+ config : configStruct,
1099
+ api,
1100
+ initializer,
1101
+ terminator,
1102
+ multiApiInitializer,
1103
+
1499
1104
  module: moduleFromJSFile,
1500
1105
  description,
1501
1106
  section,
1502
- // config, createConfig,
1503
- createConfig,
1504
1107
  newWay,
1505
1108
  demo,
1506
1109
  test,
@@ -1508,7 +1111,6 @@ const knowledgeModuleImpl = async ({
1508
1111
  errorHandler = defaultErrorHandler,
1509
1112
  process: processResults = defaultProcess,
1510
1113
  stopAtFirstFailure = true,
1511
- acceptsAdditionalConfig = false,
1512
1114
  ...rest
1513
1115
  } = {}) => {
1514
1116
  const unknownArgs = Object.keys(rest)
@@ -1521,10 +1123,29 @@ const knowledgeModuleImpl = async ({
1521
1123
  if (!moduleFromJSFile) {
1522
1124
  throw new Error("'module' is a required parameter. The value should be either 'module' or a lambda that will be called when the file is acting as a module.")
1523
1125
  }
1524
- // if (!config && !createConfig) {
1525
- if (!createConfig) {
1126
+
1127
+ if (!configStruct) {
1526
1128
  throw new Error("'config' or 'createConfig' is a required parameter. The value should the config that defines the knowledge module.")
1527
1129
  }
1130
+
1131
+ const createConfig = async () => {
1132
+ const config = new Config(configStruct, moduleFromJSFile, _process)
1133
+ config.setTerminator(terminator)
1134
+ config.stop_auto_rebuild()
1135
+ await config.add(...(includes || []))
1136
+ if (api) {
1137
+ config.setApi(api)
1138
+ }
1139
+ if (multiApiInitializer) {
1140
+ await config.setMultiApi(multiApiInitializer)
1141
+ }
1142
+ if (initializer) {
1143
+ config.initializer(initializer)
1144
+ }
1145
+ await config.restart_auto_rebuild()
1146
+ return config
1147
+ }
1148
+
1528
1149
  if (!description) {
1529
1150
  throw new Error("'description' is a required parameter. The value should the description of the knowledge module.")
1530
1151
  }
@@ -1557,525 +1178,562 @@ const knowledgeModuleImpl = async ({
1557
1178
  }
1558
1179
 
1559
1180
  if (isProcess) {
1560
- const config = createConfig()
1561
- setupConfig(config)
1562
- processResults = processResults({ config, errorHandler })
1563
- // setup();
1564
- const parser = new runtime.ArgumentParser({
1565
- description: 'Entodicton knowledge module'
1566
- })
1181
+ let config
1182
+ try {
1183
+ const parser = new runtime.ArgumentParser({
1184
+ description: 'Entodicton knowledge module'
1185
+ })
1567
1186
 
1568
- const helpDebugAssociation = 'In order to get a debug break when a specific association is created set the DEBUG_ASSOCIATION environment variable to the JSON of the association to break on. For example DEBUG_ASSOCIATION=\'[["the", 0], ["mammal", 1]]\''
1569
- const helpDebugHierarchy = 'In order to get a debug break when a specific hierarchy is created set the DEBUG_HIERARCHY environment variable to the JSON of the child-parent pair to break on. For example DEBUG_HIERARCHY=\'[["cat", 1], ["mammel", 1]]\''
1570
- const helpDebugPriority = 'In order to get a debug break when a specific set of priorities is created set set DEBUG_PRIORITY environment variable to the JSON of the priorities that you want to break on. For example DEBUG_PRIORITY=\'[["verb", 0], ["article", 0]]\''
1571
- const helpDebugContextualPriority = 'In order to get a debug break when a specific set of contextual priorities is created set set DEBUG_CONTEXTUAL_PRIORITY environment variable to the JSON of the priorities that you want to break on. For example DEBUG_CONTEXTUAL_PRIORITY=\'{ context: [["verb", 0], ["article", 0], select: 1}\''
1572
- const helpDebugBridge = 'In order to get a debug break when a specific bridge is created set the DEBUG_BRIDGE environment variable to id/level to break on. For example DEBUG_BRIDGE=\'id#level\''
1573
- const helpDebugOperator = 'In order to get a debug break when a specific hierarcy is created set the DEBUG_OPERATOR environment variable to debug any config loaded. For example DEBUG_OPERATOR=\'([operator] ([arg]))\''
1574
-
1575
- parser.add_argument('-tmn', '--testModuleName', { help: 'When running tests instead of using the current modules tests use the specified modules tests' })
1576
- parser.add_argument('-t', '--test', { action: 'store_true', help: 'Run the tests. Create tests by running with the --query + --save flag' })
1577
- parser.add_argument('-tv', '--testVerbose', { action: 'store_true', help: 'Run the tests in verbose mode. Create tests by running with the --query or --loop with the --save flag' })
1578
- // parser.add_argument('-ttr', '--testToRun', { help: 'Only the specified test will be run' })
1579
- parser.add_argument('-tva', '--testAllVerbose', { action: 'store_true', help: 'Run the tests in verbose mode. All the tests will be run instead of stopping at first failure. Create tests by running with the --query or --loop with the --save flag' })
1580
- parser.add_argument('-tnp', '--testNoParenthesized', { action: 'store_true', help: 'Don\' check parenthesized differences for the tests' })
1581
- parser.add_argument('-n', '--count', { help: 'Number of times to run the tests. Default is one. Use this to check for flakey test. If possible the system will print out a message with the word "hint" suggesting how to fix the problem' })
1582
- // parser.add_argument('-b', '--build', { help: 'Specify the template file name of the form <kmName>. There should be a file called <baseKmName>.<kmName>.template.json with the queries to run. For example { queries: [...] }. The template file will be run and generate an instantiation called <baseKmName>.<kmName>.instance.json and a file called <kmName>.js that will load the template file (this is file generated only if not already existing) and a test file called <KmName>.tests.json. This can then be loaded into an instance of the current knowledge module to setup initial conditions.' })
1583
- parser.add_argument('-rt', '--rebuildTemplate', { action: 'store_true', help: 'Force a template rebuild. Using optimization where if the query/config has not changed it will use the previous value. One there is a change all subsequence query/configs will be run.' })
1584
- parser.add_argument('-rtf', '--rebuildTemplateFull', { action: 'store_true', help: 'Force a template rebuild. Skip the optimization' })
1585
- parser.add_argument('-l', '--loop', { action: 'store_true', help: 'Run a loop so that multiply queries may be run' })
1586
- parser.add_argument('-i', '--info', { action: 'store_true', help: 'Print meta-data for the module' })
1587
- parser.add_argument('-v', '--vimdiff', { action: 'store_true', help: 'For failures run vimdiff' })
1588
- parser.add_argument('-g', '--greg', { action: 'store_true', help: 'Set the server to be localhost so I can debug stuff' })
1589
- parser.add_argument('-cl', '--checkForLoop', { nargs: '?', help: 'Check for loops in the priorities, Optional argument is list of operator keys to consider. For example [["banana", 0], ["food", 1]]' })
1590
- parser.add_argument('-r', '--reset', { action: 'store_true', help: 'Get the server to bypass the cache and rebuild everything' })
1591
- parser.add_argument('-q', '--query', { help: 'Run the specified query' })
1592
- parser.add_argument('-ip ', '--server', { help: 'Server to run against' })
1593
- parser.add_argument('-qp ', '--queryParams', { help: 'Query params for the server call' })
1594
- parser.add_argument('-dt', '--deleteTest', { help: 'Delete the specified query from the tests file.' })
1595
- parser.add_argument('--parenthesized', { action: 'store_true', help: 'Show the generated phrases with parenthesis.' })
1596
- parser.add_argument('-c', '--clean', { help: 'Remove data from the test files. a === association' })
1597
- parser.add_argument('-od', '--objectDiff', { action: 'store_true', help: 'When showing the objects use a colour diff' })
1598
- parser.add_argument('-p', '--print', { help: 'Print the specified elements c === config, w === words, b === bridges, o === operators d === objects (d for data), h === hierarchy, g === generators, s === semantics, l === load t=tests ordering p === priorities a == associations j == JSON sent to server. for example --print wb' })
1599
- parser.add_argument('-s', '--save', { action: 'store_true', help: 'When running with the --query flag this will save the current run to the test file. When running without the --query flag all tests will be run and resaved.' })
1600
- parser.add_argument('-sd', '--saveDeveloper', { action: 'store_true', help: 'Same as -s but the query will not show up in the info command.' })
1601
- parser.add_argument('-dl', '--debugLoops', { action: 'store_true', help: 'When running with the --debugLoops flag the logs calls to semantics and generators will be immediately written to the console ' })
1602
- parser.add_argument('-d', '--debug', { action: 'store_true', help: 'When running with the --debug flag this set the debug flag in the config' })
1603
- parser.add_argument('-da', '--debugAssociation', { action: 'store_true', help: helpDebugAssociation })
1604
- parser.add_argument('-dh', '--debugHierarchy', { action: 'store_true', help: helpDebugHierarchy })
1605
- parser.add_argument('-dp', '--debugPriority', { action: 'store_true', help: helpDebugPriority })
1606
- parser.add_argument('-dcp', '--debugContextualPriority', { action: 'store_true', help: helpDebugContextualPriority })
1607
- parser.add_argument('-db', '--debugBridge', { action: 'store_true', help: helpDebugBridge })
1608
- parser.add_argument('-do', '--debugOperator', { action: 'store_true', help: helpDebugOperator })
1609
- parser.add_argument('-ep', '--explainPriorities', { action: 'store_true', help: 'The server will return all priorities including the generated one along with an explanation of there they came from' })
1610
- parser.add_argument('-dic', '--debugIncludeConvolutions', { nargs: '?', help: 'When running with the --debugIncludeConvolutions flag the logs will include convolutions which are somewhat annoyingly verbose. Default is false' })
1611
-
1612
- const args = parser.parse_args()
1613
- args.count = args.count || 1
1614
-
1615
- if (args.rebuildTemplateFull) {
1616
- args.rebuildTemplate = true
1617
- }
1187
+ const helpDebugWord = 'In order to get a debug break when a specific word is created set the DEBUG_WORD environment variable to the JSON of the association to break on. For example DEBUG_WORD=\'"the"\''
1188
+ const helpDebugAssociation = 'In order to get a debug break when a specific association is created set the DEBUG_ASSOCIATION environment variable to the JSON of the association to break on. For example DEBUG_ASSOCIATION=\'[["the", 0], ["mammal", 1]]\''
1189
+ const helpDebugHierarchy = 'In order to get a debug break when a specific hierarchy is created set the DEBUG_HIERARCHY environment variable to the JSON of the child-parent pair to break on. For example DEBUG_HIERARCHY=\'[["cat", 1], ["mammel", 1]]\''
1190
+ const helpDebugPriority = 'In order to get a debug break when a specific set of priorities is created set set DEBUG_PRIORITY environment variable to the JSON of the priorities that you want to break on. For example DEBUG_PRIORITY=\'[["verb", 0], ["article", 0]]\''
1191
+ const helpDebugContextualPriority = 'In order to get a debug break when a specific set of contextual priorities is created set set DEBUG_CONTEXTUAL_PRIORITY environment variable to the JSON of the priorities that you want to break on. For example DEBUG_CONTEXTUAL_PRIORITY=\'{ context: [["verb", 0], ["article", 0], select: 1}\''
1192
+ const helpDebugBridge = 'In order to get a debug break when a specific bridge is created set the DEBUG_BRIDGE environment variable to id to break on. For example DEBUG_BRIDGE=\'car\''
1193
+ const helpDebugOperator = 'In order to get a debug break when a specific hierarcy is created set the DEBUG_OPERATOR environment variable to debug any config loaded. For example DEBUG_OPERATOR=\'([operator] ([arg]))\''
1194
+
1195
+ parser.add_argument('-tmn', '--testModuleName', { help: 'When running tests instead of using the current modules tests use the specified modules tests' })
1196
+ parser.add_argument('-t', '--test', { action: 'store_true', help: 'Run the tests. Create tests by running with the --query + --save flag' })
1197
+ parser.add_argument('-tv', '--testVerbose', { action: 'store_true', help: 'Run the tests in verbose mode. Create tests by running with the --query or --loop with the --save flag' })
1198
+ // parser.add_argument('-ttr', '--testToRun', { help: 'Only the specified test will be run' })
1199
+ parser.add_argument('-tva', '--testAllVerbose', { action: 'store_true', help: 'Run the tests in verbose mode. All the tests will be run instead of stopping at first failure. Create tests by running with the --query or --loop with the --save flag. if -q is specified the tests will be run for just the specified query.' })
1200
+ parser.add_argument('-tnp', '--testNoParenthesized', { action: 'store_true', help: 'Don\' check parenthesized differences for the tests' })
1201
+ parser.add_argument('-n', '--count', { help: 'Number of times to run the tests. Default is one. Use this to check for flakey test. If possible the system will print out a message with the word "hint" suggesting how to fix the problem' })
1202
+ // parser.add_argument('-b', '--build', { help: 'Specify the template file name of the form <kmName>. There should be a file called <baseKmName>.<kmName>.template.json with the queries to run. For example { queries: [...] }. The template file will be run and generate an instantiation called <baseKmName>.<kmName>.instance.json and a file called <kmName>.js that will load the template file (this is file generated only if not already existing) and a test file called <KmName>.tests.json. This can then be loaded into an instance of the current knowledge module to setup initial conditions.' })
1203
+ parser.add_argument('-rt', '--rebuildTemplate', { action: 'store_true', help: 'Force a template rebuild. Using optimization where if the query/config has not changed it will use the previous value. One there is a change all subsequence query/configs will be run.' })
1204
+ parser.add_argument('-rtf', '--rebuildTemplateFull', { action: 'store_true', help: 'Force a template rebuild. Skip the optimization' })
1205
+ parser.add_argument('-l', '--loop', { action: 'store_true', help: 'Run a loop so that multiply queries may be run' })
1206
+ parser.add_argument('-i', '--info', { action: 'store_true', help: 'Print meta-data for the module' })
1207
+ parser.add_argument('-v', '--vimdiff', { action: 'store_true', help: 'For failures run vimdiff' })
1208
+ parser.add_argument('-g', '--greg', { action: 'store_true', help: 'Set the server to be localhost so I can debug stuff' })
1209
+ parser.add_argument('-cl', '--checkForLoop', { nargs: '?', help: 'Check for loops in the priorities, Optional argument is list of operator keys to consider. For example [["banana", 0], ["food", 1]]' })
1210
+ parser.add_argument('-r', '--reset', { action: 'store_true', help: 'Get the server to bypass the cache and rebuild everything' })
1211
+ parser.add_argument('-q', '--query', { help: 'Run the specified query' })
1212
+ parser.add_argument('-ip ', '--server', { help: 'Server to run against' })
1213
+ parser.add_argument('-qp ', '--queryParams', { help: 'Query params for the server call' })
1214
+ parser.add_argument('-dt', '--deleteTest', { help: 'Delete the specified query from the tests file.' })
1215
+ parser.add_argument('--parenthesized', { action: 'store_true', help: 'Show the generated phrases with parenthesis.' })
1216
+ parser.add_argument('-c', '--clean', { help: 'Remove data from the test files. a === association' })
1217
+ parser.add_argument('-od', '--objectDiff', { action: 'store_true', help: 'When showing the objects use a colour diff' })
1218
+ parser.add_argument('-p', '--print', { help: 'Print the specified elements c === config, w === words, b === bridges, o === operators d === objects (d for data), h === hierarchy, g === generators, s === semantics, l === load t=tests ordering p === priorities a == associations j == JSON sent to server. for example --print wb' })
1219
+ parser.add_argument('-s', '--save', { action: 'store_true', help: 'When running with the --query flag this will save the current run to the test file. When running without the --query flag all tests will be run and resaved.' })
1220
+ parser.add_argument('-sd', '--saveDeveloper', { action: 'store_true', help: 'Same as -s but the query will not show up in the info command.' })
1221
+ parser.add_argument('-dl', '--debugLoops', { action: 'store_true', help: 'When running with the --debugLoops flag the logs calls to semantics and generators will be immediately written to the console ' })
1222
+ parser.add_argument('-d', '--debug', { action: 'store_true', help: 'When running with the --debug flag this set the debug flag in the config' })
1223
+ parser.add_argument('-da', '--debugAssociation', { action: 'store_true', help: helpDebugAssociation })
1224
+ parser.add_argument('-dw', '--debugWord', { action: 'store_true', help: helpDebugWord })
1225
+ parser.add_argument('-dh', '--debugHierarchy', { action: 'store_true', help: helpDebugHierarchy })
1226
+ parser.add_argument('-dp', '--debugPriority', { action: 'store_true', help: helpDebugPriority })
1227
+ parser.add_argument('-dcp', '--debugContextualPriority', { action: 'store_true', help: helpDebugContextualPriority })
1228
+ parser.add_argument('-db', '--debugBridge', { action: 'store_true', help: helpDebugBridge })
1229
+ parser.add_argument('-do', '--debugOperator', { action: 'store_true', help: helpDebugOperator })
1230
+ parser.add_argument('-ep', '--explainPriorities', { action: 'store_true', help: 'The server will return all priorities including the generated one along with an explanation of there they came from' })
1231
+ parser.add_argument('-dic', '--debugIncludeConvolutions', { nargs: '?', help: 'When running with the --debugIncludeConvolutions flag the logs will include convolutions which are somewhat annoyingly verbose. Default is false' })
1232
+
1233
+ const args = parser.parse_args()
1234
+ args.count = args.count || 1
1235
+
1236
+ if (args.rebuildTemplateFull) {
1237
+ args.rebuildTemplate = true
1238
+ }
1239
+
1240
+ config = await createConfig()
1241
+
1242
+ // dont debug the load of the KM's if rebuild template is on since we want to debug the template rebuild not the load
1243
+ if (args.rebuildTemplate) {
1244
+ global.pauseDebugging = true
1245
+ }
1618
1246
 
1619
- if (args.parenthesized) {
1620
- config.parenthesized = true
1621
- }
1622
- if (args.checkForLoop) {
1623
- try {
1624
- args.checkForLoop = JSON.parse(args.checkForLoop)
1625
- const isKey = (what) => {
1626
- if (!Array.isArray(what)) {
1627
- return false
1628
- }
1629
- if (what.length !== 2) {
1630
- return false
1631
- }
1632
- if (!typeof what[0] == 'string') {
1633
- return false
1247
+ setupConfig(config)
1248
+ processResults = processResults({ config, errorHandler })
1249
+
1250
+ if (args.rebuildTemplate) {
1251
+ global.pauseDebugging = false
1252
+ }
1253
+
1254
+ // setup();
1255
+
1256
+ if (args.parenthesized) {
1257
+ config.parenthesized = true
1258
+ }
1259
+ if (args.checkForLoop) {
1260
+ try {
1261
+ args.checkForLoop = JSON.parse(args.checkForLoop)
1262
+ const isKey = (what) => {
1263
+ if (!Array.isArray(what)) {
1264
+ return false
1265
+ }
1266
+ if (what.length !== 2) {
1267
+ return false
1268
+ }
1269
+ if (!typeof what[0] == 'string') {
1270
+ return false
1271
+ }
1272
+ if (!typeof what[1] == 'number') {
1273
+ return false
1274
+ }
1275
+ return true
1634
1276
  }
1635
- if (!typeof what[1] == 'number') {
1636
- return false
1277
+ if (!Array.isArray(args.checkForLoop) || args.checkForLoop.some((value) => !isKey(value))) {
1278
+ throw new Error('Error for the checkForLoop argument. Expected a JSON array of operator keys of the form "[<id>, <level>]"')
1637
1279
  }
1638
- return true
1639
- }
1640
- if (!Array.isArray(args.checkForLoop) || args.checkForLoop.some((value) => !isKey(value))) {
1280
+ } catch (e) {
1641
1281
  throw new Error('Error for the checkForLoop argument. Expected a JSON array of operator keys of the form "[<id>, <level>]"')
1642
1282
  }
1643
- } catch (e) {
1644
- throw new Error(`Error parsing JSON of the checkForLoop argument. ${e}`)
1283
+ } else {
1284
+ if (process.argv.includes('--checkForLoop') || process.argv.includes('-cl')) {
1285
+ args.checkForLoop = true
1286
+ }
1645
1287
  }
1646
- } else {
1647
- if (process.argv.includes('--checkForLoop') || process.argv.includes('-cl')) {
1648
- args.checkForLoop = true
1288
+ if (args.debugAssociation) {
1289
+ console.log(helpDebugAssociation)
1290
+ runtime.process.exit(-1)
1291
+ }
1292
+ if (args.debugWord) {
1293
+ console.log(helpDebugWord)
1294
+ runtime.process.exit(-1)
1295
+ }
1296
+ if (args.debugHierarchy) {
1297
+ console.log(helpDebugHierarchy)
1298
+ runtime.process.exit(-1)
1299
+ }
1300
+ if (args.debugPriority) {
1301
+ console.log(helpDebugPriority)
1302
+ runtime.process.exit(-1)
1303
+ }
1304
+ if (args.debugBridge) {
1305
+ console.log(helpDebugBridge)
1306
+ runtime.process.exit(-1)
1307
+ }
1308
+ if (args.debugOperator) {
1309
+ console.log(helpDebugOperator)
1310
+ runtime.process.exit(-1)
1649
1311
  }
1650
- }
1651
- if (args.debugAssociation) {
1652
- console.log(helpDebugAssociation)
1653
- runtime.process.exit(-1)
1654
- }
1655
- if (args.debugHierarchy) {
1656
- console.log(helpDebugHierarchy)
1657
- runtime.process.exit(-1)
1658
- }
1659
- if (args.debugPriority) {
1660
- console.log(helpDebugPriority)
1661
- runtime.process.exit(-1)
1662
- }
1663
- if (args.debugBridge) {
1664
- console.log(helpDebugBridge)
1665
- runtime.process.exit(-1)
1666
- }
1667
- if (args.debugOperator) {
1668
- console.log(helpDebugOperator)
1669
- runtime.process.exit(-1)
1670
- }
1671
1312
 
1672
- if (args.clean) {
1673
- const tests = JSON.parse(runtime.fs.readFileSync(testConfig.name))
1674
- for (const test of tests) {
1675
- delete test.associations
1313
+ if (args.clean) {
1314
+ const tests = JSON.parse(runtime.fs.readFileSync(testConfig.name))
1315
+ for (const test of tests) {
1316
+ delete test.associations
1317
+ }
1318
+ writeTestFile(testConfig.name, tests)
1319
+ console.log(`Cleaned ${testConfig.name}`)
1320
+ return
1676
1321
  }
1677
- writeTestFile(testConfig.name, tests)
1678
- console.log(`Cleaned ${testConfig.name}`)
1679
- return
1680
- }
1681
1322
 
1682
- if (args.deleteTest) {
1683
- let tests = JSON.parse(runtime.fs.readFileSync(testConfig.name))
1684
- tests = tests.filter((test) => test.query !== args.deleteTest)
1685
- writeTestFile(testConfig.name, tests)
1686
- console.log(`Remove the test for "${args.deleteTest}"`)
1687
- return
1688
- }
1323
+ if (args.deleteTest) {
1324
+ let tests = JSON.parse(runtime.fs.readFileSync(testConfig.name))
1325
+ tests = tests.filter((test) => test.query !== args.deleteTest)
1326
+ writeTestFile(testConfig.name, tests)
1327
+ console.log(`Remove the test for "${args.deleteTest}"`)
1328
+ return
1329
+ }
1689
1330
 
1690
- const options = { rebuild: false }
1691
- if (args.rebuildTemplate) {
1692
- options.rebuild = true
1693
- }
1694
- if (args.greg) {
1695
- config.server('http://localhost:3000', '6804954f-e56d-471f-bbb8-08e3c54d9321')
1696
- }
1697
- if (args.server) {
1698
- config.server(args.server)
1699
- }
1331
+ const options = { rebuild: false }
1332
+ if (args.rebuildTemplate) {
1333
+ options.rebuild = true
1334
+ }
1335
+ if (args.greg) {
1336
+ config.server('http://localhost:3000', '6804954f-e56d-471f-bbb8-08e3c54d9321')
1337
+ }
1338
+ if (args.server) {
1339
+ config.server(args.server)
1340
+ }
1700
1341
 
1701
- if (args.queryParams) {
1702
- config.setQueryParams(args.queryParams)
1703
- }
1342
+ if (args.queryParams) {
1343
+ config.setQueryParams(args.queryParams)
1344
+ }
1704
1345
 
1705
- if (args.debug) {
1706
- config.config.debug = true
1707
- }
1346
+ if (args.debug) {
1347
+ config.config.debug = true
1348
+ }
1708
1349
 
1709
- if (args.reset) {
1710
- config.config.skip_cache = true
1711
- }
1350
+ if (args.reset) {
1351
+ config.config.skip_cache = true
1352
+ }
1712
1353
 
1713
- if (args.explainPriorities) {
1714
- config.config.explain_priorities = true
1715
- }
1354
+ if (args.explainPriorities) {
1355
+ config.config.explain_priorities = true
1356
+ }
1716
1357
 
1717
- config.config.debugIncludeConvolutions = args.debugIncludeConvolutions || process.argv.includes('--debugIncludeConvolutions') || process.argv.includes('-dic')
1358
+ config.config.debugIncludeConvolutions = args.debugIncludeConvolutions || process.argv.includes('--debugIncludeConvolutions') || process.argv.includes('-dic')
1718
1359
 
1719
- let configPrinted = false
1720
- const printConfig = () => {
1721
- if (configPrinted) {
1722
- return
1723
- }
1724
- configPrinted = true
1725
- if (args.print) {
1726
- if (args.print.includes('t')) {
1727
- console.log('Test queries')
1728
- let counter = 0
1729
- for (const test of config.tests) {
1730
- console.log(`${counter} - ${test.query}`)
1731
- counter += 1
1732
- }
1733
- }
1734
- if (args.print.includes('c')) {
1735
- const { data } = setupProcessB({ config })
1736
- console.log('Config as sent to server')
1737
- console.log(JSON.stringify(data, null, 2))
1360
+ let configPrinted = false
1361
+ const printConfig = () => {
1362
+ if (configPrinted) {
1363
+ return
1738
1364
  }
1365
+ configPrinted = true
1366
+ if (args.print) {
1367
+ if (args.print.includes('t')) {
1368
+ console.log('Test queries')
1369
+ let counter = 0
1370
+ for (const test of config.tests) {
1371
+ console.log(`${counter} - ${test.query}`)
1372
+ counter += 1
1373
+ }
1374
+ }
1375
+ if (args.print.includes('c')) {
1376
+ const { data } = setupProcessB({ config })
1377
+ console.log('Config as sent to server')
1378
+ console.log(JSON.stringify(data, null, 2))
1379
+ }
1739
1380
 
1740
- if (args.print.includes('l')) {
1741
- console.log('Module load ordering')
1742
- for (const km of config.configs) {
1743
- console.log(` ${km.name}`)
1381
+ if (args.print.includes('l')) {
1382
+ console.log('Module load ordering')
1383
+ for (const km of config.configs) {
1384
+ console.log(` ${km.name}`)
1385
+ }
1744
1386
  }
1745
- }
1746
- if (args.print.includes('w')) {
1747
- for (const word in config.config.words) {
1748
- console.log(word.concat(' ', ...config.config.words[word].map((def) => JSON.stringify(def))))
1387
+ if (args.print.includes('w')) {
1388
+ // { literals: Object, patterns: Array(2), hierarchy: Array(97) }
1389
+ console.log('literals')
1390
+ for (const word in config.config.words.literals) {
1391
+ console.log(' ' + word.concat(...config.config.words.literals[word].map((def, i) => ((i > 0) ? ' '.repeat(4+word.length) : ' ') + JSON.stringify(def) + '\n')))
1392
+ }
1393
+ console.log('patterns')
1394
+ for (const pattern of config.config.words.patterns) {
1395
+ console.log(' ' + JSON.stringify(pattern))
1396
+ }
1749
1397
  }
1750
- }
1751
- if (args.print.includes('b')) {
1752
- for (const bridge of config.config.bridges) {
1753
- console.log(JSON.stringify(bridge))
1398
+ if (args.print.includes('b')) {
1399
+ for (const bridge of config.config.bridges) {
1400
+ console.log(JSON.stringify(bridge))
1401
+ }
1754
1402
  }
1755
- }
1756
- if (args.print.includes('o')) {
1757
- for (const operator of config.config.operators) {
1758
- console.log(JSON.stringify(operator))
1403
+ if (args.print.includes('o')) {
1404
+ for (const operator of config.config.operators) {
1405
+ console.log(JSON.stringify(operator))
1406
+ }
1759
1407
  }
1760
- }
1761
- if (args.print.includes('j')) {
1762
- const { data } = setupProcessB({ config })
1763
- console.log(JSON.stringify(data, null, 2))
1764
- }
1765
- if (args.print.includes('a')) {
1766
- console.log('associations ================')
1767
- const properties = ['negative', 'positive']
1768
- for (const property of properties) {
1769
- console.log(` ${property} ===============`)
1770
- for (const association of config.config.associations[property]) {
1771
- console.log(` ${JSON.stringify(association)}`)
1408
+ if (args.print.includes('j')) {
1409
+ const { data } = setupProcessB({ config })
1410
+ console.log(JSON.stringify(data, null, 2))
1411
+ }
1412
+ if (args.print.includes('a')) {
1413
+ console.log('associations ================')
1414
+ const properties = ['negative', 'positive']
1415
+ for (const property of properties) {
1416
+ console.log(` ${property} ===============`)
1417
+ for (const association of config.config.associations[property]) {
1418
+ console.log(` ${JSON.stringify(association)}`)
1419
+ }
1772
1420
  }
1773
1421
  }
1774
- }
1775
- if (args.print.includes('d')) {
1776
- console.log(JSON.stringify(config.config.objects, null, 2))
1777
- }
1778
- if (args.print.includes('p')) {
1779
- for (const priority of config.config.priorities) {
1780
- console.log(JSON.stringify(priority))
1422
+ if (args.print.includes('d')) {
1423
+ console.log(JSON.stringify(config.config.objects, null, 2))
1781
1424
  }
1782
- }
1783
- if (args.print.includes('h')) {
1784
- for (const edge of config.config.hierarchy) {
1785
- console.log(JSON.stringify(edge))
1425
+ if (args.print.includes('p')) {
1426
+ for (const priority of config.config.priorities) {
1427
+ console.log(JSON.stringify(priority))
1428
+ }
1786
1429
  }
1787
- }
1788
- if (args.print.includes('g')) {
1789
- const easyToRead = _.cloneDeep(config.config.generators)
1790
- for (const semantic of easyToRead) {
1791
- semantic.match = semantic.match.toString()
1792
- semantic.apply = semantic.apply.toString()
1793
- if (semantic.applyWrapped) {
1794
- semantic.applyWrapped = semantic.applyWrapped.toString()
1430
+ if (args.print.includes('h')) {
1431
+ for (const edge of config.config.hierarchy) {
1432
+ console.log(JSON.stringify(edge))
1795
1433
  }
1796
1434
  }
1797
- console.dir(easyToRead)
1798
- }
1799
- if (args.print.includes('s')) {
1800
- const easyToRead = _.cloneDeep(config.config.semantics)
1801
- for (const semantic of easyToRead) {
1802
- semantic.match = semantic.match.toString()
1803
- semantic.apply = semantic.apply.toString()
1435
+ if (args.print.includes('g')) {
1436
+ const easyToRead = _.cloneDeep(config.config.generators)
1437
+ for (const semantic of easyToRead) {
1438
+ semantic.match = semantic.match.toString()
1439
+ semantic.apply = semantic.apply.toString()
1440
+ if (semantic.applyWrapped) {
1441
+ semantic.applyWrapped = semantic.applyWrapped.toString()
1442
+ }
1443
+ }
1444
+ console.dir(easyToRead)
1445
+ }
1446
+ if (args.print.includes('s')) {
1447
+ const easyToRead = _.cloneDeep(config.config.semantics)
1448
+ for (const semantic of easyToRead) {
1449
+ semantic.match = semantic.match.toString()
1450
+ semantic.apply = semantic.apply.toString()
1451
+ }
1452
+ console.dir(easyToRead)
1804
1453
  }
1805
- console.dir(easyToRead)
1806
1454
  }
1807
1455
  }
1808
- }
1809
1456
 
1810
- checkTemplate(template)
1457
+ checkTemplate(template)
1811
1458
 
1812
- if (template) {
1813
- let needsRebuild
1814
- if (args.rebuildTemplate && !args.rebuildTemplateFull) {
1815
- // get the startOfChanges for the partial rebuild
1816
- needsRebuild = config.needsRebuild(template.template, template.instance, { ...options, rebuild: false })
1817
- } else {
1818
- // do a check or full rebuild
1819
- needsRebuild = config.needsRebuild(template.template, template.instance, options)
1820
- }
1459
+ if (template) {
1460
+ let needsRebuild
1461
+ if (args.rebuildTemplate && !args.rebuildTemplateFull) {
1462
+ // get the startOfChanges for the partial rebuild
1463
+ needsRebuild = config.needsRebuild(template.template, template.instance, { ...options, rebuild: false })
1464
+ } else {
1465
+ // do a check or full rebuild
1466
+ needsRebuild = config.needsRebuild(template.template, template.instance, options)
1467
+ }
1821
1468
 
1822
- if (needsRebuild.needsRebuild) {
1823
- if (needsRebuild.previousResultss) {
1824
- console.log('Rebuild using the optimization to use previous results until a change is hit. For a full rebuild use -rtf')
1469
+ if (needsRebuild.needsRebuild) {
1470
+ if (needsRebuild.previousResultss) {
1471
+ console.log('Rebuild using the optimization to use previous results until a change is hit. For a full rebuild use -rtf')
1472
+ }
1473
+ console.log(`This module "${config.name}" needs rebuilding all other arguments will be ignored. Try again after the template is rebuilt.`)
1474
+ options.rebuild = true
1475
+ config.config.rebuild = true
1476
+ }
1477
+ try {
1478
+ await config.load(rebuildTemplate, template.template, template.instance, { rebuild: needsRebuild.needsRebuild || options.rebuild, previousResultss: needsRebuild.previousResultss, startOfChanges: needsRebuild.startOfChanges })
1479
+ } catch (e) {
1480
+ console.error(`Error loading template for ${config.name}. ${e.error ? e.error : e}${e.stack ? e.stack : ''}`)
1481
+ runtime.process.exit(-1)
1482
+ }
1483
+ if (!args.query) {
1484
+ printConfig()
1485
+ }
1486
+ if (needsRebuild.needsRebuild) {
1487
+ return
1825
1488
  }
1826
- console.log(`This module "${config.name}" needs rebuilding all other arguments will be ignored. Try again after the template is rebuilt.`)
1827
- options.rebuild = true
1828
- config.config.rebuild = true
1829
1489
  }
1830
- try {
1831
- config.load(template.template, template.instance, { rebuild: needsRebuild.needsRebuild || options.rebuild, previousResultss: needsRebuild.previousResultss, startOfChanges: needsRebuild.startOfChanges })
1832
- } catch (e) {
1833
- console.error(`Error loading template for ${config.name}. ${e.error ? e.error : e}${e.stack ? e.stack : ''}`)
1834
- runtime.process.exit(-1)
1490
+
1491
+ if (args.retrain) {
1492
+ config.config.retrain = true
1835
1493
  }
1836
- if (!args.query) {
1837
- printConfig()
1494
+
1495
+ if (args.saveDeveloper) {
1496
+ args.save = true
1838
1497
  }
1839
- if (needsRebuild.needsRebuild) {
1840
- return
1498
+ if (args.test || args.testVerbose || args.testAllVerbose || args.save) {
1499
+ global.transitoryMode = true
1841
1500
  }
1842
- }
1843
-
1844
- if (args.retrain) {
1845
- config.config.retrain = true
1846
- }
1847
-
1848
- if (args.test || args.testVerbose || args.testAllVerbose || args.save) {
1849
- global.transitoryMode = true
1850
- }
1851
- if (!args.query && !args.test && !args.info && (args.save || args.saveDeveloper)) {
1852
- global.transitoryMode = true
1853
- saveTests(config, test, testConfig, args.saveDeveloper)
1854
- // } else if (args.build) {
1855
- } else if (args.info) {
1856
- showInfo(description, section, config)
1857
- } else if (args.test || args.testVerbose || args.testAllVerbose) {
1858
- // TODO make test always a string
1859
- if (typeof test === 'string') {
1860
- const l = (n, hasError) => {
1861
- if (n === 0) {
1862
- if (hasError) {
1863
- runtime.process.exit(-1)
1501
+ if (!args.query && !args.test && !args.info && (args.save || args.saveDeveloper)) {
1502
+ global.transitoryMode = true
1503
+ await saveTests(config, test, testConfig, args.saveDeveloper)
1504
+ // } else if (args.build) {
1505
+ } else if (args.info) {
1506
+ showInfo(description, section, config)
1507
+ } else if (args.test || args.testVerbose || args.testAllVerbose) {
1508
+ // TODO make test always a string
1509
+ if (typeof test === 'string') {
1510
+ const l = async (n, hasError) => {
1511
+ if (n === 0) {
1512
+ if (hasError) {
1513
+ runtime.process.exit(-1)
1514
+ }
1515
+ return
1864
1516
  }
1865
- return
1866
- }
1867
- let useTestConfig = testConfig
1868
- if (args.testModuleName) {
1869
- useTestConfig = config.getConfigs()[args.testModuleName].getTestConfig()
1870
- useTestConfig.testModuleName = args.testModuleName
1871
- test = useTestConfig.name
1872
- }
1873
- runTests(config, test, { args, debug: args.debug, testConfig: useTestConfig, verbose: args.testVerbose || args.testAllVerbose, stopAtFirstError: !args.testAllVerbose }).then((results) => {
1874
- let newError = false
1875
- if (results.length > 0) {
1876
- let headerShown = false
1877
-
1878
- let hasError = false
1879
- for (const result of results) {
1880
- if (JSON.stringify(result.expected.paraphrases) !== JSON.stringify(result.actual.paraphrases)) {
1881
- result.hasError = true
1882
- }
1883
- if (!args.testNoParenthesized) {
1884
- if (JSON.stringify(result.expected.paraphrasesParenthesized) !== JSON.stringify(result.actual.paraphrasesParenthesized)) {
1517
+ let useTestConfig = testConfig
1518
+ if (args.testModuleName) {
1519
+ useTestConfig = config.getConfigs()[args.testModuleName].getTestConfig()
1520
+ useTestConfig.testModuleName = args.testModuleName
1521
+ test = useTestConfig.name
1522
+ }
1523
+ await runTests(config, test, { args, debug: args.debug, testConfig: useTestConfig, verbose: args.testVerbose || args.testAllVerbose, stopAtFirstError: !args.testAllVerbose }).then((results) => {
1524
+ let newError = false
1525
+ if (results.length > 0) {
1526
+ let headerShown = false
1527
+
1528
+ let hasError = false
1529
+ for (const result of results) {
1530
+ if (JSON.stringify(result.expected.paraphrases) !== JSON.stringify(result.actual.paraphrases)) {
1885
1531
  result.hasError = true
1886
1532
  }
1887
- if (JSON.stringify(result.expected.generatedParenthesized) !== JSON.stringify(result.actual.generatedParenthesized)) {
1533
+ if (!args.testNoParenthesized) {
1534
+ if (JSON.stringify(result.expected.paraphrasesParenthesized) !== JSON.stringify(result.actual.paraphrasesParenthesized)) {
1535
+ result.hasError = true
1536
+ }
1537
+ if (JSON.stringify(result.expected.generatedParenthesized) !== JSON.stringify(result.actual.generatedParenthesized)) {
1538
+ result.hasError = true
1539
+ }
1540
+ }
1541
+ if (JSON.stringify(result.expected.responses) !== JSON.stringify(result.actual.responses)) {
1888
1542
  result.hasError = true
1889
1543
  }
1544
+ if (JSON.stringify(result.expected.checked) !== JSON.stringify(result.actual.checked)) {
1545
+ result.hasError = true
1546
+ }
1547
+ if (!sameJSON(result.expected.checkedContexts, result.actual.checkedContexts)) {
1548
+ result.hasError = true
1549
+ }
1550
+ if (result.hasError) {
1551
+ hasError = true
1552
+ }
1890
1553
  }
1891
- if (JSON.stringify(result.expected.responses) !== JSON.stringify(result.actual.responses)) {
1892
- result.hasError = true
1893
- }
1894
- if (JSON.stringify(result.expected.checked) !== JSON.stringify(result.actual.checked)) {
1895
- result.hasError = true
1896
- }
1897
- if (!sameJSON(result.expected.checkedContexts, result.actual.checkedContexts)) {
1898
- result.hasError = true
1899
- }
1900
- if (result.hasError) {
1901
- hasError = true
1902
- }
1903
- }
1904
1554
 
1905
- if (hasError) {
1906
- console.log('**************************** ERRORS ************************')
1907
- for (const result of results) {
1908
- console.log('Utterance: ', result.utterance)
1909
- const show = (label, expected, actual) => {
1910
- if (JSON.stringify(expected) !== JSON.stringify(actual)) {
1555
+ if (hasError) {
1556
+ console.log('**************************** ERRORS ************************')
1557
+ for (const result of results) {
1558
+ console.log('Utterance: ', result.utterance)
1559
+ const show = (label, expected, actual) => {
1560
+ if (JSON.stringify(expected) !== JSON.stringify(actual)) {
1561
+ if (!headerShown) {
1562
+ console.log(' Failure')
1563
+ }
1564
+ console.log(` expected ${label}`, expected)
1565
+ console.log(` actual ${label} `, actual)
1566
+ newError = true
1567
+ headerShown = true
1568
+ if (args.vimdiff) {
1569
+ vimdiff(actual, expected, `"${result.utterance}" - ${label}`)
1570
+ }
1571
+ result.hasError = true
1572
+ }
1573
+ }
1574
+ show('paraphrases', result.expected.paraphrases, result.actual.paraphrases)
1575
+ if (!args.testNoParenthesized) {
1576
+ show('paraphrases parenthesized', result.expected.paraphrasesParenthesized, result.actual.paraphrasesParenthesized)
1577
+ }
1578
+ show('responses', result.expected.responses, result.actual.responses)
1579
+ if (!args.testNoParenthesized) {
1580
+ show('responses parenthesized', result.expected.generatedParenthesized, result.actual.generatedParenthesized)
1581
+ }
1582
+ /*
1583
+ if (JSON.stringify(result.expected.paraphrases) !== JSON.stringify(result.actual.paraphrases)) {
1911
1584
  if (!headerShown) {
1912
1585
  console.log(' Failure')
1913
1586
  }
1914
- console.log(` expected ${label}`, expected)
1915
- console.log(` actual ${label} `, actual)
1587
+ console.log(' expected paraphrases', result.expected.paraphrases)
1588
+ console.log(' actual paraphrases ', result.actual.paraphrases)
1916
1589
  newError = true
1917
1590
  headerShown = true
1918
- if (args.vimdiff) {
1919
- vimdiff(actual, expected, `"${result.utterance}" - ${label}`)
1920
- }
1921
- result.hasError = true
1922
- }
1923
- }
1924
- show('paraphrases', result.expected.paraphrases, result.actual.paraphrases)
1925
- if (!args.testNoParenthesized) {
1926
- show('paraphrases parenthesized', result.expected.paraphrasesParenthesized, result.actual.paraphrasesParenthesized)
1927
- }
1928
- show('responses', result.expected.responses, result.actual.responses)
1929
- if (!args.testNoParenthesized) {
1930
- show('responses parenthesized', result.expected.generatedParenthesized, result.actual.generatedParenthesized)
1931
- }
1932
- /*
1933
- if (JSON.stringify(result.expected.paraphrases) !== JSON.stringify(result.actual.paraphrases)) {
1934
- if (!headerShown) {
1935
- console.log(' Failure')
1936
1591
  }
1937
- console.log(' expected paraphrases', result.expected.paraphrases)
1938
- console.log(' actual paraphrases ', result.actual.paraphrases)
1939
- newError = true
1940
- headerShown = true
1941
- }
1942
- if (JSON.stringify(result.expected.responses) !== JSON.stringify(result.actual.responses)) {
1943
- if (!headerShown) {
1944
- console.log(' Failure')
1592
+ if (JSON.stringify(result.expected.responses) !== JSON.stringify(result.actual.responses)) {
1593
+ if (!headerShown) {
1594
+ console.log(' Failure')
1595
+ }
1596
+ console.log(' expected responses ', result.expected.responses)
1597
+ console.log(' actual responses ', result.actual.responses)
1598
+ newError = true
1599
+ headerShown = true
1945
1600
  }
1946
- console.log(' expected responses ', result.expected.responses)
1947
- console.log(' actual responses ', result.actual.responses)
1948
- newError = true
1949
- headerShown = true
1950
- }
1951
- */
1952
- if (JSON.stringify(result.expected.checked) !== JSON.stringify(result.actual.checked)) {
1953
- if (!headerShown) {
1954
- console.log(' Failure')
1601
+ */
1602
+ if (JSON.stringify(result.expected.checked) !== JSON.stringify(result.actual.checked)) {
1603
+ if (!headerShown) {
1604
+ console.log(' Failure')
1605
+ }
1606
+ const widths = [4, 18, 72]
1607
+ const lines = new Lines(widths)
1608
+ lines.setElement(1, 1, 'expected checked objects')
1609
+ lines.setElement(2, 2, JSON.stringify(result.expected.checked, null, 2))
1610
+ lines.log()
1611
+ lines.setElement(1, 1, 'actual checked objects')
1612
+ lines.setElement(2, 2, JSON.stringify(result.actual.checked, null, 2))
1613
+ lines.log()
1614
+ if (args.vimdiff) {
1615
+ show('checked properties for objects', result.expected.checked, result.actual.checked)
1616
+ }
1617
+ newError = true
1618
+ headerShown = true
1955
1619
  }
1956
- const widths = [4, 18, 72]
1957
- const lines = new Lines(widths)
1958
- lines.setElement(1, 1, 'expected checked objects')
1959
- lines.setElement(2, 2, JSON.stringify(result.expected.checked, null, 2))
1960
- lines.log()
1961
- lines.setElement(1, 1, 'actual checked objects')
1962
- lines.setElement(2, 2, JSON.stringify(result.actual.checked, null, 2))
1963
- lines.log()
1964
- if (args.vimdiff) {
1965
- vimdiff(result.actual.checked, result.expected.checked)
1620
+ if (!sameJSON(result.expected.checkedContexts, result.actual.checkedContexts)) {
1621
+ if (!headerShown) {
1622
+ console.log(' Failure')
1623
+ }
1624
+ const widths = [4, 18, 72]
1625
+ const lines = new Lines(widths)
1626
+ lines.setElement(1, 1, 'expected checked contexts', true)
1627
+ lines.setElement(2, 2, JSON.stringify(result.expected.checkedContexts, null, 2))
1628
+ lines.log()
1629
+ lines.setElement(1, 1, 'actual checked contexts', true)
1630
+ lines.setElement(2, 2, JSON.stringify(result.actual.checkedContexts, null, 2))
1631
+ lines.log()
1632
+ if (args.vimdiff) {
1633
+ show('checked properties for context', result.expected.checkedContexts, result.actual.checkedContexts)
1634
+ }
1635
+ newError = true
1636
+ headerShown = true
1966
1637
  }
1967
- newError = true
1968
- headerShown = true
1969
1638
  }
1970
- if (!sameJSON(result.expected.checkedContexts, result.actual.checkedContexts)) {
1971
- if (!headerShown) {
1972
- console.log(' Failure')
1639
+ } else {
1640
+ if (results.length > 0 && args.vimdiff) {
1641
+ for (const result of results) {
1642
+ vimdiff(result.actual, result.expected)
1973
1643
  }
1974
- const widths = [4, 18, 72]
1975
- const lines = new Lines(widths)
1976
- lines.setElement(1, 1, 'expected checked contexts', true)
1977
- lines.setElement(2, 2, JSON.stringify(result.expected.checkedContexts, null, 2))
1978
- lines.log()
1979
- lines.setElement(1, 1, 'actual checked contexts', true)
1980
- lines.setElement(2, 2, JSON.stringify(result.actual.checkedContexts, null, 2))
1981
- lines.log()
1982
- if (args.vimdiff) {
1983
- vimdiff(result.actual.checkedContexts, result.expected.checkedContexts)
1984
- }
1985
- newError = true
1986
- headerShown = true
1987
1644
  }
1988
1645
  }
1989
- } else {
1990
- if (results.length > 0 && args.vimdiff) {
1991
- for (const result of results) {
1992
- vimdiff(result.actual, result.expected)
1646
+ if (hasError) {
1647
+ if (!headerShown) {
1648
+ if (!(useTestConfig.check && useTestConfig.check.length > 0)) {
1649
+ console.log('There are failures due to things other than paraphrases, responses and checked properties being different. They are not shown because you ran -tv or -tva which only shows difference in paraphrase and results. Usually what I do is -s and do a diff to make sure there are no other problems. If the paraphrases or results were different they would have shown here.')
1650
+ }
1993
1651
  }
1994
- }
1995
- }
1996
- if (hasError) {
1997
- if (!headerShown) {
1998
1652
  if (!(useTestConfig.check && useTestConfig.check.length > 0)) {
1999
- console.log('There are failures due to things other than paraphrases, responses and checked properties being different. They are not shown because you ran -tv or -tva which only shows difference in paraphrase and results. Usually what I do is -s and do a diff to make sure there are no other problems. If the paraphrases or results were different they would have shown here.')
2000
- }
2001
- }
2002
- if (!(useTestConfig.check && useTestConfig.check.length > 0)) {
2003
- console.log('use -v arg to write files expected.json and actual.json in the current directory for detailed comparison. Or do -s and then git diff the changes.')
2004
- // console.log(JSON.stringify(contexts))
2005
- let errorCount = 0
2006
- for (const result of results) {
2007
- if (result.hasError) {
2008
- errorCount += 1
1653
+ console.log('use -v arg to write files expected.json and actual.json in the current directory for detailed comparison. Or do -s and then git diff the changes.')
1654
+ // console.log(JSON.stringify(contexts))
1655
+ let errorCount = 0
1656
+ for (const result of results) {
1657
+ if (result.hasError) {
1658
+ console.log(`FAILED ${result.utterance}`)
1659
+ errorCount += 1
1660
+ }
2009
1661
  }
1662
+ console.log(`**************************** THERE WERE ${errorCount} TEST FAILURES ************************`)
2010
1663
  }
2011
- console.log(`**************************** THERE WERE ${errorCount} TEST FAILURES ************************`)
2012
1664
  }
2013
1665
  }
2014
- }
2015
- // const contexts = { failures: results }
2016
- l(n - 1, hasError || newError)
2017
- }).catch((error) => {
2018
- console.error(error)
2019
- runtime.process.exit(-1)
2020
- errorHandler(error)
1666
+ // const contexts = { failures: results }
1667
+ l(n - 1, hasError || newError)
1668
+ }).catch((error) => {
1669
+ console.error(error)
1670
+ runtime.process.exit(-1)
1671
+ errorHandler(error)
1672
+ })
1673
+ }
1674
+ await l(args.count, false)
1675
+ } else {
1676
+ test()
1677
+ }
1678
+ } else if (args.loop) {
1679
+ const readline = runtime.readline.createInterface({ input: runtime.process.stdin, output: runtime.process.stdout })
1680
+ const f = () => readline.question('Enter query? (newline to quit) ', query => {
1681
+ query = query.trim()
1682
+ if (query.length === 0) {
1683
+ return readline.close()
1684
+ }
1685
+ const promise = _process(config, query, { testsFN: test }).then((results) => {
1686
+ console.log(results.responses.join(' '))
2021
1687
  })
1688
+ if (!('then' in promise)) {
1689
+ throw new Error('Return a promise from process in the definition of knowledgeModule')
1690
+ }
1691
+ promise
1692
+ .then(() => {
1693
+ f()
1694
+ })
1695
+ .catch((e) => {
1696
+ if (e.errno == 'ECONNREFUSED') {
1697
+ console.log(e)
1698
+ readline.close()
1699
+ } else {
1700
+ console.log(e)
1701
+ f()
1702
+ }
1703
+ })
1704
+ })
1705
+ f()
1706
+ } else if (args.query) {
1707
+ let useTestConfig = testConfig
1708
+ if (args.testModuleName) {
1709
+ config.testConfig.testModuleName = args.testModuleName
1710
+ config.testConfig.checks = config.getConfigs()[args.testModuleName].getTestConfig().checks
1711
+ // useTestConfig = config.getConfigs()[args.testModuleName].getTestConfig()
1712
+ // useTestConfig.testModuleName = args.testModuleName
2022
1713
  }
2023
- l(args.count, false)
2024
- } else {
2025
- test()
2026
- }
2027
- } else if (args.loop) {
2028
- const readline = runtime.readline.createInterface({ input: runtime.process.stdin, output: runtime.process.stdout })
2029
- const f = () => readline.question('Enter query? (newline to quit) ', query => {
2030
- query = query.trim()
2031
- if (query.length === 0) {
2032
- return readline.close()
1714
+ const objects = getObjects(config.config.objects)(config.uuid)
1715
+ // for the compare
1716
+ if (args.objectDiff) {
1717
+ global.beforeObjects = _.cloneDeep(objects)
2033
1718
  }
2034
- const promise = _process(config, query, { testsFN: test }).then((results) => {
2035
- console.log(results.responses.join(' '))
2036
- })
2037
- if (!('then' in promise)) {
2038
- throw new Error('Return a promise from process in the definition of knowledgeModule')
1719
+ try {
1720
+ await processResults(_process(config, args.query, { commandLineArgs: args, dontAddAssociations: args.dontAddAssociations, writeTests: args.save || args.saveDeveloper, saveDeveloper: args.saveDeveloper, testConfig, testsFN: test }))
1721
+ } catch (error) {
1722
+ console.log('Error', error)
2039
1723
  }
2040
- promise
2041
- .then(() => {
2042
- f()
2043
- })
2044
- .catch((e) => {
2045
- if (e.errno == 'ECONNREFUSED') {
2046
- console.log(e)
2047
- readline.close()
2048
- } else {
2049
- console.log(e)
2050
- f()
2051
- }
2052
- })
2053
- })
2054
- f()
2055
- } else if (args.query) {
2056
- let useTestConfig = testConfig
2057
- if (args.testModuleName) {
2058
- config.testConfig.testModuleName = args.testModuleName
2059
- config.testConfig.checks = config.getConfigs()[args.testModuleName].getTestConfig().checks
2060
- // useTestConfig = config.getConfigs()[args.testModuleName].getTestConfig()
2061
- // useTestConfig.testModuleName = args.testModuleName
2062
1724
  }
2063
- const objects = getObjects(config.config.objects)(config.uuid)
2064
- // for the compare
2065
- if (args.objectDiff) {
2066
- global.beforeObjects = _.cloneDeep(objects)
2067
- }
2068
- try {
2069
- await processResults(_process(config, args.query, { commandLineArgs: args, dontAddAssociations: args.dontAddAssociations, writeTests: args.save || args.saveDeveloper, saveDeveloper: args.saveDeveloper, testConfig, testsFN: test }))
2070
- } catch (error) {
2071
- console.log('Error', error)
1725
+ printConfig()
1726
+ } finally {
1727
+ if (config) {
1728
+ config.terminate()
2072
1729
  }
2073
1730
  }
2074
- printConfig()
2075
1731
  } else {
2076
- const initConfig = (config) => {
1732
+ const initConfig = async (config) => {
2077
1733
  if (template) {
2078
1734
  if (config.needsRebuild(template.template, template.instance, { isModule: !isProcess }).needsRebuild) {
1735
+ debugger
1736
+ config.needsRebuild(template.template, template.instance, { isModule: !isProcess })
2079
1737
  const error = `This module "${config.name}" cannot be used because the instance file needs rebuilding. Run on the command line with no arguments or the -rt argument to rebuild.`
2080
1738
  throw new Error(error)
2081
1739
  }
@@ -2108,24 +1766,21 @@ const knowledgeModuleImpl = async ({
2108
1766
 
2109
1767
  if (template) {
2110
1768
  try {
2111
- config.load(template.template, template.instance)
1769
+ await config.load(rebuildTemplate, template.template, template.instance)
2112
1770
  } catch (e) {
2113
1771
  errorHandler(e)
2114
1772
  }
2115
1773
  }
2116
1774
  }
2117
1775
 
2118
- createConfigExport = (additionalConfig) => {
2119
- if (createConfig.cached) {
1776
+ // no cache 21 minutes + rebuild fails "node tester_rebuild -m colors"
1777
+ // cache okay
1778
+ createConfigExport = async () => {
1779
+ if (false && createConfig.cached) {
2120
1780
  return createConfig.cached
2121
1781
  }
2122
- const config = createConfig(acceptsAdditionalConfig ? additionalConfig : null)
2123
- if (!acceptsAdditionalConfig && additionalConfig) {
2124
- config.stop_auto_rebuild()
2125
- additionalConfig(config)
2126
- config.restart_auto_rebuild()
2127
- }
2128
- initConfig(config)
1782
+ const config = await createConfig()
1783
+ await initConfig(config)
2129
1784
  // config.rebuild({ isModule: true })
2130
1785
  createConfig.cached = config
2131
1786
  return createConfig.cached
@@ -2154,11 +1809,6 @@ const ensureTestFile = (module, name, type) => {
2154
1809
  }
2155
1810
  }
2156
1811
 
2157
- function w (func) {
2158
- func.where = where(3)
2159
- return func
2160
- }
2161
-
2162
1812
  const knowledgeModule = async (...args) => {
2163
1813
  await knowledgeModuleImpl(...args).catch((e) => {
2164
1814
  console.error(e)
@@ -2169,9 +1819,6 @@ const knowledgeModule = async (...args) => {
2169
1819
  module.exports = {
2170
1820
  process: _process,
2171
1821
  stableId,
2172
- where,
2173
- w,
2174
- // submitBug,
2175
1822
  ensureTestFile,
2176
1823
  rebuildTemplate,
2177
1824
  processContext,
@@ -2188,5 +1835,6 @@ module.exports = {
2188
1835
  loadInstance,
2189
1836
  gs,
2190
1837
  flattens,
2191
- writeTest
1838
+ writeTest,
1839
+ getConfigForTest,
2192
1840
  }