@dxos/brain 0.0.1 → 0.13.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.
Files changed (71) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +32 -1
  3. package/dist/lib/Builtins.mjs +184 -0
  4. package/dist/lib/Builtins.mjs.map +1 -0
  5. package/dist/lib/CompilePrompt.mjs +305 -0
  6. package/dist/lib/CompilePrompt.mjs.map +1 -0
  7. package/dist/lib/Compiler.mjs +212 -0
  8. package/dist/lib/Compiler.mjs.map +1 -0
  9. package/dist/lib/Encoding.mjs +116 -0
  10. package/dist/lib/Encoding.mjs.map +1 -0
  11. package/dist/lib/GoalRules.mjs +245 -0
  12. package/dist/lib/GoalRules.mjs.map +1 -0
  13. package/dist/lib/Vocabulary.mjs +92 -0
  14. package/dist/lib/Vocabulary.mjs.map +1 -0
  15. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  16. package/dist/lib/index.mjs +7 -0
  17. package/dist/lib/testing.mjs +831 -0
  18. package/dist/lib/testing.mjs.map +1 -0
  19. package/dist/types/src/Builtins.d.ts +61 -0
  20. package/dist/types/src/Builtins.d.ts.map +1 -0
  21. package/dist/types/src/Builtins.test.d.ts +2 -0
  22. package/dist/types/src/Builtins.test.d.ts.map +1 -0
  23. package/dist/types/src/CompilePrompt.d.ts +107 -0
  24. package/dist/types/src/CompilePrompt.d.ts.map +1 -0
  25. package/dist/types/src/CompilePrompt.test.d.ts +2 -0
  26. package/dist/types/src/CompilePrompt.test.d.ts.map +1 -0
  27. package/dist/types/src/Compiler.d.ts +76 -0
  28. package/dist/types/src/Compiler.d.ts.map +1 -0
  29. package/dist/types/src/Compiler.test.d.ts +2 -0
  30. package/dist/types/src/Compiler.test.d.ts.map +1 -0
  31. package/dist/types/src/Encoding.d.ts +42 -0
  32. package/dist/types/src/Encoding.d.ts.map +1 -0
  33. package/dist/types/src/Encoding.test.d.ts +2 -0
  34. package/dist/types/src/Encoding.test.d.ts.map +1 -0
  35. package/dist/types/src/GoalRules.d.ts +125 -0
  36. package/dist/types/src/GoalRules.d.ts.map +1 -0
  37. package/dist/types/src/GoalRules.test.d.ts +2 -0
  38. package/dist/types/src/GoalRules.test.d.ts.map +1 -0
  39. package/dist/types/src/Vocabulary.d.ts +31 -0
  40. package/dist/types/src/Vocabulary.d.ts.map +1 -0
  41. package/dist/types/src/Vocabulary.test.d.ts +2 -0
  42. package/dist/types/src/Vocabulary.test.d.ts.map +1 -0
  43. package/dist/types/src/index.d.ts +7 -0
  44. package/dist/types/src/index.d.ts.map +1 -0
  45. package/dist/types/src/testing/index.d.ts +4 -0
  46. package/dist/types/src/testing/index.d.ts.map +1 -0
  47. package/dist/types/src/testing/reference.d.ts +9 -0
  48. package/dist/types/src/testing/reference.d.ts.map +1 -0
  49. package/dist/types/src/testing/scenarios.d.ts +73 -0
  50. package/dist/types/src/testing/scenarios.d.ts.map +1 -0
  51. package/dist/types/src/testing/simulate.d.ts +31 -0
  52. package/dist/types/src/testing/simulate.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -0
  54. package/package.json +74 -5
  55. package/src/Builtins.test.ts +45 -0
  56. package/src/Builtins.ts +284 -0
  57. package/src/CompilePrompt.test.ts +117 -0
  58. package/src/CompilePrompt.ts +376 -0
  59. package/src/Compiler.test.ts +85 -0
  60. package/src/Compiler.ts +234 -0
  61. package/src/Encoding.test.ts +79 -0
  62. package/src/Encoding.ts +99 -0
  63. package/src/GoalRules.test.ts +186 -0
  64. package/src/GoalRules.ts +306 -0
  65. package/src/Vocabulary.test.ts +48 -0
  66. package/src/Vocabulary.ts +88 -0
  67. package/src/index.ts +10 -0
  68. package/src/testing/index.ts +7 -0
  69. package/src/testing/reference.ts +91 -0
  70. package/src/testing/scenarios.ts +604 -0
  71. package/src/testing/simulate.ts +127 -0
