@dxos/brain 0.13.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 (39) hide show
  1. package/dist/lib/Builtins.mjs +4 -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 +62 -4
  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 +2 -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/Evaluator.d.ts +77 -0
  17. package/dist/types/src/Evaluator.d.ts.map +1 -0
  18. package/dist/types/src/Evaluator.test.d.ts +2 -0
  19. package/dist/types/src/Evaluator.test.d.ts.map +1 -0
  20. package/dist/types/src/GoalRules.d.ts +6 -0
  21. package/dist/types/src/GoalRules.d.ts.map +1 -1
  22. package/dist/types/src/Oracle.d.ts +126 -0
  23. package/dist/types/src/Oracle.d.ts.map +1 -0
  24. package/dist/types/src/Oracle.test.d.ts +2 -0
  25. package/dist/types/src/Oracle.test.d.ts.map +1 -0
  26. package/dist/types/src/index.d.ts +2 -0
  27. package/dist/types/src/index.d.ts.map +1 -1
  28. package/dist/types/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +15 -5
  30. package/src/Builtins.ts +2 -1
  31. package/src/Encoding.test.ts +14 -0
  32. package/src/Encoding.ts +9 -0
  33. package/src/Evaluator.test.ts +158 -0
  34. package/src/Evaluator.ts +186 -0
  35. package/src/GoalRules.test.ts +8 -0
  36. package/src/GoalRules.ts +81 -4
  37. package/src/Oracle.test.ts +71 -0
  38. package/src/Oracle.ts +182 -0
  39. package/src/index.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/brain",
3
- "version": "0.13.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/datalog": "0.13.0",
65
- "@dxos/errors": "0.13.0",
66
- "@dxos/pipeline-rdf": "0.13.0",
67
- "@dxos/util": "0.13.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
@@ -164,7 +164,8 @@ export const parseDuration = (duration: string | number): number | undefined =>
164
164
 
165
165
  const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
166
166
 
167
- 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 => {
168
169
  const time = typeof value === 'number' ? value : Date.parse(value);
169
170
  return Number.isNaN(time) ? undefined : time;
170
171
  };
@@ -76,4 +76,18 @@ describe('Encoding', () => {
76
76
  ['fact', 'factuality', 'force', 'polarity', 'recordedAt', 'saidAt', 'source', 'surface'].sort(),
77
77
  );
78
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
+ });
79
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);
@@ -183,4 +183,12 @@ describe('GoalRules', () => {
183
183
  ]);
184
184
  });
185
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
+ });
186
194
  });
