@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.
- package/LICENSE +105 -0
- package/README.md +32 -1
- package/dist/lib/Builtins.mjs +184 -0
- package/dist/lib/Builtins.mjs.map +1 -0
- package/dist/lib/CompilePrompt.mjs +305 -0
- package/dist/lib/CompilePrompt.mjs.map +1 -0
- package/dist/lib/Compiler.mjs +212 -0
- package/dist/lib/Compiler.mjs.map +1 -0
- package/dist/lib/Encoding.mjs +116 -0
- package/dist/lib/Encoding.mjs.map +1 -0
- package/dist/lib/GoalRules.mjs +245 -0
- package/dist/lib/GoalRules.mjs.map +1 -0
- package/dist/lib/Vocabulary.mjs +92 -0
- package/dist/lib/Vocabulary.mjs.map +1 -0
- package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
- package/dist/lib/index.mjs +7 -0
- package/dist/lib/testing.mjs +831 -0
- package/dist/lib/testing.mjs.map +1 -0
- package/dist/types/src/Builtins.d.ts +61 -0
- package/dist/types/src/Builtins.d.ts.map +1 -0
- package/dist/types/src/Builtins.test.d.ts +2 -0
- package/dist/types/src/Builtins.test.d.ts.map +1 -0
- package/dist/types/src/CompilePrompt.d.ts +107 -0
- package/dist/types/src/CompilePrompt.d.ts.map +1 -0
- package/dist/types/src/CompilePrompt.test.d.ts +2 -0
- package/dist/types/src/CompilePrompt.test.d.ts.map +1 -0
- package/dist/types/src/Compiler.d.ts +76 -0
- package/dist/types/src/Compiler.d.ts.map +1 -0
- package/dist/types/src/Compiler.test.d.ts +2 -0
- package/dist/types/src/Compiler.test.d.ts.map +1 -0
- package/dist/types/src/Encoding.d.ts +42 -0
- package/dist/types/src/Encoding.d.ts.map +1 -0
- package/dist/types/src/Encoding.test.d.ts +2 -0
- package/dist/types/src/Encoding.test.d.ts.map +1 -0
- package/dist/types/src/GoalRules.d.ts +125 -0
- package/dist/types/src/GoalRules.d.ts.map +1 -0
- package/dist/types/src/GoalRules.test.d.ts +2 -0
- package/dist/types/src/GoalRules.test.d.ts.map +1 -0
- package/dist/types/src/Vocabulary.d.ts +31 -0
- package/dist/types/src/Vocabulary.d.ts.map +1 -0
- package/dist/types/src/Vocabulary.test.d.ts +2 -0
- package/dist/types/src/Vocabulary.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +7 -0
- package/dist/types/src/index.d.ts.map +1 -0
- package/dist/types/src/testing/index.d.ts +4 -0
- package/dist/types/src/testing/index.d.ts.map +1 -0
- package/dist/types/src/testing/reference.d.ts +9 -0
- package/dist/types/src/testing/reference.d.ts.map +1 -0
- package/dist/types/src/testing/scenarios.d.ts +73 -0
- package/dist/types/src/testing/scenarios.d.ts.map +1 -0
- package/dist/types/src/testing/simulate.d.ts +31 -0
- package/dist/types/src/testing/simulate.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +74 -5
- package/src/Builtins.test.ts +45 -0
- package/src/Builtins.ts +284 -0
- package/src/CompilePrompt.test.ts +117 -0
- package/src/CompilePrompt.ts +376 -0
- package/src/Compiler.test.ts +85 -0
- package/src/Compiler.ts +234 -0
- package/src/Encoding.test.ts +79 -0
- package/src/Encoding.ts +99 -0
- package/src/GoalRules.test.ts +186 -0
- package/src/GoalRules.ts +306 -0
- package/src/Vocabulary.test.ts +48 -0
- package/src/Vocabulary.ts +88 -0
- package/src/index.ts +10 -0
- package/src/testing/index.ts +7 -0
- package/src/testing/reference.ts +91 -0
- package/src/testing/scenarios.ts +604 -0
- package/src/testing/simulate.ts +127 -0
package/src/GoalRules.ts
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import type * as Ast from '@dxos/datalog/Ast';
|
|
8
|
+
import * as Engine from '@dxos/datalog/Engine';
|
|
9
|
+
import { BaseError } from '@dxos/errors';
|
|
10
|
+
import { RDF } from '@dxos/pipeline-rdf';
|
|
11
|
+
|
|
12
|
+
import * as Builtins from './Builtins.ts';
|
|
13
|
+
import * as Compiler from './Compiler.ts';
|
|
14
|
+
import * as Encoding from './Encoding.ts';
|
|
15
|
+
import type * as Vocabulary from './Vocabulary.ts';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Size of the evaluator's working memory: past it the oldest facts retire, so a goal that runs
|
|
19
|
+
* indefinitely keeps a bounded engine, text and entity index (and bounded queries over them).
|
|
20
|
+
*/
|
|
21
|
+
export const MAX_FACTS = 10_000;
|
|
22
|
+
|
|
23
|
+
/** Most sub-goals one evaluator tracks; sub-goals are structural, so exceeding it is an error. */
|
|
24
|
+
export const MAX_SUBGOALS = 256;
|
|
25
|
+
|
|
26
|
+
/** Thrown by `GoalRules.update` when an input would take the evaluator past {@link MAX_SUBGOALS}. */
|
|
27
|
+
export class CapacityError extends BaseError.extend('CapacityError', 'Goal evaluator capacity exceeded') {
|
|
28
|
+
constructor(context: { readonly max: number; readonly requested: number }) {
|
|
29
|
+
super({ message: `Goal evaluator would hold ${context.requested} sub-goals; the cap is ${context.max}.`, context });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A reason to run judgment on the goal. */
|
|
34
|
+
export type Wake = {
|
|
35
|
+
/** The wake rule's label, `achieved`, or the sub-goal whose status changed. */
|
|
36
|
+
readonly label: string;
|
|
37
|
+
readonly cause: 'rule' | 'achieved' | 'subgoal';
|
|
38
|
+
/** Ids of the facts the waking derivation rests on. */
|
|
39
|
+
readonly facts: ReadonlyArray<string>;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type Evaluation = {
|
|
43
|
+
readonly at: number;
|
|
44
|
+
readonly wakes: ReadonlyArray<Wake>;
|
|
45
|
+
readonly achieved: boolean;
|
|
46
|
+
readonly holds: boolean;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** An action the agent proposes, checked against the goal's `blocks` rules before it runs. */
|
|
50
|
+
export type Action = {
|
|
51
|
+
readonly id: string;
|
|
52
|
+
readonly kind: string;
|
|
53
|
+
readonly args: Readonly<Record<string, string>>;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type ActionCheck = {
|
|
57
|
+
readonly blocked: boolean;
|
|
58
|
+
/** Ids of the facts that contributed to the block (empty when only the action did). */
|
|
59
|
+
readonly facts: ReadonlyArray<string>;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type Options = {
|
|
63
|
+
readonly source: string;
|
|
64
|
+
/** When the goal was created (epoch ms); also the clock's starting time. */
|
|
65
|
+
readonly createdAt: number;
|
|
66
|
+
readonly vocabulary?: Vocabulary.Vocabulary;
|
|
67
|
+
readonly text?: Builtins.TextIndex;
|
|
68
|
+
readonly entities?: Builtins.EntityIndex;
|
|
69
|
+
/** Entities a fact concerns; defaults to its subject. */
|
|
70
|
+
readonly concerns?: (fact: RDF.Fact) => ReadonlyArray<string>;
|
|
71
|
+
/**
|
|
72
|
+
* Working-memory size; defaults to {@link MAX_FACTS}. Each `update` first retires facts whose
|
|
73
|
+
* `assertion.validTo` is before the clock, then the oldest (by `generatedAtTime`, then arrival)
|
|
74
|
+
* until at most `maxFacts` remain. Retiring drops a fact from the evaluator only; the feed and any
|
|
75
|
+
* external index keep it, and a re-sent fact with a retired id is admitted again as new.
|
|
76
|
+
* Retirement never wakes the goal, and the facts behind the current `achieved` derivation are
|
|
77
|
+
* never retired, so a goal stays achieved once it is; `holds` and wake bindings may lapse as
|
|
78
|
+
* their facts retire, and a lapsed binding wakes again when new facts restore it.
|
|
79
|
+
*/
|
|
80
|
+
readonly maxFacts?: number;
|
|
81
|
+
/** Overrides {@link MAX_SUBGOALS}. */
|
|
82
|
+
readonly maxSubgoals?: number;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export type Input = {
|
|
86
|
+
/** Evaluation time (epoch ms); a change re-evaluates time built-ins. */
|
|
87
|
+
readonly at: number;
|
|
88
|
+
readonly facts?: ReadonlyArray<RDF.Fact>;
|
|
89
|
+
/** Current status of each sub-goal; a new id adds the sub-goal. */
|
|
90
|
+
readonly subgoals?: Readonly<Record<string, string>>;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Evaluates one goal's compiled rules over a growing fact stream and a clock. A goal wakes when a
|
|
95
|
+
* wake rule gains a new binding, when `achieved` first becomes true, and when a sub-goal's status
|
|
96
|
+
* changes.
|
|
97
|
+
*/
|
|
98
|
+
export class GoalRules {
|
|
99
|
+
readonly compilation: Compiler.Compilation;
|
|
100
|
+
readonly #engine: Engine.Engine;
|
|
101
|
+
readonly #vocabulary: Vocabulary.Vocabulary;
|
|
102
|
+
readonly #text: Builtins.TextIndex;
|
|
103
|
+
readonly #entities: Builtins.EntityIndex;
|
|
104
|
+
readonly #concerns: (fact: RDF.Fact) => ReadonlyArray<string>;
|
|
105
|
+
/** Working memory in arrival order. */
|
|
106
|
+
readonly #facts = new Map<string, Admitted>();
|
|
107
|
+
readonly #subgoals = new Map<string, string>();
|
|
108
|
+
readonly #maxFacts: number;
|
|
109
|
+
readonly #maxSubgoals: number;
|
|
110
|
+
#now: number;
|
|
111
|
+
#previous: number;
|
|
112
|
+
#achieved = false;
|
|
113
|
+
#sequence = 0;
|
|
114
|
+
|
|
115
|
+
/** @throws Compiler.CompileError if the rules do not compile. */
|
|
116
|
+
constructor(options: Options) {
|
|
117
|
+
this.#now = options.createdAt;
|
|
118
|
+
this.#previous = options.createdAt;
|
|
119
|
+
this.#maxFacts = options.maxFacts ?? MAX_FACTS;
|
|
120
|
+
this.#maxSubgoals = options.maxSubgoals ?? MAX_SUBGOALS;
|
|
121
|
+
this.#vocabulary = options.vocabulary ?? Compiler.defaultVocabulary();
|
|
122
|
+
this.#text = options.text ?? new Builtins.KeywordIndex();
|
|
123
|
+
this.#entities = options.entities ?? new Builtins.MemoryEntityIndex();
|
|
124
|
+
this.#concerns = options.concerns ?? ((fact) => [RDF.termValue(fact.assertion.subject)]);
|
|
125
|
+
const builtins = Builtins.make({
|
|
126
|
+
clock: {
|
|
127
|
+
now: () => this.#now,
|
|
128
|
+
previous: () => this.#previous,
|
|
129
|
+
createdAt: options.createdAt,
|
|
130
|
+
saidAt: (factId) => this.#facts.get(factId)?.saidAt,
|
|
131
|
+
},
|
|
132
|
+
text: this.#text,
|
|
133
|
+
entities: this.#entities,
|
|
134
|
+
});
|
|
135
|
+
this.compilation = Compiler.compileOrThrow(options.source, { vocabulary: this.#vocabulary, builtins });
|
|
136
|
+
this.#engine = Engine.make({ program: this.compilation.program, builtins, relations: Compiler.RELATIONS });
|
|
137
|
+
this.#achieved = this.achieved;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
get achieved(): boolean {
|
|
141
|
+
return this.#engine.has('achieved', ['goal']);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
get holds(): boolean {
|
|
145
|
+
return this.#engine.has('holds', ['goal']);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Adds facts and sub-goal status at time `at`, retiring facts past the working-memory window
|
|
150
|
+
* (see {@link Options.maxFacts}); returns the wakes and the goal's state.
|
|
151
|
+
* @throws CapacityError if the input would exceed the sub-goal cap; nothing is applied.
|
|
152
|
+
*/
|
|
153
|
+
update({ at, facts = [], subgoals = {} }: Input): Evaluation {
|
|
154
|
+
this.#checkSubgoals(subgoals);
|
|
155
|
+
this.#previous = this.#now;
|
|
156
|
+
this.#now = at;
|
|
157
|
+
|
|
158
|
+
const arrived = new Map<string, { fact: RDF.Fact; admitted: Admitted }>();
|
|
159
|
+
for (const fact of facts) {
|
|
160
|
+
if (!this.#facts.has(fact.id) && !arrived.has(fact.id)) {
|
|
161
|
+
arrived.set(fact.id, { fact, admitted: this.#admit(fact) });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const retired = this.#retire([...arrived.values()].map(({ admitted }) => admitted));
|
|
165
|
+
const retiring: Engine.Entry[] = [];
|
|
166
|
+
for (const id of retired) {
|
|
167
|
+
const admitted = this.#facts.get(id);
|
|
168
|
+
if (admitted) {
|
|
169
|
+
retiring.push(...admitted.entries);
|
|
170
|
+
this.#facts.delete(id);
|
|
171
|
+
this.#text.remove(id);
|
|
172
|
+
this.#entities.remove(id);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (retiring.length > 0) {
|
|
176
|
+
// A separate pass whose changes are discarded, so retirement never wakes the goal.
|
|
177
|
+
this.#engine.update({ retract: retiring });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const insert: Engine.Entry[] = [];
|
|
181
|
+
const retract: Engine.Entry[] = [];
|
|
182
|
+
for (const { fact, admitted } of arrived.values()) {
|
|
183
|
+
if (!retired.has(fact.id)) {
|
|
184
|
+
this.#facts.set(fact.id, admitted);
|
|
185
|
+
this.#text.add(fact.id, factText(fact));
|
|
186
|
+
this.#entities.add(fact.id, this.#concerns(fact));
|
|
187
|
+
insert.push(...admitted.entries);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const wakes: Wake[] = [];
|
|
192
|
+
for (const [subgoal, status] of Object.entries(subgoals)) {
|
|
193
|
+
const previous = this.#subgoals.get(subgoal);
|
|
194
|
+
if (previous === status) {
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (previous === undefined) {
|
|
198
|
+
insert.push({ relation: 'subgoal', tuple: ['goal', subgoal] });
|
|
199
|
+
} else {
|
|
200
|
+
retract.push({ relation: 'status', tuple: [subgoal, previous] });
|
|
201
|
+
wakes.push({ label: subgoal, cause: 'subgoal', facts: [] });
|
|
202
|
+
}
|
|
203
|
+
insert.push({ relation: 'status', tuple: [subgoal, status] });
|
|
204
|
+
this.#subgoals.set(subgoal, status);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const changes = this.#engine.update({ insert, retract, refresh: this.#now !== this.#previous });
|
|
208
|
+
for (const [relation, label] of this.compilation.wakes) {
|
|
209
|
+
for (const tuple of changes.added.get(relation) ?? []) {
|
|
210
|
+
wakes.push({ label, cause: 'rule', facts: Encoding.factIds(this.#engine.provenance(relation, tuple)) });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const achieved = this.achieved;
|
|
215
|
+
if (achieved && !this.#achieved) {
|
|
216
|
+
wakes.push({
|
|
217
|
+
label: 'achieved',
|
|
218
|
+
cause: 'achieved',
|
|
219
|
+
facts: Encoding.factIds(this.#engine.provenance('achieved', ['goal'])),
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
this.#achieved = achieved;
|
|
223
|
+
return { at, wakes, achieved, holds: this.holds };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
#checkSubgoals(subgoals: Readonly<Record<string, string>>): void {
|
|
227
|
+
const requested = this.#subgoals.size + Object.keys(subgoals).filter((id) => !this.#subgoals.has(id)).length;
|
|
228
|
+
if (requested > this.#maxSubgoals) {
|
|
229
|
+
throw new CapacityError({ max: this.#maxSubgoals, requested });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
#admit(fact: RDF.Fact): Admitted {
|
|
234
|
+
const validTo = fact.assertion.validTo === undefined ? undefined : Date.parse(fact.assertion.validTo);
|
|
235
|
+
return {
|
|
236
|
+
id: fact.id,
|
|
237
|
+
sequence: this.#sequence++,
|
|
238
|
+
saidAt: Date.parse(fact.attribution.generatedAtTime),
|
|
239
|
+
validTo: validTo === undefined || Number.isNaN(validTo) ? undefined : validTo,
|
|
240
|
+
entries: Encoding.encode(fact, this.#vocabulary),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Ids to retire from working memory plus the arriving facts: expired first, then oldest past the cap. */
|
|
245
|
+
#retire(arriving: ReadonlyArray<Admitted>): Set<string> {
|
|
246
|
+
const pinned = new Set(this.achieved ? Encoding.factIds(this.#engine.provenance('achieved', ['goal'])) : []);
|
|
247
|
+
const retired = new Set<string>();
|
|
248
|
+
const kept: Admitted[] = [];
|
|
249
|
+
for (const admitted of [...this.#facts.values(), ...arriving]) {
|
|
250
|
+
if (!pinned.has(admitted.id) && admitted.validTo !== undefined && admitted.validTo < this.#now) {
|
|
251
|
+
retired.add(admitted.id);
|
|
252
|
+
} else {
|
|
253
|
+
kept.push(admitted);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
let excess = kept.length - this.#maxFacts;
|
|
257
|
+
if (excess > 0) {
|
|
258
|
+
const oldest = kept
|
|
259
|
+
.filter(({ id }) => !pinned.has(id))
|
|
260
|
+
.sort((a, b) => age(a.saidAt) - age(b.saidAt) || a.sequence - b.sequence);
|
|
261
|
+
for (const { id } of oldest) {
|
|
262
|
+
if (excess-- <= 0) {
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
retired.add(id);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return retired;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Evaluates the `blocks` rules for a proposed action without keeping it. */
|
|
272
|
+
checkAction(action: Action): ActionCheck {
|
|
273
|
+
const entries: Engine.Entry[] = [
|
|
274
|
+
{ relation: 'action', tuple: [action.id, action.kind] },
|
|
275
|
+
...Object.entries(action.args).map(([key, value]) => ({ relation: 'actionArg', tuple: [action.id, key, value] })),
|
|
276
|
+
];
|
|
277
|
+
this.#engine.update({ insert: entries });
|
|
278
|
+
const tuple: Ast.Tuple = [action.id];
|
|
279
|
+
const blocked = this.#engine.has('blocks', tuple);
|
|
280
|
+
const facts = blocked ? Encoding.factIds(this.#engine.provenance('blocks', tuple)) : [];
|
|
281
|
+
this.#engine.update({ retract: entries });
|
|
282
|
+
return { blocked, facts };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** A fact in working memory, with what retirement needs to order and retract it. */
|
|
287
|
+
type Admitted = {
|
|
288
|
+
readonly id: string;
|
|
289
|
+
/** Arrival order, the tie-break between facts said at the same time. */
|
|
290
|
+
readonly sequence: number;
|
|
291
|
+
readonly saidAt: number;
|
|
292
|
+
readonly validTo?: number;
|
|
293
|
+
readonly entries: ReadonlyArray<Engine.Entry>;
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
/** An unparseable `generatedAtTime` sorts as oldest. */
|
|
297
|
+
const age = (saidAt: number): number => (Number.isNaN(saidAt) ? Number.NEGATIVE_INFINITY : saidAt);
|
|
298
|
+
|
|
299
|
+
/** Creates a goal evaluator. */
|
|
300
|
+
export const make = (options: Options): GoalRules => new GoalRules(options);
|
|
301
|
+
|
|
302
|
+
/** The text `about` matches: what was said plus the triple. */
|
|
303
|
+
const factText = ({ assertion }: RDF.Fact): string =>
|
|
304
|
+
[assertion.quote ?? '', RDF.termValue(assertion.subject), assertion.predicate, RDF.termValue(assertion.object)].join(
|
|
305
|
+
' ',
|
|
306
|
+
);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { describe, test } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { Predicate } from '@dxos/pipeline-rdf/types';
|
|
8
|
+
|
|
9
|
+
import * as Vocabulary from './Vocabulary.ts';
|
|
10
|
+
|
|
11
|
+
describe('Vocabulary', () => {
|
|
12
|
+
test('normalize applies the fact store relation key before joining words', ({ expect }) => {
|
|
13
|
+
for (const surface of ['works at', 'Works At', 'is working at', 'worked-at', 'works_at']) {
|
|
14
|
+
expect(Vocabulary.normalize(surface)).toBe(Predicate.normalize('works at').replace(/\s+/g, '_'));
|
|
15
|
+
}
|
|
16
|
+
expect(Vocabulary.normalize('Will-Work-On')).toBe(Vocabulary.normalize('working on'));
|
|
17
|
+
expect(Vocabulary.normalize(Vocabulary.normalize('is helping with'))).toBe(Vocabulary.normalize('is helping with'));
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('canonicalizes inflected and auxiliary surface forms', ({ expect }) => {
|
|
21
|
+
const vocabulary = Vocabulary.make(Vocabulary.DEFAULT_ENTRIES);
|
|
22
|
+
expect(vocabulary.canonical('works_on')).toBe('works_on');
|
|
23
|
+
expect(vocabulary.canonical('is working on')).toBe('works_on');
|
|
24
|
+
expect(vocabulary.canonical('worked on')).toBe('works_on');
|
|
25
|
+
expect(vocabulary.canonical('Helped-With')).toBe('helps_with');
|
|
26
|
+
expect(vocabulary.canonical('was finished')).toBe('completed');
|
|
27
|
+
expect(vocabulary.resolve('is waiting for')).toBe('awaiting');
|
|
28
|
+
expect(vocabulary.resolve('hates')).toBe('hates');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('keeps synonyms that differ beyond inflection distinct', ({ expect }) => {
|
|
32
|
+
const vocabulary = Vocabulary.make([
|
|
33
|
+
{ predicate: 'works_at', synonyms: ['employed by'] },
|
|
34
|
+
{ predicate: 'works_for' },
|
|
35
|
+
]);
|
|
36
|
+
expect(vocabulary.canonical('is employed by')).toBe('works_at');
|
|
37
|
+
expect(vocabulary.canonical('working for')).toBe('works_for');
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('rejects synonyms that collapse onto two canonical predicates', ({ expect }) => {
|
|
41
|
+
expect(() =>
|
|
42
|
+
Vocabulary.make([
|
|
43
|
+
{ predicate: 'likes', synonyms: ['is fond of'] },
|
|
44
|
+
{ predicate: 'loves', synonyms: ['fond of'] },
|
|
45
|
+
]),
|
|
46
|
+
).toThrow(/maps to both/);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import { Predicate } from '@dxos/pipeline-rdf/types';
|
|
8
|
+
|
|
9
|
+
/** A canonical predicate and the surface forms extraction maps onto it. */
|
|
10
|
+
export type Entry = {
|
|
11
|
+
/** Identifier usable as rule shorthand (`helps_with(dima, X)`). */
|
|
12
|
+
readonly predicate: string;
|
|
13
|
+
readonly synonyms?: ReadonlyArray<string>;
|
|
14
|
+
readonly description?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The lookup key for a surface predicate: pipeline-rdf's relation key (case, auxiliaries and head-verb
|
|
19
|
+
* inflection collapse, as the fact store matches them) with words joined by `_`, so `Will-Work-On`,
|
|
20
|
+
* `working on` and `works_on` compare equal.
|
|
21
|
+
*/
|
|
22
|
+
export const normalize = (surface: string): string =>
|
|
23
|
+
Predicate.normalize(surface.replace(/[_-]+/g, ' ')).replace(/\s+/g, '_');
|
|
24
|
+
|
|
25
|
+
/** The canonical predicates rules may use as shorthand, and the synonyms that map onto them. */
|
|
26
|
+
export class Vocabulary {
|
|
27
|
+
readonly entries: ReadonlyArray<Entry>;
|
|
28
|
+
readonly #canonical = new Map<string, string>();
|
|
29
|
+
readonly #predicates = new Set<string>();
|
|
30
|
+
|
|
31
|
+
/** @throws Error on an invalid predicate name, a reserved name, or a synonym claimed twice. */
|
|
32
|
+
constructor(entries: ReadonlyArray<Entry>, reserved: ReadonlyArray<string> = []) {
|
|
33
|
+
this.entries = entries;
|
|
34
|
+
for (const { predicate, synonyms = [] } of entries) {
|
|
35
|
+
if (!/^[a-z][a-z0-9_]*$/.test(predicate)) {
|
|
36
|
+
throw new Error(`Canonical predicate must be a lowercase identifier: ${predicate}`);
|
|
37
|
+
}
|
|
38
|
+
if (reserved.includes(predicate)) {
|
|
39
|
+
throw new Error(`Canonical predicate collides with a reserved name: ${predicate}`);
|
|
40
|
+
}
|
|
41
|
+
this.#predicates.add(predicate);
|
|
42
|
+
for (const surface of [predicate, ...synonyms]) {
|
|
43
|
+
const key = normalize(surface);
|
|
44
|
+
const existing = this.#canonical.get(key);
|
|
45
|
+
if (existing !== undefined && existing !== predicate) {
|
|
46
|
+
throw new Error(`Synonym ${surface} maps to both ${existing} and ${predicate}`);
|
|
47
|
+
}
|
|
48
|
+
this.#canonical.set(key, predicate);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** True if `name` is a canonical predicate. */
|
|
54
|
+
isCanonical(name: string): boolean {
|
|
55
|
+
return this.#predicates.has(name);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The canonical predicate for a surface form, if the vocabulary knows it. */
|
|
59
|
+
canonical(surface: string): string | undefined {
|
|
60
|
+
return this.#canonical.get(normalize(surface));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The stored predicate for a surface form: canonical if known, otherwise the form unchanged. */
|
|
64
|
+
resolve(surface: string): string {
|
|
65
|
+
return this.canonical(surface) ?? surface;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Creates a vocabulary. */
|
|
70
|
+
export const make = (entries: ReadonlyArray<Entry>, reserved: ReadonlyArray<string> = []): Vocabulary =>
|
|
71
|
+
new Vocabulary(entries, reserved);
|
|
72
|
+
|
|
73
|
+
/** A starter vocabulary covering the example goals; extraction grows it. */
|
|
74
|
+
export const DEFAULT_ENTRIES: ReadonlyArray<Entry> = [
|
|
75
|
+
{ predicate: 'helps_with', synonyms: ['will-help-with', 'helping-with'] },
|
|
76
|
+
{ predicate: 'works_on', synonyms: ['working-on', 'will-work-on', 'working_on'] },
|
|
77
|
+
{ predicate: 'completed', synonyms: ['finished', 'done'] },
|
|
78
|
+
{ predicate: 'shipped', synonyms: ['ships', 'released'] },
|
|
79
|
+
{ predicate: 'proposes', synonyms: ['suggests'] },
|
|
80
|
+
{ predicate: 'received' },
|
|
81
|
+
{ predicate: 'archived' },
|
|
82
|
+
{ predicate: 'deleted' },
|
|
83
|
+
{ predicate: 'filed' },
|
|
84
|
+
{ predicate: 'drafted' },
|
|
85
|
+
{ predicate: 'notified' },
|
|
86
|
+
{ predicate: 'relayed' },
|
|
87
|
+
{ predicate: 'awaiting', synonyms: ['waiting-for'] },
|
|
88
|
+
];
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
export * as Builtins from './Builtins.ts';
|
|
6
|
+
export * as CompilePrompt from './CompilePrompt.ts';
|
|
7
|
+
export * as Compiler from './Compiler.ts';
|
|
8
|
+
export * as Encoding from './Encoding.ts';
|
|
9
|
+
export * as GoalRules from './GoalRules.ts';
|
|
10
|
+
export * as Vocabulary from './Vocabulary.ts';
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { trim } from '@dxos/util';
|
|
6
|
+
|
|
7
|
+
/** Hand-written reference compilations of the eight example goals, keyed by scenario number. */
|
|
8
|
+
export const REFERENCE: Readonly<Record<number, string>> = {
|
|
9
|
+
1: trim`
|
|
10
|
+
wake(dima_work) :- speaker(F, dima), not force(F, expressive).
|
|
11
|
+
wake(dima_work) :- fact(F, dima, _, _), not speaker(F, dima).
|
|
12
|
+
`,
|
|
13
|
+
2: trim`
|
|
14
|
+
shipped(F) :- about(F, "release"), about(F, "shipped"), polarity(F, "+"), not mood(F, interrogative), factuality(F, "CT+").
|
|
15
|
+
candidate(F) :- fact(F, _, _, _), about(F, "release").
|
|
16
|
+
wake(release) :- candidate(F), not achieved(goal).
|
|
17
|
+
achieved(goal) :- shipped(F), fact(N, goal, notified, _), saidAt(F, T1), saidAt(N, T2), T2 >= T1.
|
|
18
|
+
`,
|
|
19
|
+
3: trim`
|
|
20
|
+
dima(F) :- speaker(F, dima), force(F, commissive), about(F, "agent plugin").
|
|
21
|
+
wake(reply) :- dima(F), not achieved(goal).
|
|
22
|
+
wake(reply) :- dima(F), achieved(goal).
|
|
23
|
+
wake(followup) :- elapsed(goal, 2d), not achieved(goal).
|
|
24
|
+
achieved(goal) :- dima(F), polarity(F, "+").
|
|
25
|
+
`,
|
|
26
|
+
4: trim`
|
|
27
|
+
gone(M) :- fact(_, M, archived, inbox).
|
|
28
|
+
gone(M) :- fact(_, M, deleted, inbox).
|
|
29
|
+
waiting(M) :- fact(_, M, received, inbox), not gone(M).
|
|
30
|
+
wake(email) :- fact(F, M, received, inbox).
|
|
31
|
+
holds(goal) :- not waiting(_).
|
|
32
|
+
`,
|
|
33
|
+
5: trim`
|
|
34
|
+
filed(F) :- about(F, "tax return"), about(F, "filed"), polarity(F, "+"), not speaker(F, alice).
|
|
35
|
+
achieved(goal) :- filed(F).
|
|
36
|
+
wake(remind) :- due("2027-04-15T00:00:00Z", 30d), not achieved(goal).
|
|
37
|
+
wake(remind) :- due("2027-04-15T00:00:00Z", 7d), not achieved(goal).
|
|
38
|
+
wake(overdue) :- due("2027-04-15T23:59:59Z", 0d), not achieved(goal).
|
|
39
|
+
wake(progress) :- subgoal(goal, G), status(G, achieved).
|
|
40
|
+
wake(progress) :- speaker(F, rich), about(F, "tax").
|
|
41
|
+
`,
|
|
42
|
+
6: trim`
|
|
43
|
+
wake(practice) :- every(1d), not achieved(goal).
|
|
44
|
+
`,
|
|
45
|
+
7: trim`
|
|
46
|
+
meeting(A) :- action(A, book_meeting).
|
|
47
|
+
meeting(A) :- action(A, update_meeting).
|
|
48
|
+
blocks(A) :- meeting(A), actionArg(A, start, T), weekday(T, friday).
|
|
49
|
+
`,
|
|
50
|
+
8: trim`
|
|
51
|
+
mine(F) :- source(F, "session:s42"), speaker(F, rich).
|
|
52
|
+
wake(turn) :- mine(F), not achieved(goal).
|
|
53
|
+
achieved(goal) :- mine(F), force(F, commissive), polarity(F, "+"), fact(D, goal, drafted, _).
|
|
54
|
+
`,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Plausible but wrong compilations; replaying the scenario must reject each one. */
|
|
58
|
+
export const WRONG: ReadonlyArray<{ readonly scenario: number; readonly note: string; readonly source: string }> = [
|
|
59
|
+
{
|
|
60
|
+
scenario: 3,
|
|
61
|
+
note: 'achievement ignores polarity, so a refusal achieves the goal',
|
|
62
|
+
source: trim`
|
|
63
|
+
achieved(goal) :- speaker(F, dima), force(F, commissive), about(F, "agent plugin").
|
|
64
|
+
wake(followup) :- elapsed(goal, 2d).
|
|
65
|
+
wake(reply) :- speaker(F, dima).
|
|
66
|
+
`,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
scenario: 1,
|
|
70
|
+
note: "only Dima's own messages wake, missing third-party reports",
|
|
71
|
+
source: 'wake(x) :- speaker(F, dima).',
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
scenario: 7,
|
|
75
|
+
note: 'any action with any Friday argument is blocked',
|
|
76
|
+
source: 'blocks(A) :- action(A, _), actionArg(A, _, T), weekday(T, friday).',
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
scenario: 4,
|
|
80
|
+
note: 'holds on any archived email instead of on an empty inbox',
|
|
81
|
+
source: trim`
|
|
82
|
+
holds(goal) :- fact(_, M, archived, inbox).
|
|
83
|
+
wake(e) :- fact(F, _, received, inbox).
|
|
84
|
+
`,
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
scenario: 6,
|
|
88
|
+
note: 'elapsed fires once, not daily',
|
|
89
|
+
source: 'wake(p) :- elapsed(goal, 1d).',
|
|
90
|
+
},
|
|
91
|
+
];
|