@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
package/package.json CHANGED
@@ -1,10 +1,79 @@
1
1
  {
2
2
  "name": "@dxos/brain",
3
- "version": "0.0.1",
4
- "description": "Placeholder to register the package name; the first real release is published by the DXOS release pipeline.",
3
+ "version": "0.13.0",
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
- "repository": { "type": "git", "url": "https://github.com/dxos/dxos" },
6
+ "bugs": "https://github.com/dxos/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
7
11
  "license": "FSL-1.1-Apache-2.0",
8
12
  "author": "DXOS.org",
9
- "publishConfig": { "access": "public" }
10
- }
13
+ "sideEffects": false,
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "source": "./src/index.ts",
18
+ "types": "./dist/types/src/index.d.ts",
19
+ "import": "./dist/lib/index.mjs"
20
+ },
21
+ "./Builtins": {
22
+ "source": "./src/Builtins.ts",
23
+ "types": "./dist/types/src/Builtins.d.ts",
24
+ "import": "./dist/lib/Builtins.mjs"
25
+ },
26
+ "./CompilePrompt": {
27
+ "source": "./src/CompilePrompt.ts",
28
+ "types": "./dist/types/src/CompilePrompt.d.ts",
29
+ "import": "./dist/lib/CompilePrompt.mjs"
30
+ },
31
+ "./Compiler": {
32
+ "source": "./src/Compiler.ts",
33
+ "types": "./dist/types/src/Compiler.d.ts",
34
+ "import": "./dist/lib/Compiler.mjs"
35
+ },
36
+ "./Encoding": {
37
+ "source": "./src/Encoding.ts",
38
+ "types": "./dist/types/src/Encoding.d.ts",
39
+ "import": "./dist/lib/Encoding.mjs"
40
+ },
41
+ "./GoalRules": {
42
+ "source": "./src/GoalRules.ts",
43
+ "types": "./dist/types/src/GoalRules.d.ts",
44
+ "import": "./dist/lib/GoalRules.mjs"
45
+ },
46
+ "./Vocabulary": {
47
+ "source": "./src/Vocabulary.ts",
48
+ "types": "./dist/types/src/Vocabulary.d.ts",
49
+ "import": "./dist/lib/Vocabulary.mjs"
50
+ },
51
+ "./package.json": "./package.json",
52
+ "./testing": {
53
+ "source": "./src/testing/index.ts",
54
+ "types": "./dist/types/src/testing/index.d.ts",
55
+ "import": "./dist/lib/testing.mjs"
56
+ }
57
+ },
58
+ "types": "dist/types/src/index.d.ts",
59
+ "files": [
60
+ "dist",
61
+ "src"
62
+ ],
63
+ "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"
68
+ },
69
+ "devDependencies": {
70
+ "effect": "4.0.0",
71
+ "vitest": "4.1.10"
72
+ },
73
+ "peerDependencies": {
74
+ "effect": "4.0.0"
75
+ },
76
+ "publishConfig": {
77
+ "access": "public"
78
+ }
79
+ }
@@ -0,0 +1,45 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import * as Builtins from './Builtins.ts';
8
+
9
+ describe('Builtins', () => {
10
+ test('keyword matching stems and ignores stop words', ({ expect }) => {
11
+ expect(Builtins.keywordMatch('I shipped the v0.9 release', 'release ships')).toBe(true);
12
+ expect(Builtins.keywordMatch('French fries for lunch', 'french practice')).toBe(false);
13
+ expect(Builtins.keywordMatch('anything', 'the of')).toBe(false);
14
+ });
15
+
16
+ test('parses durations', ({ expect }) => {
17
+ expect(Builtins.parseDuration('2d')).toBe(2 * 864e5);
18
+ expect(Builtins.parseDuration('PT30m')).toBe(30 * 6e4);
19
+ expect(Builtins.parseDuration('soon')).toBeUndefined();
20
+ });
21
+
22
+ test('evaluates time and text built-ins', ({ expect }) => {
23
+ const context = Builtins.emptyContext();
24
+ context.text.add('f1', 'the agent plugin');
25
+ context.entities.add('f1', ['rich']);
26
+ let now = Date.parse('2027-01-06T09:00:00Z');
27
+ const registry = Builtins.make({
28
+ ...context,
29
+ clock: { ...context.clock, now: () => now, createdAt: Date.parse('2027-01-04T09:00:00Z') },
30
+ });
31
+ const call = (name: string, ...args: Array<string | undefined>) => [...(registry.get(name)?.evaluate(args) ?? [])];
32
+
33
+ expect(call('about', undefined, 'plugin')).toEqual([['f1', 'plugin']]);
34
+ expect(call('about', 'f1', 'release')).toEqual([]);
35
+ expect(call('concerns', undefined, 'rich')).toEqual([['f1', 'rich']]);
36
+ expect(call('elapsed', 'goal', '2d')).toHaveLength(1);
37
+ now -= 1;
38
+ expect(call('elapsed', 'goal', '2d')).toHaveLength(0);
39
+ expect(call('weekday', '2027-01-08T15:00:00Z', undefined)).toEqual([['2027-01-08T15:00:00Z', 'friday']]);
40
+ expect(call('weekday', '2027-01-08T15:00:00Z', 'Friday')).toEqual([['2027-01-08T15:00:00Z', 'Friday']]);
41
+ expect(call('due', '2027-01-10T00:00:00Z', '7d')).toHaveLength(1);
42
+ expect(registry.get('elapsed')?.volatile).toBe(true);
43
+ expect(registry.get('weekday')?.volatile).toBeFalsy();
44
+ });
45
+ });
@@ -0,0 +1,284 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Builtin from '@dxos/datalog/Builtin';
8
+
9
+ /** Finds facts about a topic; a semantic index replaces the keyword one without touching rules. */
10
+ export interface TextIndex {
11
+ add(factId: string, text: string): void;
12
+ remove(factId: string): void;
13
+ /** True if the fact is about `query`. */
14
+ matches(factId: string, query: string): boolean;
15
+ /** Every fact about `query`. */
16
+ search(query: string): Iterable<string>;
17
+ }
18
+
19
+ /** The entities each fact concerns (entity resolution), for scoping possessive goals. */
20
+ export interface EntityIndex {
21
+ add(factId: string, entities: ReadonlyArray<string>): void;
22
+ remove(factId: string): void;
23
+ concerns(factId: string): ReadonlyArray<string>;
24
+ facts(entity: string): Iterable<string>;
25
+ }
26
+
27
+ /** What the time built-ins read; `previous` is the time of the evaluation before this one. */
28
+ export type Clock = {
29
+ readonly now: () => number;
30
+ readonly previous: () => number;
31
+ /** When the goal was created; `elapsed(goal, …)` measures from it. */
32
+ readonly createdAt: number;
33
+ /** When a fact was said, for `elapsed(F, …)`. */
34
+ readonly saidAt: (factId: string) => number | undefined;
35
+ };
36
+
37
+ export type Context = {
38
+ readonly clock: Clock;
39
+ readonly text: TextIndex;
40
+ readonly entities: EntityIndex;
41
+ };
42
+
43
+ const STOP_WORDS = new Set([
44
+ 'the',
45
+ 'a',
46
+ 'an',
47
+ 'of',
48
+ 'to',
49
+ 'on',
50
+ 'in',
51
+ 'for',
52
+ 'and',
53
+ 'or',
54
+ 'with',
55
+ 'about',
56
+ 'is',
57
+ 'my',
58
+ 'me',
59
+ 'this',
60
+ 'that',
61
+ 'at',
62
+ 'by',
63
+ 'it',
64
+ ]);
65
+
66
+ const stem = (word: string): string => {
67
+ let stemmed = word.toLowerCase();
68
+ if (stemmed.length > 4 && stemmed.endsWith('ing')) {
69
+ stemmed = stemmed.slice(0, -3);
70
+ } else if (stemmed.length > 3 && (stemmed.endsWith('ed') || stemmed.endsWith('es'))) {
71
+ stemmed = stemmed.slice(0, -2);
72
+ } else if (stemmed.length > 2 && stemmed.endsWith('s')) {
73
+ stemmed = stemmed.slice(0, -1);
74
+ }
75
+ if (stemmed.length > 3 && stemmed.at(-1) === stemmed.at(-2)) {
76
+ stemmed = stemmed.slice(0, -1);
77
+ }
78
+ return stemmed;
79
+ };
80
+
81
+ const words = (text: string): string[] =>
82
+ text
83
+ .toLowerCase()
84
+ .split(/[^a-z0-9]+/)
85
+ .filter(Boolean);
86
+
87
+ /** True if every non-stop keyword of `query` (stemmed, prefix-tolerant) occurs in `text`. */
88
+ export const keywordMatch = (text: string, query: string): boolean => {
89
+ const stems = new Set(words(text).map(stem));
90
+ const keywords = words(query)
91
+ .filter((word) => !STOP_WORDS.has(word))
92
+ .map(stem);
93
+ return (
94
+ keywords.length > 0 &&
95
+ keywords.every((keyword) =>
96
+ [...stems].some(
97
+ (candidate) =>
98
+ candidate === keyword ||
99
+ (keyword.length >= 4 && candidate.startsWith(keyword)) ||
100
+ (candidate.length >= 4 && keyword.startsWith(candidate)),
101
+ ),
102
+ )
103
+ );
104
+ };
105
+
106
+ /** Keyword stand-in for a semantic index. */
107
+ export class KeywordIndex implements TextIndex {
108
+ readonly #texts = new Map<string, string>();
109
+
110
+ add(factId: string, text: string): void {
111
+ this.#texts.set(factId, text);
112
+ }
113
+
114
+ remove(factId: string): void {
115
+ this.#texts.delete(factId);
116
+ }
117
+
118
+ matches(factId: string, query: string): boolean {
119
+ return keywordMatch(this.#texts.get(factId) ?? '', query);
120
+ }
121
+
122
+ *search(query: string): Iterable<string> {
123
+ for (const [factId, text] of this.#texts) {
124
+ if (keywordMatch(text, query)) {
125
+ yield factId;
126
+ }
127
+ }
128
+ }
129
+ }
130
+
131
+ /** In-memory entity index. */
132
+ export class MemoryEntityIndex implements EntityIndex {
133
+ readonly #byFact = new Map<string, ReadonlyArray<string>>();
134
+
135
+ add(factId: string, entities: ReadonlyArray<string>): void {
136
+ this.#byFact.set(factId, entities);
137
+ }
138
+
139
+ remove(factId: string): void {
140
+ this.#byFact.delete(factId);
141
+ }
142
+
143
+ concerns(factId: string): ReadonlyArray<string> {
144
+ return this.#byFact.get(factId) ?? [];
145
+ }
146
+
147
+ *facts(entity: string): Iterable<string> {
148
+ for (const [factId, entities] of this.#byFact) {
149
+ if (entities.includes(entity)) {
150
+ yield factId;
151
+ }
152
+ }
153
+ }
154
+ }
155
+
156
+ const DURATION_UNITS: Record<string, number> = { s: 1e3, m: 6e4, h: 36e5, d: 864e5, w: 6048e5 };
157
+
158
+ /** Parses `30s`, `5m`, `2h`, `2d`, `1w` (optionally ISO-prefixed `P`/`PT`) to milliseconds. */
159
+ export const parseDuration = (duration: string | number): number | undefined => {
160
+ const match = /^P?T?(\d+(?:\.\d+)?)\s*([smhdw])$/i.exec(String(duration).trim());
161
+ const unit = match ? DURATION_UNITS[match[2].toLowerCase()] : undefined;
162
+ return match && unit !== undefined ? Number(match[1]) * unit : undefined;
163
+ };
164
+
165
+ const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
166
+
167
+ const parseTime = (value: string | number): number | undefined => {
168
+ const time = typeof value === 'number' ? value : Date.parse(value);
169
+ return Number.isNaN(time) ? undefined : time;
170
+ };
171
+
172
+ /**
173
+ * The goal built-ins: `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`),
174
+ * `elapsed(Ref, Duration)` (`Ref` is `goal`, a fact id or a time), `every(Duration)` (a period
175
+ * boundary passed since the previous evaluation), `due(Time, Lead)`, `weekday(Time, Day)` and
176
+ * `hour(Time, Hour)` (UTC).
177
+ */
178
+ export const make = ({ clock, text, entities }: Context): Builtin.Registry => {
179
+ const reference = (value: string | number): number | undefined =>
180
+ value === 'goal' ? clock.createdAt : (clock.saidAt(String(value)) ?? parseTime(value));
181
+
182
+ return Builtin.registry(
183
+ Builtin.make({
184
+ name: 'about',
185
+ arity: 2,
186
+ modes: ['fb'],
187
+ evaluate: ([factId, query]) => {
188
+ if (query === undefined) {
189
+ return [];
190
+ }
191
+ if (factId === undefined) {
192
+ return [...text.search(String(query))].map((id) => [id, query]);
193
+ }
194
+ return text.matches(String(factId), String(query)) ? [[factId, query]] : [];
195
+ },
196
+ }),
197
+ Builtin.make({
198
+ name: 'concerns',
199
+ arity: 2,
200
+ modes: ['fb'],
201
+ evaluate: ([factId, entity]) => {
202
+ if (entity === undefined) {
203
+ return [];
204
+ }
205
+ if (factId === undefined) {
206
+ return [...entities.facts(String(entity))].map((id) => [id, entity]);
207
+ }
208
+ return entities.concerns(String(factId)).includes(String(entity)) ? [[factId, entity]] : [];
209
+ },
210
+ }),
211
+ Builtin.predicate(
212
+ 'elapsed',
213
+ 2,
214
+ ([ref, duration]) => {
215
+ const start = reference(ref);
216
+ const length = parseDuration(duration);
217
+ return start !== undefined && length !== undefined && clock.now() - start >= length;
218
+ },
219
+ { volatile: true },
220
+ ),
221
+ Builtin.predicate(
222
+ 'every',
223
+ 1,
224
+ ([duration]) => {
225
+ const period = parseDuration(duration);
226
+ if (period === undefined || period <= 0) {
227
+ return false;
228
+ }
229
+ const tick = (time: number) => Math.floor((time - clock.createdAt) / period);
230
+ return tick(clock.now()) > tick(clock.previous());
231
+ },
232
+ { volatile: true },
233
+ ),
234
+ Builtin.predicate(
235
+ 'due',
236
+ 2,
237
+ ([time, lead]) => {
238
+ const deadline = parseTime(time);
239
+ const length = parseDuration(lead);
240
+ return deadline !== undefined && length !== undefined && clock.now() >= deadline - length;
241
+ },
242
+ { volatile: true },
243
+ ),
244
+ Builtin.make({
245
+ name: 'weekday',
246
+ arity: 2,
247
+ modes: ['bf'],
248
+ evaluate: ([time, day]) => {
249
+ const parsed = time === undefined ? undefined : parseTime(time);
250
+ if (time === undefined || parsed === undefined) {
251
+ return [];
252
+ }
253
+ const weekday = WEEKDAYS[new Date(parsed).getUTCDay()];
254
+ if (day === undefined) {
255
+ return [[time, weekday]];
256
+ }
257
+ return String(day).toLowerCase() === weekday ? [[time, day]] : [];
258
+ },
259
+ }),
260
+ Builtin.make({
261
+ name: 'hour',
262
+ arity: 2,
263
+ modes: ['bf'],
264
+ evaluate: ([time, hour]) => {
265
+ const parsed = time === undefined ? undefined : parseTime(time);
266
+ if (time === undefined || parsed === undefined) {
267
+ return [];
268
+ }
269
+ const value = new Date(parsed).getUTCHours();
270
+ if (hour === undefined) {
271
+ return [[time, value]];
272
+ }
273
+ return Number(hour) === value ? [[time, hour]] : [];
274
+ },
275
+ }),
276
+ );
277
+ };
278
+
279
+ /** A context with empty indexes and a frozen clock, for checking rules without evaluating them. */
280
+ export const emptyContext = (): Context => ({
281
+ clock: { now: () => 0, previous: () => 0, createdAt: 0, saidAt: () => undefined },
282
+ text: new KeywordIndex(),
283
+ entities: new MemoryEntityIndex(),
284
+ });
@@ -0,0 +1,117 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { trim } from '@dxos/util';
8
+
9
+ import * as Builtins from './Builtins.ts';
10
+ import * as CompilePrompt from './CompilePrompt.ts';
11
+ import * as Compiler from './Compiler.ts';
12
+ import * as Encoding from './Encoding.ts';
13
+ import { REFERENCE, SCENARIOS } from './testing/index.ts';
14
+ import * as Vocabulary from './Vocabulary.ts';
15
+
16
+ describe('CompilePrompt', () => {
17
+ test('mentions every relation, built-in, head and canonical predicate', ({ expect }) => {
18
+ const prompt = CompilePrompt.SYSTEM_PROMPT;
19
+ const names = [
20
+ ...Object.keys(Encoding.RELATIONS),
21
+ ...Builtins.make(Builtins.emptyContext()).keys(),
22
+ ...Compiler.GOAL_HEADS,
23
+ ...Vocabulary.DEFAULT_ENTRIES.map(({ predicate }) => predicate),
24
+ ];
25
+ for (const name of names) {
26
+ expect(prompt, name).toMatch(new RegExp(`\\b${name}\\(|^- ${name}\\b`, 'm'));
27
+ }
28
+ });
29
+
30
+ test('documents exactly the registered built-ins', ({ expect }) => {
31
+ expect(Object.keys(CompilePrompt.BUILTIN_DOCS).sort()).toEqual(
32
+ [...Builtins.make(Builtins.emptyContext()).keys()].sort(),
33
+ );
34
+ });
35
+
36
+ test('builds the canonical list from the given vocabulary', ({ expect }) => {
37
+ const vocabulary = Vocabulary.make([{ predicate: 'reviews', synonyms: ['reviewing'] }]);
38
+ expect(CompilePrompt.systemPrompt({ vocabulary })).toContain('- reviews (extracted as: reviewing)');
39
+ });
40
+
41
+ test('worked examples compile', ({ expect }) => {
42
+ for (const example of CompilePrompt.EXAMPLES) {
43
+ expect(Compiler.compile(example.datalog).diagnostics, example.goal).toEqual([]);
44
+ }
45
+ });
46
+
47
+ test('user message carries the goal, owner, time, session and instructions', ({ expect }) => {
48
+ const scenario = SCENARIOS.find(({ n }) => n === 3);
49
+ expect(
50
+ CompilePrompt.userMessage({
51
+ goal: 'Get Dima to help me with the agent plugin',
52
+ owner: 'rich',
53
+ now: '2027-01-04T09:00:00Z',
54
+ instructions: scenario?.context,
55
+ session: 'session:s42',
56
+ }),
57
+ ).toBe(
58
+ [
59
+ 'Goal: "Get Dima to help me with the agent plugin"',
60
+ 'Owner: rich',
61
+ 'Created: 2027-01-04T09:00:00Z',
62
+ 'Session goal; current session id: session:s42',
63
+ 'Instructions: Follow up after 2 days without a commitment.',
64
+ ].join('\n'),
65
+ );
66
+ expect(CompilePrompt.userMessage({ goal: 'Learn French', owner: 'rich', now: 'now', instructions: ' ' })).toBe(
67
+ 'Goal: "Learn French"\nOwner: rich\nCreated: now',
68
+ );
69
+ });
70
+ });
71
+
72
+ describe('parseReply', () => {
73
+ test('extracts every section', ({ expect }) => {
74
+ const reply = CompilePrompt.parseReply(trim`
75
+ <kind>outcome</kind>
76
+ <drivers>fact, time</drivers>
77
+ <achievement>rule</achievement>
78
+ <datalog>
79
+ ${REFERENCE[3]}
80
+ </datalog>
81
+ <notes>Refusals wake but never achieve.</notes>
82
+ `);
83
+ expect(reply).toEqual({
84
+ kind: 'outcome',
85
+ drivers: ['fact', 'time'],
86
+ achievement: 'rule',
87
+ datalog: REFERENCE[3],
88
+ notes: 'Refusals wake but never achieve.',
89
+ });
90
+ expect(Compiler.compile(reply.datalog).diagnostics).toEqual([]);
91
+ });
92
+
93
+ test('accepts a code fence inside or instead of the datalog section', ({ expect }) => {
94
+ const rules = 'wake(practice) :- every(1d), not achieved(goal).';
95
+ expect(CompilePrompt.parseReply(`<datalog>\n\`\`\`prolog\n${rules}\n\`\`\`\n</datalog>`).datalog).toBe(rules);
96
+ expect(CompilePrompt.parseReply(`Here you go:\n\`\`\`datalog\n${rules}\n\`\`\``)).toEqual({
97
+ drivers: [],
98
+ datalog: rules,
99
+ });
100
+ });
101
+
102
+ test('fails with a typed error on a malformed reply', ({ expect }) => {
103
+ const code = (text: string) => {
104
+ try {
105
+ CompilePrompt.parseReply(text);
106
+ return undefined;
107
+ } catch (error) {
108
+ return error instanceof CompilePrompt.ReplyError ? error.code : error;
109
+ }
110
+ };
111
+ expect(code('<kind>outcome</kind>')).toBe('missing-datalog');
112
+ expect(code('<datalog>\n \n</datalog>')).toBe('empty-datalog');
113
+ expect(code('<kind>goal</kind><datalog>p(a).</datalog>')).toBe('invalid-kind');
114
+ expect(code('<drivers>fact, email</drivers><datalog>p(a).</datalog>')).toBe('invalid-drivers');
115
+ expect(code('<achievement>maybe</achievement><datalog>p(a).</datalog>')).toBe('invalid-achievement');
116
+ });
117
+ });