package/src/GoalRules.ts CHANGED
@@ -107,6 +107,7 @@ export class GoalRules {
107
107
  readonly #subgoals = new Map<string, string>();
108
108
  readonly #maxFacts: number;
109
109
  readonly #maxSubgoals: number;
110
+ readonly #createdAt: number;
110
111
  #now: number;
111
112
  #previous: number;
112
113
  #achieved = false;
@@ -114,6 +115,7 @@ export class GoalRules {
114
115
 
115
116
  /** @throws Compiler.CompileError if the rules do not compile. */
116
117
  constructor(options: Options) {
118
+ this.#createdAt = options.createdAt;
117
119
  this.#now = options.createdAt;
118
120
  this.#previous = options.createdAt;
119
121
  this.#maxFacts = options.maxFacts ?? MAX_FACTS;
@@ -204,7 +206,16 @@ export class GoalRules {
204
206
  this.#subgoals.set(subgoal, status);
205
207
  }
206
208
 
207
- const changes = this.#engine.update({ insert, retract, refresh: this.#now !== this.#previous });
209
+ const refresh = this.#now !== this.#previous;
210
+ if (refresh) {
211
+ // Re-evaluate at the previous time with no period boundary crossed, discarding the changes: otherwise a
212
+ // binding `every` held at the previous evaluation is still present, and the next boundary adds nothing new.
213
+ const now = this.#now;
214
+ this.#now = this.#previous;
215
+ this.#engine.update({ refresh: true });
216
+ this.#now = now;
217
+ }
218
+ const changes = this.#engine.update({ insert, retract, refresh });
208
219
  for (const [relation, label] of this.compilation.wakes) {
209
220
  for (const tuple of changes.added.get(relation) ?? []) {
210
221
  wakes.push({ label, cause: 'rule', facts: Encoding.factIds(this.#engine.provenance(relation, tuple)) });
@@ -268,6 +279,70 @@ export class GoalRules {
268
279
  return retired;
269
280
  }
270
281
 
282
+ /**
283
+ * The earliest time after the last evaluation at which a time built-in can change its answer
284
+ * (`elapsed`, `every`, `due`), so a host schedules its next {@link update} rather than polling;
285
+ * `undefined` when the rules read no clock.
286
+ */
287
+ nextDueAt(): number | undefined {
288
+ const candidates: number[] = [];
289
+ const after = (time: number | undefined) => {
290
+ if (time !== undefined && time > this.#now) {
291
+ candidates.push(time);
292
+ }
293
+ };
294
+ const constant = (term: Ast.Term | undefined): Ast.Value | undefined =>
295
+ term?.type === 'constant' ? term.value : undefined;
296
+ const visit = (literal: Ast.Literal): void => {
297
+ if (literal.type === 'aggregate') {
298
+ literal.body.forEach(visit);
299
+ return;
300
+ }
301
+ if (literal.type !== 'atom') {
302
+ return;
303
+ }
304
+ const [first, second] = literal.atom.terms;
305
+ switch (literal.atom.predicate) {
306
+ case 'elapsed': {
307
+ const length = Builtins.parseDuration(constant(second) ?? '');
308
+ if (length === undefined) {
309
+ return;
310
+ }
311
+ const ref = constant(first);
312
+ if (ref === undefined) {
313
+ // `elapsed(F, …)` over facts: each fact in working memory starts its own clock.
314
+ for (const { saidAt } of this.#facts.values()) {
315
+ after(saidAt + length);
316
+ }
317
+ } else if (ref === 'goal') {
318
+ after(this.#createdAt + length);
319
+ } else {
320
+ const start = this.#facts.get(String(ref))?.saidAt ?? Builtins.parseTime(ref);
321
+ after(start === undefined ? undefined : start + length);
322
+ }
323
+ return;
324
+ }
325
+ case 'every': {
326
+ const period = Builtins.parseDuration(constant(first) ?? '');
327
+ if (period !== undefined && period > 0) {
328
+ after(this.#createdAt + (Math.floor((this.#now - this.#createdAt) / period) + 1) * period);
329
+ }
330
+ return;
331
+ }
332
+ case 'due': {
333
+ const deadline = Builtins.parseTime(constant(first) ?? '');
334
+ const lead = Builtins.parseDuration(constant(second) ?? '');
335
+ after(deadline === undefined || lead === undefined ? undefined : deadline - lead);
336
+ return;
337
+ }
338
+ }
339
+ };
340
+ for (const rule of this.compilation.program.rules) {
341
+ rule.body.forEach(visit);
342
+ }
343
+ return candidates.length === 0 ? undefined : Math.min(...candidates);
344
+ }
345
+
271
346
  /** Evaluates the `blocks` rules for a proposed action without keeping it. */
272
347
  checkAction(action: Action): ActionCheck {
273
348
  const entries: Engine.Entry[] = [
@@ -299,8 +374,10 @@ const age = (saidAt: number): number => (Number.isNaN(saidAt) ? Number.NEGATIVE_
299
374
  /** Creates a goal evaluator. */
300
375
  export const make = (options: Options): GoalRules => new GoalRules(options);
301
376
 
377
+ /** A term's id and, for an entity known by an opaque id (a DID), its label, so `about` matches the name. */
378
+ const termText = (term: RDF.Term): string =>
379
+ term.kind === 'entity' && term.label !== undefined ? `${term.entity} ${term.label}` : RDF.termValue(term);
380
+
302
381
  /** The text `about` matches: what was said plus the triple. */
303
382
  const factText = ({ assertion }: RDF.Fact): string =>
304
- [assertion.quote ?? '', RDF.termValue(assertion.subject), assertion.predicate, RDF.termValue(assertion.object)].join(
305
- ' ',
306
- );
383
+ [assertion.quote ?? '', termText(assertion.subject), assertion.predicate, termText(assertion.object)].join(' ');
@@ -0,0 +1,71 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import * as Oracle from './Oracle.ts';
8
+ import { REFERENCE } from './testing/index.ts';
9
+
10
+ const CREATED = Date.parse('2027-01-04T09:00:00Z');
11
+
12
+ /** A timeline for goal 1 ("keep me informed about what Dima is working on"), as an oracle might write it. */
13
+ const TIMELINE = JSON.stringify({
14
+ steps: [
15
+ {
16
+ after: '10m',
17
+ says: [
18
+ {
19
+ speaker: 'rich',
20
+ quote: 'Lunch?',
21
+ subject: 'rich',
22
+ predicate: 'suggests',
23
+ object: 'lunch',
24
+ force: 'directive',
25
+ },
26
+ ],
27
+ wake: false,
28
+ note: 'unrelated, and not Dima',
29
+ },
30
+ {
31
+ after: '1h',
32
+ says: [
33
+ { speaker: 'dima', quote: 'I am on the indexer.', subject: 'dima', predicate: 'works on', object: 'indexer' },
34
+ ],
35
+ wake: true,
36
+ },
37
+ ],
38
+ });
39
+
40
+ describe('Oracle', () => {
41
+ test('parses a timeline, also inside a code fence', ({ expect }) => {
42
+ const reply = Oracle.parseReply(`Here it is:\n\`\`\`json\n${TIMELINE}\n\`\`\``);
43
+ expect(reply.steps.map(({ wake }) => wake)).toEqual([false, true]);
44
+ expect(() => Oracle.parseReply('no json')).toThrow(Oracle.ReplyError);
45
+ expect(() => Oracle.parseReply('{"steps":[]}')).toThrow(Oracle.ReplyError);
46
+ });
47
+
48
+ test('passes a compilation that replays the timeline and fails one that does not', ({ expect }) => {
49
+ const { steps } = Oracle.parseReply(TIMELINE);
50
+ expect(Oracle.replay(REFERENCE[1], { createdAt: CREATED, steps })).toEqual({ ok: true, failures: [] });
51
+
52
+ // Waking on anyone at all wakes on the near miss.
53
+ const loose = Oracle.replay('wake(any) :- fact(F, _, _, _).', { createdAt: CREATED, steps });
54
+ expect(loose.ok).toBe(false);
55
+ expect(loose.failures).toEqual([
56
+ expect.stringContaining('step 1 (unrelated, and not Dima): wake=true, expected false'),
57
+ ]);
58
+
59
+ // Rules that do not compile fail the gate rather than throw.
60
+ expect(Oracle.replay('wake(x) :- nonsense(', { createdAt: CREATED, steps }).ok).toBe(false);
61
+ });
62
+
63
+ test('tells the oracle the ids people go by', ({ expect }) => {
64
+ const message = Oracle.userMessage({
65
+ goal: 'Keep me posted on Bob',
66
+ owner: 'did:halo:ALICE',
67
+ people: [{ name: 'Bob', id: 'did:halo:BOB' }],
68
+ });
69
+ expect(message).toContain('Bob = did:halo:BOB');
70
+ });
71
+ });