@dxos/brain 0.12.0 → 0.14.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 (41) hide show
  1. package/dist/lib/Builtins.mjs +10 -2
  2. package/dist/lib/Builtins.mjs.map +1 -1
  3. package/dist/lib/Encoding.mjs +12 -2
  4. package/dist/lib/Encoding.mjs.map +1 -1
  5. package/dist/lib/Evaluator.mjs +144 -0
  6. package/dist/lib/Evaluator.mjs.map +1 -0
  7. package/dist/lib/GoalRules.mjs +153 -11
  8. package/dist/lib/GoalRules.mjs.map +1 -1
  9. package/dist/lib/Oracle.mjs +169 -0
  10. package/dist/lib/Oracle.mjs.map +1 -0
  11. package/dist/lib/index.mjs +3 -1
  12. package/dist/types/src/Builtins.d.ts +6 -0
  13. package/dist/types/src/Builtins.d.ts.map +1 -1
  14. package/dist/types/src/Encoding.d.ts +4 -0
  15. package/dist/types/src/Encoding.d.ts.map +1 -1
  16. package/dist/types/src/Encoding.test.d.ts +2 -0
  17. package/dist/types/src/Encoding.test.d.ts.map +1 -0
  18. package/dist/types/src/Evaluator.d.ts +77 -0
  19. package/dist/types/src/Evaluator.d.ts.map +1 -0
  20. package/dist/types/src/Evaluator.test.d.ts +2 -0
  21. package/dist/types/src/Evaluator.test.d.ts.map +1 -0
  22. package/dist/types/src/GoalRules.d.ts +66 -1
  23. package/dist/types/src/GoalRules.d.ts.map +1 -1
  24. package/dist/types/src/Oracle.d.ts +126 -0
  25. package/dist/types/src/Oracle.d.ts.map +1 -0
  26. package/dist/types/src/Oracle.test.d.ts +2 -0
  27. package/dist/types/src/Oracle.test.d.ts.map +1 -0
  28. package/dist/types/src/index.d.ts +2 -0
  29. package/dist/types/src/index.d.ts.map +1 -1
  30. package/dist/types/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +15 -5
  32. package/src/Builtins.ts +12 -1
  33. package/src/Encoding.test.ts +93 -0
  34. package/src/Encoding.ts +9 -0
  35. package/src/Evaluator.test.ts +158 -0
  36. package/src/Evaluator.ts +186 -0
  37. package/src/GoalRules.test.ts +98 -0
  38. package/src/GoalRules.ts +212 -10
  39. package/src/Oracle.test.ts +71 -0
  40. package/src/Oracle.ts +182 -0
  41. package/src/index.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/brain",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Agent brain: pipeline-rdf facts encoded as Datalog relations, a canonical predicate vocabulary, goal built-ins and an incremental goal-rule evaluator.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -38,11 +38,21 @@
38
38
  "types": "./dist/types/src/Encoding.d.ts",
39
39
  "import": "./dist/lib/Encoding.mjs"
40
40
  },
41
+ "./Evaluator": {
42
+ "source": "./src/Evaluator.ts",
43
+ "types": "./dist/types/src/Evaluator.d.ts",
44
+ "import": "./dist/lib/Evaluator.mjs"
45
+ },
41
46
  "./GoalRules": {
42
47
  "source": "./src/GoalRules.ts",
43
48
  "types": "./dist/types/src/GoalRules.d.ts",
44
49
  "import": "./dist/lib/GoalRules.mjs"
45
50
  },
51
+ "./Oracle": {
52
+ "source": "./src/Oracle.ts",
53
+ "types": "./dist/types/src/Oracle.d.ts",
54
+ "import": "./dist/lib/Oracle.mjs"
55
+ },
46
56
  "./Vocabulary": {
47
57
  "source": "./src/Vocabulary.ts",
48
58
  "types": "./dist/types/src/Vocabulary.d.ts",
@@ -61,10 +71,10 @@
61
71
  "src"
62
72
  ],