@@ -0,0 +1,234 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Ast from '@dxos/datalog/Ast';
8
+ import type * as Builtin from '@dxos/datalog/Builtin';
9
+ import * as Checker from '@dxos/datalog/Checker';
10
+ import * as Parser from '@dxos/datalog/Parser';
11
+ import { BaseError } from '@dxos/errors';
12
+
13
+ import * as Builtins from './Builtins.ts';
14
+ import * as Encoding from './Encoding.ts';
15
+ import * as Vocabulary from './Vocabulary.ts';
16
+
17
+ /** Heads a goal program may define: `achieved(goal)`, `holds(goal)`, `wake(Label)`, `blocks(Action)`. */
18
+ export const GOAL_HEADS = ['achieved', 'holds', 'wake', 'blocks'] as const;
19
+
20
+ /** Relations goal rules may read; goal heads a program leaves undefined are empty. */
21
+ export const RELATIONS: Readonly<Record<string, number>> = {
22
+ ...Encoding.RELATIONS,
23
+ ...Object.fromEntries(GOAL_HEADS.map((head) => [head, 1])),
24
+ };
25
+
26
+ export type DiagnosticCode = Checker.DiagnosticCode | 'parse' | 'vocabulary' | 'goal';
27
+
28
+ export type Diagnostic = {
29
+ readonly code: DiagnosticCode;
30
+ readonly message: string;
31
+ readonly position?: Ast.Position;
32
+ };
33
+
34
+ /** A checked goal program ready for evaluation. */
35
+ export type Compilation = {
36
+ readonly source: string;
37
+ readonly program: Ast.Program;
38
+ /** Per-rule wake relations (one tuple per binding) and the label each one wakes. */
39
+ readonly wakes: ReadonlyMap<string, string>;
40
+ };
41
+
42
+ export type Options = {
43
+ readonly vocabulary?: Vocabulary.Vocabulary;
44
+ /** Defaults to the goal built-ins over an empty context (signatures are all checking needs). */
45
+ readonly builtins?: Builtin.Registry;
46
+ };
47
+
48
+ /** Thrown by `compileOrThrow` and `GoalRules` when compilation reports diagnostics. */
49
+ export class CompileError extends BaseError.extend('CompileError', 'Goal rules do not compile') {
50
+ // A typed field rather than `context`, which would repeat every diagnostic in the message as JSON.
51
+ readonly diagnostics: ReadonlyArray<Diagnostic>;
52
+
53
+ constructor(diagnostics: ReadonlyArray<Diagnostic>) {
54
+ super({ message: `Goal rules do not compile:\n${diagnostics.map(formatDiagnostic).join('\n')}` });
55
+ this.diagnostics = diagnostics;
56
+ }
57
+ }
58
+
59
+ /** Formats a diagnostic as `line:column code: message`. */
60
+ export const formatDiagnostic = ({ code, message, position }: Diagnostic): string =>
61
+ `${position ? `${position.line}:${position.column} ` : ''}${code}: ${message}`;
62
+
63
+ /** The vocabulary used when none is given. */
64
+ export const defaultVocabulary = (): Vocabulary.Vocabulary =>
65
+ Vocabulary.make(Vocabulary.DEFAULT_ENTRIES, [...Object.keys(Encoding.RELATIONS), ...GOAL_HEADS]);
66
+
67
+ /**
68
+ * Compiles goal rules: parses, expands predicate shorthand for canonical vocabulary predicates
69
+ * (`helps_with(S, O)` → `fact(_, S, helps_with, O)`, `helps_with(F, S, O)` exposes the id),
70
+ * checks goal heads, then runs the engine's static checks against the fact relations.
71
+ */
72
+ export const compile = (
73
+ source: string,
74
+ options: Options = {},
75
+ ): { compilation?: Compilation; diagnostics: Diagnostic[] } => {
76
+ const vocabulary = options.vocabulary ?? defaultVocabulary();
77
+ const builtins = options.builtins ?? Builtins.make(Builtins.emptyContext());
78
+
79
+ let parsed: Ast.Program;
80
+ try {
81
+ parsed = Parser.parse(source);
82
+ } catch (error) {
83
+ if (error instanceof Parser.ParseError) {
84
+ return { diagnostics: [{ code: 'parse', message: error.reason, position: error.position }] };
85
+ }
86
+ throw error;
87
+ }
88
+
89
+ const diagnostics: Diagnostic[] = [];
90
+ const defined = new Set(parsed.rules.map((rule) => rule.head.predicate));
91
+ let anonymous = 0;
92
+
93
+ const rewriteAtom = (literal: Ast.AtomLiteral, fallback: Ast.Position | undefined): Ast.AtomLiteral => {
94
+ const { predicate, terms } = literal.atom;
95
+ const position = literal.position ?? fallback;
96
+ if (predicate === 'fact') {
97
+ const stored = terms[2];
98
+ if (stored?.type === 'constant') {
99
+ const canonical = vocabulary.canonical(String(stored.value));
100
+ if (canonical !== undefined && canonical !== stored.value) {
101
+ diagnostics.push({
102
+ code: 'vocabulary',
103
+ message: `predicate "${stored.value}" is stored as ${canonical}; use ${canonical}`,
104
+ position,
105
+ });
106
+ }
107
+ }
108
+ return literal;
109
+ }
110
+ if (predicate in Encoding.RELATIONS || builtins.has(predicate) || defined.has(predicate)) {
111
+ return literal;
112
+ }
113
+ if (vocabulary.isCanonical(predicate)) {
114
+ if (terms.length !== 2 && terms.length !== 3) {
115
+ diagnostics.push({
116
+ code: 'vocabulary',
117
+ message: `shorthand ${predicate} takes (Subject, Object) or (Fact, Subject, Object), not ${terms.length} arguments`,
118
+ position,
119
+ });
120
+ return literal;
121
+ }
122
+ const id: Ast.Term =
123
+ terms.length === 3 ? terms[0] : { type: 'variable', name: `_shorthand${anonymous++}`, anonymous: true };
124
+ const [subject, object] = terms.length === 3 ? [terms[1], terms[2]] : [terms[0], terms[1]];
125
+ return { ...literal, atom: Ast.atom('fact', [id, subject, Ast.constant(predicate), object]) };
126
+ }
127
+ const canonical = vocabulary.canonical(predicate);
128
+ if (canonical !== undefined) {
129
+ diagnostics.push({
130
+ code: 'vocabulary',
131
+ message: `${predicate} is a synonym; shorthand must use the canonical predicate ${canonical}`,
132
+ position,
133
+ });
134
+ }
135
+ return literal;
136
+ };
137
+
138
+ const rewriteLiteral = (literal: Ast.Literal, fallback: Ast.Position | undefined): Ast.Literal => {
139
+ switch (literal.type) {
140
+ case 'atom':
141
+ return rewriteAtom(literal, fallback);
142
+ case 'comparison':
143
+ return literal;
144
+ case 'aggregate':
145
+ return { ...literal, body: literal.body.map((inner) => rewriteLiteral(inner, literal.position ?? fallback)) };
146
+ }
147
+ };
148
+
149
+ const rules: Ast.Rule[] = [];
150
+ const wakes = new Map<string, string>();
151
+ parsed.rules.forEach((parsedRule, index) => {
152
+ const rule = {
153
+ ...parsedRule,
154
+ body: parsedRule.body.map((literal) => rewriteLiteral(literal, parsedRule.position)),
155
+ };
156
+ const { predicate, terms } = rule.head;
157
+ if (predicate in Encoding.RELATIONS) {
158
+ diagnostics.push({
159
+ code: 'goal',
160
+ message: `rules cannot define the base relation ${predicate}`,
161
+ position: rule.position,
162
+ });
163
+ }
164
+ if (isGoalHead(predicate)) {
165
+ const [argument] = terms;
166
+ if (terms.length !== 1) {
167
+ diagnostics.push({ code: 'goal', message: `${predicate} takes one argument`, position: rule.position });
168
+ } else if (predicate !== 'blocks' && argument.type !== 'constant') {
169
+ diagnostics.push({ code: 'goal', message: `${predicate} takes a constant argument`, position: rule.position });
170
+ } else if (
171
+ (predicate === 'achieved' || predicate === 'holds') &&
172
+ (argument.type !== 'constant' || argument.value !== 'goal')
173
+ ) {
174
+ diagnostics.push({
175
+ code: 'goal',
176
+ message: `${predicate} must be written ${predicate}(goal)`,
177
+ position: rule.position,
178
+ });
179
+ }
180
+ }
181
+
182
+ const label = terms[0];
183
+ if (predicate === 'wake' && terms.length === 1 && label.type === 'constant' && rule.body.length > 0) {
184
+ // One relation per wake rule, carrying its body bindings, so each new binding is a new tuple.
185
+ const relation = `wake#${index}`;
186
+ const variables = bodyVariables(rule.body).map((name) => Ast.variable(name));
187
+ wakes.set(relation, String(label.value));
188
+ rules.push({ ...rule, head: Ast.atom(relation, [label, ...variables]) });
189
+ rules.push({
190
+ head: rule.head,
191
+ body: [{ type: 'atom', negated: false, atom: Ast.atom(relation, [label, ...variables]) }],
192
+ position: rule.position,
193
+ });
194
+ } else {
195
+ rules.push(rule);
196
+ }
197
+ });
198
+
199
+ const program: Ast.Program = { rules };
200
+ if (diagnostics.length > 0) {
201
+ // Engine checks would repeat each vocabulary error as an undefined predicate.
202
+ return { diagnostics };
203
+ }
204
+ for (const diagnostic of Checker.check(program, { builtins, relations: RELATIONS })) {
205
+ diagnostics.push({ code: diagnostic.code, message: diagnostic.message, position: diagnostic.position });
206
+ }
207
+ return diagnostics.length > 0 ? { diagnostics } : { compilation: { source, program, wakes }, diagnostics };
208
+ };
209
+
210
+ /** Compiles goal rules, throwing on any diagnostic. */
211
+ export const compileOrThrow = (source: string, options: Options = {}): Compilation => {
212
+ const { compilation, diagnostics } = compile(source, options);
213
+ if (!compilation) {
214
+ throw new CompileError(diagnostics);
215
+ }
216
+ return compilation;
217
+ };
218
+
219
+ const isGoalHead = (predicate: string): boolean => GOAL_HEADS.some((head) => head === predicate);
220
+
221
+ /** Variables a safe body binds: those of positive literals, comparisons and aggregate results. */
222
+ const bodyVariables = (body: ReadonlyArray<Ast.Literal>): string[] => {
223
+ const names = new Set<string>();
224
+ for (const literal of body) {
225
+ if (literal.type === 'atom' && !literal.negated) {
226
+ Ast.variablesOf(literal.atom.terms).forEach((name) => names.add(name));
227
+ } else if (literal.type === 'comparison') {
228
+ Ast.variablesOf([literal.left, literal.right]).forEach((name) => names.add(name));
229
+ } else if (literal.type === 'aggregate') {
230
+ Ast.variablesOf([literal.result]).forEach((name) => names.add(name));
231
+ }
232
+ }
233
+ return [...names];
234
+ };
@@ -0,0 +1,79 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { type RDF } from '@dxos/pipeline-rdf';
8
+
9
+ import * as Encoding from './Encoding.ts';
10
+ import * as Vocabulary from './Vocabulary.ts';
11
+
12
+ const REFUSAL: RDF.Fact = {
13
+ id: 'fact-1',
14
+ assertion: {
15
+ subject: { kind: 'entity', entity: 'dima', label: 'Dima' },
16
+ predicate: 'will-work-on',
17
+ object: { kind: 'literal', literal: 'agent plugin' },
18
+ validFrom: '2027-01-05',
19
+ validTo: '2027-01-12',
20
+ quote: "I'm busy this week, can't help with the agent plugin",
21
+ },
22
+ factuality: { value: 'CT-', polarity: '-', confidence: 0.8, nature: 'epistemic' },
23
+ illocution: { force: 'commissive', mood: 'declarative', addressee: 'rich' },
24
+ attribution: {
25
+ agent: 'dima',
26
+ source: 'dxn:queue:chat:msg-1',
27
+ generatedAtTime: '2027-01-05T10:00:00.000Z',
28
+ wasDerivedFrom: ['fact-0'],
29
+ span: { start: 0, end: 52 },
30
+ },
31
+ recordedAt: '2027-01-05T10:00:05.000Z',
32
+ extractor: { id: 'default', model: 'test', version: '1' },
33
+ sourceHash: 'abc',
34
+ pass: 'pass-1',
35
+ };
36
+
37
+ const MINIMAL: RDF.Fact = {
38
+ id: 'fact-2',
39
+ assertion: {
40
+ subject: { kind: 'entity', entity: 'release' },
41
+ predicate: 'shipped',
42
+ object: { kind: 'literal', literal: 'npm' },
43
+ },
44
+ factuality: { value: 'CT+', polarity: '+' },
45
+ attribution: { source: 'dxn:queue:chat:msg-2', generatedAtTime: '2027-01-07T16:00:00.000Z' },
46
+ recordedAt: '2027-01-07T16:00:01.000Z',
47
+ extractor: { id: 'default', model: 'test', version: '1' },
48
+ sourceHash: 'def',
49
+ };
50
+
51
+ const byRelation = (entries: ReadonlyArray<{ relation: string; tuple: ReadonlyArray<unknown> }>) =>
52
+ Object.fromEntries(entries.map(({ relation, tuple }) => [relation, tuple]));
53
+
54
+ describe('Encoding', () => {
55
+ test('encodes fact and metadata relations keyed by the fact id', ({ expect }) => {
56
+ const entries = Encoding.encode(REFUSAL, Vocabulary.make(Vocabulary.DEFAULT_ENTRIES));
57
+ const relations = byRelation(entries);
58
+ expect(relations.fact).toEqual(['fact-1', 'dima', 'works_on', 'agent plugin']);
59
+ expect(relations.surface).toEqual(['fact-1', 'will-work-on']);
60
+ expect(relations.speaker).toEqual(['fact-1', 'dima']);
61
+ expect(relations.saidAt).toEqual(['fact-1', '2027-01-05T10:00:00.000Z']);
62
+ expect(relations.force).toEqual(['fact-1', 'commissive']);
63
+ expect(relations.addressee).toEqual(['fact-1', 'rich']);
64
+ expect(relations.polarity).toEqual(['fact-1', '-']);
65
+ expect(relations.confidence).toEqual(['fact-1', 0.8]);
66
+ expect(relations.supersedes).toEqual(['fact-1', 'fact-0']);
67
+ expect(relations.pass).toEqual(['fact-1', 'pass-1']);
68
+ expect(entries.every(({ relation, tuple }) => Encoding.RELATIONS[relation] === tuple.length)).toBe(true);
69
+ expect(Encoding.factIds(entries)).toEqual(['fact-1']);
70
+ });
71
+
72
+ test('a fact without an illocution is assertive and omits absent fields', ({ expect }) => {
73
+ const relations = byRelation(Encoding.encode(MINIMAL));
74
+ expect(relations.force).toEqual(['fact-2', 'assertive']);
75
+ expect(Object.keys(relations).sort()).toEqual(
76
+ ['fact', 'factuality', 'force', 'polarity', 'recordedAt', 'saidAt', 'source', 'surface'].sort(),
77
+ );
78
+ });
79
+ });
@@ -0,0 +1,99 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import type * as Engine from '@dxos/datalog/Engine';
8
+ import { RDF } from '@dxos/pipeline-rdf';
9
+
10
+ import type * as Vocabulary from './Vocabulary.ts';
11
+
12
+ /** Relations every fact contributes to, keyed by the fact id `F`. */
13
+ export const FACT_RELATIONS = {
14
+ fact: 4,
15
+ speaker: 2,
16
+ force: 2,
17
+ polarity: 2,
18
+ mood: 2,
19
+ factuality: 2,
20
+ addressee: 2,
21
+ quote: 2,
22
+ source: 2,
23
+ saidAt: 2,
24
+ surface: 2,
25
+ supersedes: 2,
26
+ validFrom: 2,
27
+ validTo: 2,
28
+ confidence: 2,
29
+ nature: 2,
30
+ recordedAt: 2,
31
+ pass: 2,
32
+ } as const;
33
+
34
+ /** Relations the goal runtime maintains: sub-goal status and proposed actions. */
35
+ export const GOAL_RELATIONS = {
36
+ subgoal: 2,
37
+ status: 2,
38
+ action: 2,
39
+ actionArg: 3,
40
+ } as const;
41
+
42
+ /** Every base relation a goal rule may read. */
43
+ export const RELATIONS: Readonly<Record<string, number>> = { ...FACT_RELATIONS, ...GOAL_RELATIONS };
44
+
45
+ /**
46
+ * Encodes a fact as `fact(F, S, P, O)` plus one metadata relation per present field. `P` is the
47
+ * canonical predicate when the vocabulary knows the surface form, which `surface(F, …)` keeps; a fact
48
+ * without an illocution is `assertive`, and `supersedes` lists `attribution.wasDerivedFrom`.
49
+ */
50
+ export const encode = (fact: RDF.Fact, vocabulary?: Vocabulary.Vocabulary): Engine.Entry[] => {
51
+ const { id, assertion, factuality, illocution, attribution } = fact;
52
+ const entries: Engine.Entry[] = [
53
+ {
54
+ relation: 'fact',
55
+ tuple: [
56
+ id,
57
+ RDF.termValue(assertion.subject),
58
+ vocabulary?.resolve(assertion.predicate) ?? assertion.predicate,
59
+ RDF.termValue(assertion.object),
60
+ ],
61
+ },
62
+ { relation: 'surface', tuple: [id, assertion.predicate] },
63
+ { relation: 'force', tuple: [id, illocution?.force ?? 'assertive'] },
64
+ { relation: 'polarity', tuple: [id, factuality.polarity] },
65
+ { relation: 'factuality', tuple: [id, factuality.value] },
66
+ { relation: 'source', tuple: [id, attribution.source] },
67
+ { relation: 'saidAt', tuple: [id, attribution.generatedAtTime] },
68
+ { relation: 'recordedAt', tuple: [id, fact.recordedAt] },
69
+ ];
70
+ const optional: ReadonlyArray<[string, string | number | undefined]> = [
71
+ ['speaker', attribution.agent],
72
+ ['mood', illocution?.mood],
73
+ ['addressee', illocution?.addressee],
74
+ ['quote', assertion.quote],
75
+ ['validFrom', assertion.validFrom],
76
+ ['validTo', assertion.validTo],
77
+ ['confidence', factuality.confidence],
78
+ ['nature', factuality.nature],
79
+ ['pass', fact.pass],
80
+ ];
81
+ for (const [relation, value] of optional) {
82
+ if (value !== undefined) {
83
+ entries.push({ relation, tuple: [id, value] });
84
+ }
85
+ }
86
+ for (const superseded of attribution.wasDerivedFrom ?? []) {
87
+ entries.push({ relation: 'supersedes', tuple: [id, superseded] });
88
+ }
89
+ return entries;
90
+ };
91
+
92
+ /** The fact ids among base entries (from provenance). */
93
+ export const factIds = (entries: ReadonlyArray<Engine.Entry>): string[] => [
94
+ ...new Set(
95
+ entries.flatMap(({ relation, tuple }) =>
96
+ relation in FACT_RELATIONS && typeof tuple[0] === 'string' ? [tuple[0]] : [],
97
+ ),
98
+ ),
99
+ ];
@@ -0,0 +1,186 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { type RDF } from '@dxos/pipeline-rdf';
8
+
9
+ import * as GoalRules from './GoalRules.ts';
10
+ import { REFERENCE, SCENARIOS, WRONG, simulate, toFact } from './testing/index.ts';
11
+
12
+ describe('GoalRules', () => {
13
+ describe('example goals replay against their reference compilations', () => {
14
+ test.for(SCENARIOS.map((scenario) => [scenario.n, scenario.goal] as const))(
15
+ 'goal %i: %s',
16
+ ([number], { expect }) => {
17
+ const scenario = SCENARIOS.find((candidate) => candidate.n === number);
18
+ expect(scenario).toBeDefined();
19
+ if (scenario) {
20
+ const result = simulate(scenario, REFERENCE[number]);
21
+ expect(result.failures).toEqual([]);
22
+ }
23
+ },
24
+ );
25
+ });
26
+
27
+ describe('replay rejects wrong compilations', () => {
28
+ test.for(WRONG.map(({ scenario, note, source }) => [scenario, note, source] as const))(
29
+ 'goal %i: %s',
30
+ ([number, , source], { expect }) => {
31
+ const scenario = SCENARIOS.find((candidate) => candidate.n === number);
32
+ expect(scenario).toBeDefined();
33
+ if (scenario) {
34
+ const result = simulate(scenario, source);
35
+ expect(result.steps).toHaveLength(scenario.steps.length);
36
+ expect(result.failures.length).toBeGreaterThan(0);
37
+ }
38
+ },
39
+ );
40
+ });
41
+
42
+ test('wakes once per new binding and reports the facts behind it', ({ expect }) => {
43
+ const createdAt = Date.parse('2027-01-04T09:00:00Z');
44
+ const rules = GoalRules.make({ source: 'wake(reply) :- speaker(F, dima), about(F, "plugin").', createdAt });
45
+ const say = (id: string, quote: string, minutes: number) => {
46
+ const saidAt = new Date(createdAt + minutes * 60_000).toISOString();
47
+ return rules.update({
48
+ at: Date.parse(saidAt),
49
+ facts: [
50
+ toFact(
51
+ {
52
+ id,
53
+ speaker: 'dima',
54
+ quote,
55
+ s: 'dima',
56
+ p: 'says',
57
+ o: 'x',
58
+ force: 'assertive',
59
+ polarity: '+',
60
+ mood: 'declarative',
61
+ source: 'chat',
62
+ factuality: 'CT+',
63
+ },
64
+ saidAt,
65
+ ),
66
+ ],
67
+ });
68
+ };
69
+
70
+ expect(say('f1', 'the plugin is ready', 1).wakes).toEqual([{ label: 'reply', cause: 'rule', facts: ['f1'] }]);
71
+ expect(say('f2', 'lunch?', 2).wakes).toEqual([]);
72
+ expect(say('f3', 'plugin docs too', 3).wakes).toEqual([{ label: 'reply', cause: 'rule', facts: ['f3'] }]);
73
+ });
74
+
75
+ test('wakes when achieved first holds and when a sub-goal changes status', ({ expect }) => {
76
+ const rules = GoalRules.make({
77
+ source:
78
+ 'achieved(goal) :- subgoal(goal, G), status(G, done), not open.\nopen :- subgoal(goal, G), status(G, active).',
79
+ createdAt: 0,
80
+ });
81
+ expect(rules.update({ at: 1, subgoals: { first: 'active', second: 'done' } }).wakes).toEqual([]);
82
+ const evaluation = rules.update({ at: 2, subgoals: { first: 'done', second: 'done' } });
83
+ expect(evaluation.achieved).toBe(true);
84
+ expect(evaluation.wakes.map(({ label, cause }) => [label, cause])).toEqual([
85
+ ['first', 'subgoal'],
86
+ ['achieved', 'achieved'],
87
+ ]);
88
+ expect(rules.update({ at: 3 }).wakes).toEqual([]);
89
+ });
90
+
91
+ test('checks proposed actions without keeping them', ({ expect }) => {
92
+ const rules = GoalRules.make({ source: REFERENCE[7], createdAt: 0 });
93
+ const friday = { id: 'a1', kind: 'book_meeting', args: { start: '2027-01-08T15:00:00Z' } };
94
+ expect(rules.checkAction(friday).blocked).toBe(true);
95
+ expect(rules.checkAction({ ...friday, id: 'a2', args: { start: '2027-01-05T10:00:00Z' } }).blocked).toBe(false);
96
+ expect(rules.checkAction(friday).blocked).toBe(true);
97
+ });
98
+
99
+ describe('working memory', () => {
100
+ const DAY = 86_400_000;
101
+ const said = (id: string, object: string, day: number, validTo?: string): RDF.Fact => {
102
+ const fact = toFact(
103
+ {
104
+ id,
105
+ speaker: 'dima',
106
+ quote: object,
107
+ s: 'dima',
108
+ p: 'says',
109
+ o: object,
110
+ force: 'assertive',
111
+ polarity: '+',
112
+ mood: 'declarative',
113
+ source: 'chat',
114
+ factuality: 'CT+',
115
+ },
116
+ new Date(day * DAY).toISOString(),
117
+ );
118
+ return validTo === undefined ? fact : { ...fact, assertion: { ...fact.assertion, validTo } };
119
+ };
120
+
121
+ test('retires the oldest facts past the cap instead of rejecting them', ({ expect }) => {
122
+ const rules = GoalRules.make({ source: 'holds(goal) :- fact(_, dima, says, a).', createdAt: 0, maxFacts: 2 });
123
+ expect(rules.update({ at: 1 * DAY, facts: [said('f1', 'a', 1)] }).holds).toBe(true);
124
+ expect(rules.update({ at: 2 * DAY, facts: [said('f2', 'b', 2)] }).holds).toBe(true);
125
+ // A re-sent fact is already in working memory and does not count again.
126
+ expect(rules.update({ at: 3 * DAY, facts: [said('f1', 'a', 1)] }).holds).toBe(true);
127
+ expect(rules.update({ at: 4 * DAY, facts: [said('f3', 'c', 4)] }).holds).toBe(false);
128
+ // A late arrival said before everything kept is itself the oldest, so it retires at once.
129
+ expect(rules.update({ at: 5 * DAY, facts: [said('f4', 'a', 0)] }).holds).toBe(false);
130
+ });
131
+
132
+ test('retires facts once the clock passes their validTo', ({ expect }) => {
133
+ const rules = GoalRules.make({ source: 'holds(goal) :- fact(_, dima, says, a).', createdAt: 0 });
134
+ const validTo = new Date(3 * DAY).toISOString();
135
+ const first = rules.update({ at: 1 * DAY, facts: [said('f1', 'a', 1, validTo)] });
136
+ expect(first.holds).toBe(true);
137
+ expect(rules.update({ at: 2 * DAY }).holds).toBe(true);
138
+ expect(rules.update({ at: 4 * DAY })).toEqual({ at: 4 * DAY, wakes: [], achieved: false, holds: false });
139
+ expect(rules.update({ at: 5 * DAY, facts: [said('f2', 'a', 5, validTo)] }).holds).toBe(false);
140
+ });
141
+
142
+ test('retiring a fact does not wake the goal', ({ expect }) => {
143
+ const rules = GoalRules.make({
144
+ source: 'wake(gap) :- not seen.\nseen :- fact(_, dima, says, b).',
145
+ createdAt: 0,
146
+ maxFacts: 1,
147
+ });
148
+ rules.update({ at: 1 * DAY, facts: [said('f1', 'b', 1)] });
149
+ expect(rules.update({ at: 2 * DAY, facts: [said('f2', 'c', 2)] }).wakes).toEqual([]);
150
+ expect(rules.update({ at: 3 * DAY }).wakes).toEqual([]);
151
+ });
152
+
153
+ test('keeps the facts behind achieved, so retirement never un-achieves the goal', ({ expect }) => {
154
+ const rules = GoalRules.make({
155
+ source: 'achieved(goal) :- fact(_, dima, says, a).',
156
+ createdAt: 0,
157
+ maxFacts: 1,
158
+ });
159
+ const validTo = new Date(2 * DAY).toISOString();
160
+ expect(rules.update({ at: 1 * DAY, facts: [said('f1', 'a', 1, validTo)] }).wakes).toEqual([
161
+ { label: 'achieved', cause: 'achieved', facts: ['f1'] },
162
+ ]);
163
+ expect(rules.update({ at: 3 * DAY, facts: [said('f2', 'b', 3)] })).toEqual({
164
+ at: 3 * DAY,
165
+ wakes: [],
166
+ achieved: true,
167
+ holds: false,
168
+ });
169
+ });
170
+
171
+ test('rejects sub-goals past the cap without applying them', ({ expect }) => {
172
+ const rules = GoalRules.make({
173
+ source:
174
+ 'achieved(goal) :- subgoal(goal, G), status(G, done), not open.\nopen :- subgoal(goal, G), status(G, active).',
175
+ createdAt: 0,
176
+ maxSubgoals: 1,
177
+ });
178
+ rules.update({ at: 1, subgoals: { first: 'active' } });
179
+ expect(() => rules.update({ at: 2, subgoals: { second: 'active' } })).toThrow(GoalRules.CapacityError);
180
+ expect(rules.update({ at: 3, subgoals: { first: 'done' } }).wakes).toEqual([
181
+ { label: 'first', cause: 'subgoal', facts: [] },
182
+ { label: 'achieved', cause: 'achieved', facts: [] },
183
+ ]);
184
+ });
185
+ });
186
+ });