theprogrammablemind 8.0.0-beta.7 → 8.0.0-beta.71

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