63
73
  "dependencies": {
64
- "@dxos/pipeline-rdf": "0.12.0",
65
- "@dxos/datalog": "0.12.0",
66
- "@dxos/errors": "0.12.0",
67
- "@dxos/util": "0.12.0"
74
+ "@dxos/datalog": "0.14.0",
75
+ "@dxos/pipeline-rdf": "0.14.0",
76
+ "@dxos/errors": "0.14.0",
77
+ "@dxos/util": "0.14.0"
68
78
  },
69
79
  "devDependencies": {
70
80
  "effect": "4.0.0",
package/src/Builtins.ts CHANGED
@@ -9,6 +9,7 @@ import * as Builtin from '@dxos/datalog/Builtin';
9
9
  /** Finds facts about a topic; a semantic index replaces the keyword one without touching rules. */
10
10
  export interface TextIndex {
11
11
  add(factId: string, text: string): void;
12
+ remove(factId: string): void;
12
13
  /** True if the fact is about `query`. */
13
14
  matches(factId: string, query: string): boolean;
14
15
  /** Every fact about `query`. */
@@ -18,6 +19,7 @@ export interface TextIndex {
18
19
  /** The entities each fact concerns (entity resolution), for scoping possessive goals. */
19
20
  export interface EntityIndex {
20
21
  add(factId: string, entities: ReadonlyArray<string>): void;
22
+ remove(factId: string): void;
21
23
  concerns(factId: string): ReadonlyArray<string>;
22
24
  facts(entity: string): Iterable<string>;
23
25
  }
@@ -109,6 +111,10 @@ export class KeywordIndex implements TextIndex {
109
111
  this.#texts.set(factId, text);
110
112
  }
111
113
 
114
+ remove(factId: string): void {
115
+ this.#texts.delete(factId);
116
+ }
117
+
112
118
  matches(factId: string, query: string): boolean {
113
119
  return keywordMatch(this.#texts.get(factId) ?? '', query);
114
120
  }
@@ -130,6 +136,10 @@ export class MemoryEntityIndex implements EntityIndex {
130
136
  this.#byFact.set(factId, entities);
131
137
  }
132
138
 
139
+ remove(factId: string): void {
140
+ this.#byFact.delete(factId);
141
+ }
142
+
133
143
  concerns(factId: string): ReadonlyArray<string> {
134
144
  return this.#byFact.get(factId) ?? [];
135
145
  }
@@ -154,7 +164,8 @@ export const parseDuration = (duration: string | number): number | undefined =>
154
164
 
155
165
  const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
156
166
 
157
- const parseTime = (value: string | number): number | undefined => {
167
+ /** Parses an epoch-ms number or an ISO timestamp. */
168
+ export const parseTime = (value: string | number): number | undefined => {
158
169
  const time = typeof value === 'number' ? value : Date.parse(value);
159
170
  return Number.isNaN(time) ? undefined : time;
160
171
  };
@@ -0,0 +1,93 @@
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
+
80
+ test('formats a fact as ground Datalog facts in the rules dialect', ({ expect }) => {
81
+ expect(Encoding.format(MINIMAL)).toEqual([
82
+ 'fact("fact-2", release, shipped, npm).',
83
+ 'surface("fact-2", shipped).',
84
+ 'force("fact-2", assertive).',
85
+ 'polarity("fact-2", "+").',
86
+ 'factuality("fact-2", "CT+").',
87
+ 'source("fact-2", "dxn:queue:chat:msg-2").',
88
+ 'saidAt("fact-2", "2027-01-07T16:00:00.000Z").',
89
+ 'recordedAt("fact-2", "2027-01-07T16:00:01.000Z").',
90
+ ]);
91
+ expect(Encoding.formatEntry({ relation: 'confidence', tuple: ['fact-1', 0.8] })).toBe('confidence("fact-1", 0.8).');
92
+ });
93
+ });
package/src/Encoding.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  // @import-as-namespace
6
6
 
7
+ import * as Ast from '@dxos/datalog/Ast';
7
8
  import type * as Engine from '@dxos/datalog/Engine';
8
9
  import { RDF } from '@dxos/pipeline-rdf';
9
10
 
@@ -97,3 +98,11 @@ export const factIds = (entries: ReadonlyArray<Engine.Entry>): string[] => [
97
98
  ),
98
99
  ),
99
100
  ];
101
+
102
+ /** An entry as a ground Datalog fact in the dialect goal rules are written in, e.g. `speaker("fact-1", dima).`. */
103
+ export const formatEntry = ({ relation, tuple }: Engine.Entry): string =>
104
+ Ast.formatRule({ head: Ast.atom(relation, tuple.map(Ast.constant)), body: [] });
105
+
106
+ /** The relations the rules engine sees for a fact ({@link encode}), one ground Datalog fact per line. */
107
+ export const format = (fact: RDF.Fact, vocabulary?: Vocabulary.Vocabulary): string[] =>
108
+ encode(fact, vocabulary).map(formatEntry);
@@ -0,0 +1,158 @@
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 Compiler from './Compiler.ts';
10
+ import * as Evaluator from './Evaluator.ts';
11
+ import { REFERENCE, SCENARIOS, simulate, toFact } from './testing/index.ts';
12
+
13
+ const START = '2027-01-04T09:00:00.000Z';
14
+ const minutes = (count: number): number => Date.parse(START) + count * 60_000;
15
+
16
+ const said = (id: string, speaker: string, quote: string, at: number): RDF.Fact =>
17
+ toFact(
18
+ {
19
+ id,
20
+ speaker,
21
+ quote,
22
+ s: speaker,
23
+ p: 'says',
24
+ o: 'x',
25
+ force: 'assertive',
26
+ polarity: '+',
27
+ mood: 'declarative',
28
+ source: 'chat:general',
29
+ factuality: 'CT+',
30
+ },
31
+ new Date(at).toISOString(),
32
+ );
33
+
34
+ const watchDima: Evaluator.Subscription = {
35
+ id: 'watch',
36
+ rules: 'wake(dima) :- speaker(F, dima), saidAt(F, T), T >= "2027-01-04T09:00:00.000Z".',
37
+ createdAt: START,
38
+ };
39
+
40
+ describe('Evaluator', () => {
41
+ test('queues one event per new binding, with the facts behind it', ({ expect }) => {
42
+ const evaluator = Evaluator.make();
43
+ evaluator.add(watchDima);
44
+ const fact = said('f1', 'dima', 'I am on the indexer', minutes(1));
45
+
46
+ const events = evaluator.push([fact, said('f2', 'rich', 'Hello', minutes(1))], { at: minutes(1) });
47
+ expect(events).toEqual([
48
+ {
49
+ id: Evaluator.eventId('watch', 'dima', ['f1'], minutes(1)),
50
+ subscription: 'watch',
51
+ label: 'dima',
52
+ cause: 'rule',
53
+ facts: [fact],
54
+ at: minutes(1),
55
+ },
56
+ ]);
57
+ // The same fact again is no new binding.
58
+ expect(evaluator.push([fact], { at: minutes(2) })).toEqual([]);
59
+ });
60
+
61
+ test('quiet speakers are evaluated but wake nothing on their own', ({ expect }) => {
62
+ const evaluator = Evaluator.make();
63
+ evaluator.add({ id: 'any', rules: 'wake(any) :- fact(F, _, _, _).', createdAt: START });
64
+ expect(
65
+ evaluator.push([said('own', 'kai', 'Dima is on it', minutes(1))], { at: minutes(1), quiet: ['kai'] }),
66
+ ).toEqual([]);
67
+ expect(
68
+ evaluator.push([said('f1', 'dima', 'I am on it', minutes(2))], { at: minutes(2), quiet: ['kai'] }),
69
+ ).toHaveLength(1);
70
+ });
71
+
72
+ test('a subscription added later reads history but wakes only on what follows', ({ expect }) => {
73
+ const evaluator = Evaluator.make();
74
+ evaluator.push([said('old', 'dima', 'Earlier', minutes(1))], { at: minutes(1) });
75
+ evaluator.add({
76
+ id: 'count',
77
+ rules: 'wake(second) :- N = count : { speaker(_, dima) }, N >= 2.',
78
+ createdAt: START,
79
+ });
80
+ const events = evaluator.push([said('new', 'dima', 'Later', minutes(2))], { at: minutes(2) });
81
+ expect(events.map(({ label }) => label)).toEqual(['second']);
82
+ });
83
+
84
+ test('hydrate re-derives state silently; the next push wakes only on new facts', ({ expect }) => {
85
+ const history = [said('f1', 'dima', 'One', minutes(1)), said('f2', 'dima', 'Two', minutes(2))];
86
+ const evaluator = Evaluator.make();
87
+ evaluator.hydrate([watchDima], history, minutes(3));
88
+ expect(evaluator.subscriptions.map(({ id }) => id)).toEqual(['watch']);
89
+ expect(evaluator.push(history, { at: minutes(4) })).toEqual([]);
90
+ expect(evaluator.push([said('f3', 'dima', 'Three', minutes(5))], { at: minutes(5) }).map(({ id }) => id)).toEqual([
91
+ Evaluator.eventId('watch', 'dima', ['f3'], minutes(5)),
92
+ ]);
93
+ });
94
+
95
+ test('ticks fire time-driven wakes, and report when the clock next matters', ({ expect }) => {
96
+ const evaluator = Evaluator.make();
97
+ evaluator.add({ id: 'daily', rules: 'wake(practice) :- every(1d).', createdAt: START });
98
+ evaluator.add({ id: 'followup', rules: 'wake(followup) :- elapsed(goal, 2d).', createdAt: START });
99
+ expect(evaluator.nextDueAt()).toBe(minutes(24 * 60));
100
+
101
+ expect(evaluator.tick(minutes(60))).toEqual([]);
102
+ const day = evaluator.tick(minutes(24 * 60 + 1));
103
+ expect(day.map(({ label, cause, facts }) => ({ label, cause, facts }))).toEqual([
104
+ { label: 'practice', cause: 'rule', facts: [] },
105
+ ]);
106
+ expect(day[0].id).toBe(Evaluator.eventId('daily', 'practice', [], minutes(24 * 60 + 1)));
107
+ expect(evaluator.nextDueAt()).toBe(minutes(2 * 24 * 60));
108
+ expect(
109
+ evaluator
110
+ .tick(minutes(2 * 24 * 60))
111
+ .map(({ label }) => label)
112
+ .sort(),
113
+ ).toEqual(['followup', 'practice']);
114
+ });
115
+
116
+ test('nextDueAt covers due deadlines and facts that start their own clock', ({ expect }) => {
117
+ const evaluator = Evaluator.make();
118
+ evaluator.add({ id: 'tax', rules: 'wake(remind) :- due("2027-01-10T00:00:00Z", 1d).', createdAt: START });
119
+ expect(evaluator.nextDueAt()).toBe(Date.parse('2027-01-09T00:00:00Z'));
120
+ evaluator.remove('tax');
121
+ expect(evaluator.nextDueAt()).toBeUndefined();
122
+
123
+ evaluator.add({ id: 'stale', rules: 'wake(stale) :- speaker(F, dima), elapsed(F, 1h).', createdAt: START });
124
+ evaluator.push([said('f1', 'dima', 'Will do', minutes(10))], { at: minutes(10) });
125
+ expect(evaluator.nextDueAt()).toBe(minutes(70));
126
+ });
127
+
128
+ test('rules that do not compile are refused and leave the evaluator unchanged', ({ expect }) => {
129
+ const evaluator = Evaluator.make();
130
+ expect(() => evaluator.add({ id: 'bad', rules: 'wake(x) :- helpz_with(dima, X).', createdAt: START })).toThrow(
131
+ Compiler.CompileError,
132
+ );
133
+ expect(evaluator.has('bad')).toBe(false);
134
+ });
135
+
136
+ describe('wakes as GoalRules does for the example goals', () => {
137
+ // Goals 5 and 7 drive sub-goals and actions, which a subscription does not carry.
138
+ const plain = SCENARIOS.filter(({ n }) => n !== 5 && n !== 7);
139
+ test.for(plain.map(({ n, goal }) => [n, goal] as const))('goal %i: %s', ([number], { expect }) => {
140
+ const scenario = SCENARIOS.find(({ n }) => n === number);
141
+ expect(scenario).toBeDefined();
142
+ if (!scenario) {
143
+ return;
144
+ }
145
+ const reference = simulate(scenario, REFERENCE[number]);
146
+ const evaluator = Evaluator.make();
147
+ evaluator.add({ id: `goal-${number}`, rules: REFERENCE[number], createdAt: scenario.createdAt });
148
+ const woke = scenario.steps.map(
149
+ (step) =>
150
+ evaluator.push(
151
+ (step.facts ?? []).map((fact) => toFact(fact, step.at)),
152
+ { at: Date.parse(step.at) },
153
+ ).length > 0,
154
+ );
155
+ expect(woke).toEqual(reference.steps.map(({ wake }) => wake));
156
+ });
157
+ });
158
+ });
@@ -0,0 +1,186 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import { type RDF } from '@dxos/pipeline-rdf';
8
+
9
+ import * as GoalRules from './GoalRules.ts';
10
+
11
+ /** A standing goal the evaluator watches: its compiled rules and when it began. */
12
+ export type Subscription = {
13
+ readonly id: string;
14
+ /** A goal program (`wake`, `achieved`, `holds`, `blocks`); see `Compiler`. */
15
+ readonly rules: string;
16
+ /** ISO time the subscription began; the rules' clock starts here. */
17
+ readonly createdAt: string;
18
+ };
19
+
20
+ /** A wake of one subscription, ready to queue in its outbox. */
21
+ export type Event = {
22
+ /**
23
+ * Stable for the same wake: the subscription, the wake label and the facts behind it (or, for a
24
+ * wake no fact caused, the evaluation time), so a host that re-derives a wake queues it once.
25
+ */
26
+ readonly id: string;
27
+ readonly subscription: string;
28
+ readonly label: string;
29
+ readonly cause: GoalRules.Wake['cause'];
30
+ /** The facts behind the wake, in the order they arrived. */
31
+ readonly facts: ReadonlyArray<RDF.Fact>;
32
+ /** Evaluation time (epoch ms). */
33
+ readonly at: number;
34
+ };
35
+
36
+ export type PushOptions = {
37
+ /** Evaluation time (epoch ms). */
38
+ readonly at: number;
39
+ /**
40
+ * Speakers (entity ids) whose facts are evaluated but wake nothing on their own: an agent's own
41
+ * words must not wake it. A wake resting on a quiet fact and another one still wakes.
42
+ */
43
+ readonly quiet?: ReadonlyArray<string>;
44
+ };
45
+
46
+ /** The id of an event: see {@link Event.id}. */
47
+ export const eventId = (subscription: string, label: string, facts: ReadonlyArray<string>, at: number): string =>
48
+ facts.length > 0 ? `${subscription}:${label}:${[...facts].sort().join(',')}` : `${subscription}:${label}@${at}`;
49
+
50
+ /**
51
+ * Evaluates every subscription of one brain over a shared fact stream. Synchronous and in memory: a
52
+ * host keeps the facts and the outboxes in its own store, feeds pushes and clock ticks through
53
+ * {@link Evaluator.push} and {@link Evaluator.tick}, and after a restart rebuilds the evaluator with
54
+ * {@link Evaluator.hydrate}, which re-derives the rules' state without emitting events.
55
+ */
56
+ export class Evaluator {
57
+ readonly #goals = new Map<string, { subscription: Subscription; rules: GoalRules.GoalRules }>();
58
+ /** Recent facts, which seed a subscription added later and resolve the facts behind a wake. */
59
+ readonly #facts = new Map<string, RDF.Fact>();
60
+ readonly #maxFacts: number;
61
+ #at = 0;
62
+
63
+ constructor({ maxFacts = GoalRules.MAX_FACTS }: { maxFacts?: number } = {}) {
64
+ this.#maxFacts = maxFacts;
65
+ }
66
+
67
+ /** The subscriptions, in the order they were added. */
68
+ get subscriptions(): Subscription[] {
69
+ return [...this.#goals.values()].map(({ subscription }) => subscription);
70
+ }
71
+
72
+ has(id: string): boolean {
73
+ return this.#goals.has(id);
74
+ }
75
+
76
+ /**
77
+ * Adds or replaces a subscription. It sees the facts already held (said before it began, so its
78
+ * rules can read history) without waking on them.
79
+ * @throws Compiler.CompileError if the rules do not compile; nothing is changed.
80
+ */
81
+ add(subscription: Subscription): void {
82
+ const rules = makeRules(subscription);
83
+ if (this.#facts.size > 0) {
84
+ // Wakes on facts said before the subscription existed are discarded: it watches from now on.
85
+ rules.update({ at: Math.max(this.#at, startOf(subscription)), facts: [...this.#facts.values()] });
86
+ }
87
+ this.#goals.set(subscription.id, { subscription, rules });
88
+ }
89
+
90
+ /** Removes a subscription; false when it was not held. */
91
+ remove(id: string): boolean {
92
+ return this.#goals.delete(id);
93
+ }
94
+
95
+ /** Evaluates new facts at time `at`; returns the wakes, one event each. */
96
+ push(facts: ReadonlyArray<RDF.Fact>, { at, quiet = [] }: PushOptions): Event[] {
97
+ const quietIds = new Set(
98
+ facts
99
+ .filter(({ attribution }) => attribution.agent !== undefined && quiet.includes(attribution.agent))
100
+ .map(({ id }) => id),
101
+ );
102
+ this.#remember(facts);
103
+ return this.#evaluate({ at, facts }, quietIds);
104
+ }
105
+
106
+ /** Re-evaluates the clock at time `at` (a scheduled tick); returns the wakes. */
107
+ tick(at: number): Event[] {
108
+ return this.#evaluate({ at }, new Set());
109
+ }
110
+
111
+ /**
112
+ * Rebuilds state after a restart: adds the subscriptions and replays the facts as of `at` (the last
113
+ * evaluation before the restart), emitting nothing. Wakes due since then come from the next
114
+ * {@link tick} or {@link push}.
115
+ * @throws Compiler.CompileError if a subscription's rules do not compile.
116
+ */
117
+ hydrate(subscriptions: ReadonlyArray<Subscription>, facts: ReadonlyArray<RDF.Fact>, at: number): void {
118
+ this.#goals.clear();
119
+ this.#facts.clear();
120
+ this.#remember(facts);
121
+ this.#at = at;
122
+ for (const subscription of subscriptions) {
123
+ const rules = makeRules(subscription);
124
+ rules.update({ at: Math.max(at, startOf(subscription)), facts: [...this.#facts.values()] });
125
+ this.#goals.set(subscription.id, { subscription, rules });
126
+ }
127
+ }
128
+
129
+ /** The earliest time any subscription's clock can next change; see `GoalRules.nextDueAt`. */
130
+ nextDueAt(): number | undefined {
131
+ const due = [...this.#goals.values()]
132
+ .map(({ rules }) => rules.nextDueAt())
133
+ .filter((time): time is number => time !== undefined);
134
+ return due.length === 0 ? undefined : Math.min(...due);
135
+ }
136
+
137
+ #evaluate(input: { at: number; facts?: ReadonlyArray<RDF.Fact> }, quiet: ReadonlySet<string>): Event[] {
138
+ this.#at = Math.max(this.#at, input.at);
139
+ const events: Event[] = [];
140
+ for (const { subscription, rules } of this.#goals.values()) {
141
+ const { wakes } = rules.update({ at: input.at, facts: input.facts });
142
+ for (const wake of wakes) {
143
+ if (wake.facts.length > 0 && wake.facts.every((id) => quiet.has(id))) {
144
+ continue;
145
+ }
146
+ events.push({
147
+ id: eventId(subscription.id, wake.label, wake.facts, input.at),
148
+ subscription: subscription.id,
149
+ label: wake.label,
150
+ cause: wake.cause,
151
+ facts: wake.facts.flatMap((id) => {
152
+ const fact = this.#facts.get(id);
153
+ return fact ? [fact] : [];
154
+ }),
155
+ at: input.at,
156
+ });
157
+ }
158
+ }
159
+ return events;
160
+ }
161
+
162
+ /** Keeps the newest facts, at most `maxFacts`, in arrival order. */
163
+ #remember(facts: ReadonlyArray<RDF.Fact>): void {
164
+ for (const fact of facts) {
165
+ this.#facts.delete(fact.id);
166
+ this.#facts.set(fact.id, fact);
167
+ }
168
+ for (const id of this.#facts.keys()) {
169
+ if (this.#facts.size <= this.#maxFacts) {
170
+ break;
171
+ }
172
+ this.#facts.delete(id);
173
+ }
174
+ }
175
+ }
176
+
177
+ const startOf = ({ createdAt }: Subscription): number => {
178
+ const time = Date.parse(createdAt);
179
+ return Number.isNaN(time) ? 0 : time;
180
+ };
181
+
182
+ const makeRules = (subscription: Subscription): GoalRules.GoalRules =>
183
+ GoalRules.make({ source: subscription.rules, createdAt: startOf(subscription) });
184
+
185
+ /** Creates an evaluator. */
186
+ export const make = (options?: { maxFacts?: number }): Evaluator => new Evaluator(options);
@@ -4,6 +4,8 @@
4
4
 
5
5
  import { describe, test } from 'vitest';
6
6
 
7
+ import { type RDF } from '@dxos/pipeline-rdf';
8
+
7
9
  import * as GoalRules from './GoalRules.ts';
8
10
  import { REFERENCE, SCENARIOS, WRONG, simulate, toFact } from './testing/index.ts';
9
11
 
@@ -93,4 +95,100 @@ describe('GoalRules', () => {
93
95
  expect(rules.checkAction({ ...friday, id: 'a2', args: { start: '2027-01-05T10:00:00Z' } }).blocked).toBe(false);
94
96
  expect(rules.checkAction(friday).blocked).toBe(true);
95
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
+ test('every fires once per period, also when each evaluation falls on a boundary', ({ expect }) => {
187
+ const createdAt = Date.parse('2027-01-04T09:00:00Z');
188
+ const day = 24 * 60 * 60_000;
189
+ const rules = GoalRules.make({ source: 'wake(practice) :- every(1d).', createdAt });
190
+ expect(rules.update({ at: createdAt + day }).wakes.map(({ label }) => label)).toEqual(['practice']);
191
+ expect(rules.update({ at: createdAt + 2 * day }).wakes.map(({ label }) => label)).toEqual(['practice']);
192
+ expect(rules.update({ at: createdAt + 2 * day + 1 }).wakes).toEqual([]);
193
+ });
96
194
  });