@dxos/brain 0.0.1 → 0.12.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 +178 -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 +161 -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 +57 -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/GoalRules.d.ts +66 -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 +274 -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.ts +99 -0
- package/src/GoalRules.test.ts +96 -0
- package/src/GoalRules.ts +181 -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
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import * as Schema from 'effect/Schema';
|
|
8
|
+
|
|
9
|
+
import { BaseError } from '@dxos/errors';
|
|
10
|
+
import { trim } from '@dxos/util';
|
|
11
|
+
|
|
12
|
+
import * as Compiler from './Compiler.ts';
|
|
13
|
+
import * as Encoding from './Encoding.ts';
|
|
14
|
+
import * as Vocabulary from './Vocabulary.ts';
|
|
15
|
+
|
|
16
|
+
/** How a goal is satisfied; read from the goal text, never hardcoded in the runtime. */
|
|
17
|
+
export const Kind = Schema.Literals(['outcome', 'condition', 'constraint']);
|
|
18
|
+
export type Kind = Schema.Schema.Type<typeof Kind>;
|
|
19
|
+
|
|
20
|
+
/** Runtime mechanisms a goal needs: an index subscription, an alarm, a hook before each action. */
|
|
21
|
+
export const Driver = Schema.Literals(['fact', 'time', 'action']);
|
|
22
|
+
export type Driver = Schema.Schema.Type<typeof Driver>;
|
|
23
|
+
|
|
24
|
+
/** Whether `achieved(goal)` closes the goal on its own or only proposes closing it to judgment. */
|
|
25
|
+
export const Achievement = Schema.Literals(['rule', 'judgment']);
|
|
26
|
+
export type Achievement = Schema.Schema.Type<typeof Achievement>;
|
|
27
|
+
|
|
28
|
+
/** A compilation as the model returned it, before `Compiler.compile` checks the rules. */
|
|
29
|
+
export const Reply = Schema.Struct({
|
|
30
|
+
kind: Schema.optional(Kind),
|
|
31
|
+
drivers: Schema.Array(Driver),
|
|
32
|
+
achievement: Schema.optional(Achievement),
|
|
33
|
+
datalog: Schema.String,
|
|
34
|
+
notes: Schema.optional(Schema.String),
|
|
35
|
+
});
|
|
36
|
+
export interface Reply extends Schema.Schema.Type<typeof Reply> {}
|
|
37
|
+
|
|
38
|
+
/** What the user message tells the compiler about one goal. */
|
|
39
|
+
export type Goal = {
|
|
40
|
+
readonly goal: string;
|
|
41
|
+
/** Owner-written guidance, e.g. "follow up after 2 days". */
|
|
42
|
+
readonly instructions?: string;
|
|
43
|
+
/** Handle of the actor who owns the goal. */
|
|
44
|
+
readonly owner: string;
|
|
45
|
+
/** Creation time (ISO); `elapsed(goal, …)` and `every` count from it. */
|
|
46
|
+
readonly now: string;
|
|
47
|
+
/** Source id of the conversation a session goal is scoped to. */
|
|
48
|
+
readonly session?: string;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export type ReplyErrorCode =
|
|
52
|
+
| 'missing-datalog'
|
|
53
|
+
| 'empty-datalog'
|
|
54
|
+
| 'invalid-kind'
|
|
55
|
+
| 'invalid-drivers'
|
|
56
|
+
| 'invalid-achievement';
|
|
57
|
+
|
|
58
|
+
/** Thrown by `parseReply` when the model's reply does not follow the output format. */
|
|
59
|
+
export class ReplyError extends BaseError.extend('ReplyError', 'Reply does not follow the output format') {
|
|
60
|
+
constructor(
|
|
61
|
+
readonly code: ReplyErrorCode,
|
|
62
|
+
readonly reason: string,
|
|
63
|
+
) {
|
|
64
|
+
super({ message: reason, context: { code } });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One line per fact relation; typed so a new relation cannot be added without describing it. */
|
|
69
|
+
export const FACT_RELATION_DOCS: Readonly<Record<keyof typeof Encoding.FACT_RELATIONS, string>> = {
|
|
70
|
+
fact: 'fact(F, S, P, O) subject, predicate, object (entities are lowercase handles: rich, dima; the goal itself is the constant goal)',
|
|
71
|
+
speaker: "speaker(F, X) who said it: a handle, or agent for the agent's own actions",
|
|
72
|
+
force: 'force(F, X) assertive | directive | commissive | expressive',
|
|
73
|
+
polarity: 'polarity(F, X) "+" (affirmed), "-" (negated or refused), "?" (open question or unknown)',
|
|
74
|
+
mood: 'mood(F, X) declarative | interrogative | imperative',
|
|
75
|
+
factuality: 'factuality(F, X) "CT+" (certain), "PR+" (probable), "PS+" (possible), "Uu" (unknown), "CT-" …',
|
|
76
|
+
addressee: 'addressee(F, X) who it was said to',
|
|
77
|
+
quote: 'quote(F, Text) the words as said',
|
|
78
|
+
source:
|
|
79
|
+
'source(F, Src) the message or conversation, e.g. "chat:general", "mailbox:rich", "session:s42", "goal"',
|
|
80
|
+
saidAt: 'saidAt(F, T) when it was said (ISO timestamp)',
|
|
81
|
+
surface: 'surface(F, P) the predicate as extracted, before mapping to the canonical one',
|
|
82
|
+
supersedes: 'supersedes(F, Older) F corrects the fact Older',
|
|
83
|
+
validFrom: 'validFrom(F, T) when the statement starts to hold',
|
|
84
|
+
validTo: 'validTo(F, T) when the statement stops holding',
|
|
85
|
+
confidence: 'confidence(F, N) extractor confidence 0..1',
|
|
86
|
+
nature: 'nature(F, X) epistemic | aleatory',
|
|
87
|
+
recordedAt: 'recordedAt(F, T) when it was extracted',
|
|
88
|
+
pass: 'pass(F, Id) the extraction pass that produced it',
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** One line per goal-state relation the runtime maintains. */
|
|
92
|
+
export const GOAL_RELATION_DOCS: Readonly<Record<keyof typeof Encoding.GOAL_RELATIONS, string>> = {
|
|
93
|
+
subgoal: 'subgoal(goal, G) G is a sub-goal of this goal',
|
|
94
|
+
status: 'status(G, S) current status of a sub-goal: active | paused | achieved | cancelled',
|
|
95
|
+
action: 'action(A, Kind) an action the agent is ABOUT to take (constraints only)',
|
|
96
|
+
actionArg: 'actionArg(A, Key, Value) an argument of that action',
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** One entry per goal built-in, keyed by its name in `Builtins.make`. */
|
|
100
|
+
export const BUILTIN_DOCS: Readonly<Record<string, string>> = {
|
|
101
|
+
about: trim`
|
|
102
|
+
about(F, "text") fact F is about the text (its quote, subject, predicate and object). If F is unbound it
|
|
103
|
+
enumerates every matching fact (an index lookup), so it can start a rule body. Keep the text
|
|
104
|
+
short: the key noun phrase ("agent plugin", "release"), not a sentence.
|
|
105
|
+
`,
|
|
106
|
+
concerns: trim`
|
|
107
|
+
concerns(F, Entity) fact F concerns that entity (resolved subject or beneficiary, e.g. "your tax return" said to
|
|
108
|
+
rich concerns rich). If F is unbound it enumerates the facts concerning the entity.
|
|
109
|
+
`,
|
|
110
|
+
elapsed: 'elapsed(Ref, Dur) at least Dur has passed since Ref: goal (its creation), a fact id, or a timestamp',
|
|
111
|
+
every: "every(Dur) true once per period of Dur, counted from the goal's creation: a cadence",
|
|
112
|
+
due: 'due(Time, Lead) now is at or after Time minus Lead (due("2027-06-30T00:00:00Z", 0d): the deadline has passed)',
|
|
113
|
+
weekday: 'weekday(Time, D) D is monday..sunday (UTC); binds D if unbound',
|
|
114
|
+
hour: 'hour(Time, H) H is the UTC hour 0..23; binds H if unbound',
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/** One line per head the runtime reads. */
|
|
118
|
+
export const HEAD_DOCS: Readonly<Record<(typeof Compiler.GOAL_HEADS)[number], string>> = {
|
|
119
|
+
wake: 'wake(label) wake the goal for judgment; label is a constant naming the reason',
|
|
120
|
+
achieved: 'achieved(goal) the outcome has been reached (outcome goals only)',
|
|
121
|
+
holds: 'holds(goal) the maintained state currently holds (condition goals only)',
|
|
122
|
+
blocks: 'blocks(A) the constraint forbids proposed action A (constraints only)',
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
type Example = {
|
|
126
|
+
readonly goal: string;
|
|
127
|
+
readonly owner: string;
|
|
128
|
+
readonly kind: Kind;
|
|
129
|
+
readonly drivers: ReadonlyArray<Driver>;
|
|
130
|
+
readonly achievement?: Achievement;
|
|
131
|
+
readonly datalog: string;
|
|
132
|
+
readonly notes: string;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** Worked examples; tests compile each one so they stay valid in the dialect. */
|
|
136
|
+
export const EXAMPLES: ReadonlyArray<Example> = [
|
|
137
|
+
{
|
|
138
|
+
goal: 'Tell me when Alice confirms the venue for the offsite',
|
|
139
|
+
owner: 'rich',
|
|
140
|
+
kind: 'outcome',
|
|
141
|
+
drivers: ['fact'],
|
|
142
|
+
achievement: 'rule',
|
|
143
|
+
datalog: trim`
|
|
144
|
+
% anything Alice says about the venue may matter (judgment decides)
|
|
145
|
+
wake(venue_news) :- about(F, "venue"), speaker(F, alice), not achieved(goal).
|
|
146
|
+
% a confirmation is an affirmed, non-question statement about the venue
|
|
147
|
+
confirmed(F) :- about(F, "venue"), speaker(F, alice), polarity(F, "+"), not mood(F, interrogative).
|
|
148
|
+
% the outcome is that the owner was told after a confirmation
|
|
149
|
+
achieved(goal) :- confirmed(F), notified(N, goal, rich), saidAt(F, T1), saidAt(N, T2), T2 >= T1.
|
|
150
|
+
`,
|
|
151
|
+
notes: 'Wakes on any Alice venue statement; judgment decides whether it is a confirmation worth telling.',
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
goal: 'Water the plants every 3 days until the end of June',
|
|
155
|
+
owner: 'rich',
|
|
156
|
+
kind: 'outcome',
|
|
157
|
+
drivers: ['time'],
|
|
158
|
+
achievement: 'rule',
|
|
159
|
+
datalog: trim`
|
|
160
|
+
wake(water) :- every(3d), not due("2027-06-30T23:59:59Z", 0d).
|
|
161
|
+
achieved(goal) :- due("2027-06-30T23:59:59Z", 0d).
|
|
162
|
+
`,
|
|
163
|
+
notes: "Purely time-driven; the cadence is counted from the goal's creation.",
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
goal: "Don't schedule anything before 9am",
|
|
167
|
+
owner: 'rich',
|
|
168
|
+
kind: 'constraint',
|
|
169
|
+
drivers: ['action'],
|
|
170
|
+
datalog: trim`
|
|
171
|
+
schedules(A) :- action(A, book_meeting).
|
|
172
|
+
schedules(A) :- action(A, update_meeting).
|
|
173
|
+
blocks(A) :- schedules(A), actionArg(A, start, T), hour(T, H), H < 9.
|
|
174
|
+
`,
|
|
175
|
+
notes: 'Checked before actions only; facts never wake a constraint.',
|
|
176
|
+
},
|
|
177
|
+
];
|
|
178
|
+
|
|
179
|
+
const formatExample = ({ goal, owner, kind, drivers, achievement, datalog, notes }: Example, index: number): string =>
|
|
180
|
+
trim`
|
|
181
|
+
## Example ${String.fromCharCode(65 + index)}
|
|
182
|
+
Goal: "${goal}" Owner: ${owner}
|
|
183
|
+
<kind>${kind}</kind>
|
|
184
|
+
<drivers>${drivers.join(', ')}</drivers>
|
|
185
|
+
${achievement ? `<achievement>${achievement}</achievement>` : ''}
|
|
186
|
+
<datalog>
|
|
187
|
+
${datalog}
|
|
188
|
+
</datalog>
|
|
189
|
+
<notes>${notes}</notes>
|
|
190
|
+
`
|
|
191
|
+
.split('\n')
|
|
192
|
+
.filter((line) => line.length > 0)
|
|
193
|
+
.join('\n');
|
|
194
|
+
|
|
195
|
+
export type SystemPromptOptions = {
|
|
196
|
+
/** Canonical predicates the prompt offers as shorthand; defaults to the compiler's vocabulary. */
|
|
197
|
+
readonly vocabulary?: Vocabulary.Vocabulary;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** The compile prompt; built from the relations, built-ins and vocabulary so it cannot drift from the compiler. */
|
|
201
|
+
export const systemPrompt = ({ vocabulary = Compiler.defaultVocabulary() }: SystemPromptOptions = {}): string => {
|
|
202
|
+
const lines = (docs: Readonly<Record<string, string>>) =>
|
|
203
|
+
Object.values(docs)
|
|
204
|
+
.map((doc) => `- ${doc.replaceAll('\n', '\n ')}`)
|
|
205
|
+
.join('\n');
|
|
206
|
+
const canonical = vocabulary.entries
|
|
207
|
+
.map(({ predicate, synonyms = [] }) =>
|
|
208
|
+
synonyms.length > 0 ? `- ${predicate} (extracted as: ${synonyms.join(', ')})` : `- ${predicate}`,
|
|
209
|
+
)
|
|
210
|
+
.join('\n');
|
|
211
|
+
|
|
212
|
+
return trim`
|
|
213
|
+
You compile an agent's goals into rules that a cheap, deterministic runtime evaluates without a model.
|
|
214
|
+
|
|
215
|
+
A goal is a plain-text directive owned by an actor. The runtime only needs to know WHEN to wake the goal for model
|
|
216
|
+
judgment, WHEN its outcome is achieved (an outcome goal) or WHEN its state holds (a condition goal), and, for
|
|
217
|
+
constraints, WHICH proposed actions it blocks. Everything else (what to write, whether to act) is judgment and is NOT
|
|
218
|
+
your job. Prefer wake rules that are slightly too broad over ones that miss relevant facts: judgment filters noise, a
|
|
219
|
+
missed wake is lost forever. \`achieved\` must be precise: a false achievement closes the goal.
|
|
220
|
+
|
|
221
|
+
# Facts
|
|
222
|
+
|
|
223
|
+
The agent's knowledge is a set of fact tuples (one per extracted statement), each with an id F. Statements by people
|
|
224
|
+
and actions the agent itself takes are all facts. Predicates are open vocabulary chosen by an extractor; the
|
|
225
|
+
extractor maps the known surface forms below onto canonical predicates, keeping the original in surface(F, P). Do not
|
|
226
|
+
rely on any other exact predicate string: use about/2 for content.
|
|
227
|
+
|
|
228
|
+
# Datalog dialect
|
|
229
|
+
|
|
230
|
+
Syntax: \`head :- lit, lit, ... .\` Variables start uppercase or with \`_\` (\`_\` alone is anonymous). Constants are
|
|
231
|
+
lowercase identifiers (dima, commissive, goal) or "double-quoted strings". Durations are constants such as 30m, 12h,
|
|
232
|
+
2d, 1w. \`%\` starts a comment.
|
|
233
|
+
Negation: \`not p(X)\` (stratified; every variable in a negated literal must be bound by a positive literal).
|
|
234
|
+
Comparisons: \`X < Y\`, \`X >= Y\`, \`X = Y\`, \`X != Y\` (numbers, ISO timestamps or strings; both sides bound).
|
|
235
|
+
Aggregates: \`N = count : { p(X) }\`, \`M = min T : { saidAt(F, T) }\` (count, min, max, sum).
|
|
236
|
+
You may define helper predicates (lowercase, any arity). No other syntax: no disjunction (\`;\`), no arithmetic, no
|
|
237
|
+
lists, no functions; write one rule per alternative instead.
|
|
238
|
+
|
|
239
|
+
Fact relations (F is a fact id):
|
|
240
|
+
${lines(FACT_RELATION_DOCS)}
|
|
241
|
+
|
|
242
|
+
Canonical predicates. Each may be written as shorthand: \`helps_with(S, O)\` means \`fact(_, S, helps_with, O)\` and
|
|
243
|
+
\`helps_with(F, S, O)\` also binds the fact id. Use the canonical name, never a surface form, in fact/4 or shorthand:
|
|
244
|
+
${canonical}
|
|
245
|
+
|
|
246
|
+
Goal-state relations (maintained by the runtime):
|
|
247
|
+
${lines(GOAL_RELATION_DOCS)}
|
|
248
|
+
|
|
249
|
+
Built-ins (deterministic, evaluated by the runtime):
|
|
250
|
+
${lines(BUILTIN_DOCS)}
|
|
251
|
+
|
|
252
|
+
Heads you produce (the runtime reads only these):
|
|
253
|
+
${lines(HEAD_DOCS)}
|
|
254
|
+
You may reference achieved(goal) and holds(goal) in bodies (e.g. \`not achieved(goal)\`). Rules may not define the
|
|
255
|
+
fact or goal-state relations.
|
|
256
|
+
|
|
257
|
+
# Evaluation semantics
|
|
258
|
+
|
|
259
|
+
Rules are re-evaluated after every new fact and every clock tick. A wake rule FIRES when it gains a satisfying binding
|
|
260
|
+
of its body variables that it did not have at the previous evaluation. So:
|
|
261
|
+
- a fact-driven wake rule must bind the fact variable (F), so that each new matching fact fires it again;
|
|
262
|
+
- \`elapsed(goal, 3d)\` fires once when it first becomes true; \`every(1d)\` fires once per period;
|
|
263
|
+
- guard time-driven wakes with \`not achieved(goal)\` so a closed goal stops waking;
|
|
264
|
+
- the runtime itself wakes the goal when achieved(goal) first becomes true and whenever a sub-goal's status changes,
|
|
265
|
+
so you need no wake rule for either.
|
|
266
|
+
|
|
267
|
+
# Known vocabularies
|
|
268
|
+
|
|
269
|
+
- Agent actions are recorded in the goal's own feed as fact(F, goal, Verb, Obj) with speaker(F, agent) and
|
|
270
|
+
source(F, "goal"); the verbs are canonical predicates above (relayed, notified, awaiting, drafted, …).
|
|
271
|
+
- Mailbox: an arriving email is fact(F, Msg, received, inbox) with speaker = sender address and
|
|
272
|
+
source = "mailbox:<owner>"; when it leaves the inbox, fact(F, Msg, archived, inbox) or fact(F, Msg, deleted, inbox).
|
|
273
|
+
- Action kinds: book_meeting, update_meeting, cancel_meeting, send_email, send_message, archive_email.
|
|
274
|
+
Arguments: start, end, title, attendees (meetings); to, subject, sendAt (email and messages).
|
|
275
|
+
- A session goal's conversation has source(F, "<session id>"), given with the goal.
|
|
276
|
+
|
|
277
|
+
# Compilation guidance
|
|
278
|
+
|
|
279
|
+
- Match on CONTENT (about) and POLARITY. Do not require a particular speaker, force or mood for achievement unless the
|
|
280
|
+
goal itself names them ("get Dima to …" names Dima and a commitment). Extractor labels such as force are noisy, and
|
|
281
|
+
outcomes are often reported by third parties ("the accountant filed it", "Alice says it shipped").
|
|
282
|
+
- A goal about a person covers facts the person said AND facts whose subject is that person.
|
|
283
|
+
- Possessive goals ("my taxes", "my inbox") concern the owner: use concerns(F, <owner>) rather than a speaker.
|
|
284
|
+
- Session goals: scope wakes to the session's own source; facts from other sources do not concern them.
|
|
285
|
+
- Every variable in a negated literal, a comparison or the head must be bound by a positive literal in the same rule.
|
|
286
|
+
|
|
287
|
+
# Output format
|
|
288
|
+
|
|
289
|
+
Reply with exactly these sections and nothing else:
|
|
290
|
+
<kind>outcome | condition | constraint</kind>
|
|
291
|
+
<drivers>comma-separated subset of: fact, time, action</drivers>
|
|
292
|
+
<achievement>rule | judgment</achievement> (outcome goals only: rule when achieved(goal) is reliable on its own,
|
|
293
|
+
judgment when the model must confirm it before the goal closes)
|
|
294
|
+
<datalog>
|
|
295
|
+
...rules...
|
|
296
|
+
</datalog>
|
|
297
|
+
<notes>one or two sentences on the judgment calls you made, or what the rules leave to judgment</notes>
|
|
298
|
+
|
|
299
|
+
# Worked examples
|
|
300
|
+
|
|
301
|
+
${EXAMPLES.map(formatExample).join('\n\n')}
|
|
302
|
+
`;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
/** The compile prompt over the default vocabulary. */
|
|
306
|
+
export const SYSTEM_PROMPT: string = systemPrompt();
|
|
307
|
+
|
|
308
|
+
/** The user message for one goal. */
|
|
309
|
+
export const userMessage = ({ goal, instructions, owner, now, session }: Goal): string =>
|
|
310
|
+
[
|
|
311
|
+
`Goal: "${goal}"`,
|
|
312
|
+
`Owner: ${owner}`,
|
|
313
|
+
`Created: ${now}`,
|
|
314
|
+
session ? `Session goal; current session id: ${session}` : undefined,
|
|
315
|
+
instructions?.trim() ? `Instructions: ${instructions.trim()}` : undefined,
|
|
316
|
+
]
|
|
317
|
+
.filter((line) => line !== undefined)
|
|
318
|
+
.join('\n');
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Extracts the rules and metadata from a model reply. Tolerates a code fence inside or instead of the `<datalog>`
|
|
322
|
+
* section; metadata sections are optional, but a present one must hold a valid value.
|
|
323
|
+
* @throws ReplyError if there are no rules or a metadata section is invalid.
|
|
324
|
+
*/
|
|
325
|
+
export const parseReply = (text: string): Reply => {
|
|
326
|
+
const raw = section(text, 'datalog') ?? fenced(text);
|
|
327
|
+
if (raw === undefined) {
|
|
328
|
+
throw new ReplyError('missing-datalog', 'reply has no <datalog> section');
|
|
329
|
+
}
|
|
330
|
+
const datalog = fenced(raw) ?? raw;
|
|
331
|
+
if (datalog.trim().length === 0) {
|
|
332
|
+
throw new ReplyError('empty-datalog', 'the <datalog> section is empty');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const kind = section(text, 'kind')?.trim().toLowerCase();
|
|
336
|
+
if (kind !== undefined && !isKind(kind)) {
|
|
337
|
+
throw new ReplyError('invalid-kind', `unknown kind "${kind}"`);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const driversText = section(text, 'drivers');
|
|
341
|
+
const drivers = (driversText ?? '')
|
|
342
|
+
.split(/[,\s]+/)
|
|
343
|
+
.map((driver) => driver.trim().toLowerCase())
|
|
344
|
+
.filter((driver) => driver.length > 0);
|
|
345
|
+
const unknown = drivers.filter((driver) => !isDriver(driver));
|
|
346
|
+
if (unknown.length > 0) {
|
|
347
|
+
throw new ReplyError('invalid-drivers', `unknown drivers ${unknown.map((driver) => `"${driver}"`).join(', ')}`);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const achievementText = section(text, 'achievement')?.trim().toLowerCase();
|
|
351
|
+
if (achievementText !== undefined && !isAchievement(achievementText)) {
|
|
352
|
+
throw new ReplyError('invalid-achievement', `unknown achievement "${achievementText}"`);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const notes = section(text, 'notes')?.trim();
|
|
356
|
+
return {
|
|
357
|
+
...(kind !== undefined && isKind(kind) ? { kind } : {}),
|
|
358
|
+
drivers: [...new Set(drivers.filter(isDriver))],
|
|
359
|
+
...(achievementText !== undefined && isAchievement(achievementText) ? { achievement: achievementText } : {}),
|
|
360
|
+
datalog: datalog.trim(),
|
|
361
|
+
...(notes ? { notes } : {}),
|
|
362
|
+
};
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
const section = (text: string, tag: string): string | undefined =>
|
|
366
|
+
new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, 'i').exec(text)?.[1];
|
|
367
|
+
|
|
368
|
+
const FENCE = /```[a-z]*\s*\n([\s\S]*?)```/i;
|
|
369
|
+
|
|
370
|
+
const fenced = (text: string): string | undefined => FENCE.exec(text)?.[1];
|
|
371
|
+
|
|
372
|
+
const isKind = (value: string): value is Kind => Schema.is(Kind)(value);
|
|
373
|
+
|
|
374
|
+
const isDriver = (value: string): value is Driver => Schema.is(Driver)(value);
|
|
375
|
+
|
|
376
|
+
const isAchievement = (value: string): value is Achievement => Schema.is(Achievement)(value);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { describe, test } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import * as Ast from '@dxos/datalog/Ast';
|
|
8
|
+
import { trim } from '@dxos/util';
|
|
9
|
+
|
|
10
|
+
import * as Compiler from './Compiler.ts';
|
|
11
|
+
import * as Vocabulary from './Vocabulary.ts';
|
|
12
|
+
|
|
13
|
+
const codes = (source: string, options?: Compiler.Options) =>
|
|
14
|
+
Compiler.compile(source, options).diagnostics.map(({ code }) => code);
|
|
15
|
+
|
|
16
|
+
describe('Compiler', () => {
|
|
17
|
+
test('expands shorthand for canonical predicates', ({ expect }) => {
|
|
18
|
+
const { program } = Compiler.compileOrThrow(trim`
|
|
19
|
+
achieved(goal) :- helps_with(dima, "agent plugin").
|
|
20
|
+
wake(reply) :- helps_with(F, dima, X), polarity(F, "-").
|
|
21
|
+
`);
|
|
22
|
+
expect(Ast.format(program)).toBe(
|
|
23
|
+
[
|
|
24
|
+
'achieved(goal) :- fact(_, dima, helps_with, "agent plugin").',
|
|
25
|
+
'wake#1(reply, F, X) :- fact(F, dima, helps_with, X), polarity(F, "-").',
|
|
26
|
+
'wake(reply) :- wake#1(reply, F, X).',
|
|
27
|
+
].join('\n'),
|
|
28
|
+
);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('leaves rule-defined predicates alone even when they share a vocabulary name', ({ expect }) => {
|
|
32
|
+
const { program } = Compiler.compileOrThrow(trim`
|
|
33
|
+
shipped(F) :- about(F, "release"), polarity(F, "+").
|
|
34
|
+
achieved(goal) :- shipped(F).
|
|
35
|
+
`);
|
|
36
|
+
expect(Ast.format(program)).toContain('achieved(goal) :- shipped(F).');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('rejects synonyms, unknown shorthand and wrong shorthand arity', ({ expect }) => {
|
|
40
|
+
const synonym = Compiler.compile('achieved(goal) :- working_on(dima, X).');
|
|
41
|
+
expect(synonym.diagnostics).toEqual([
|
|
42
|
+
expect.objectContaining({ code: 'vocabulary', message: expect.stringContaining('canonical predicate works_on') }),
|
|
43
|
+
]);
|
|
44
|
+
expect(codes('achieved(goal) :- helps_wiht(dima, X).')).toEqual(['undefined']);
|
|
45
|
+
expect(codes('achieved(goal) :- helps_with(dima).')).toEqual(['vocabulary']);
|
|
46
|
+
expect(codes('achieved(goal) :- fact(F, dima, "will-work-on", X).')).toEqual(['vocabulary']);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('accepts open-vocabulary predicates written against fact/4', ({ expect }) => {
|
|
50
|
+
expect(codes('wake(email) :- fact(F, M, "ships-on", inbox).')).toEqual([]);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('checks goal heads and base relations', ({ expect }) => {
|
|
54
|
+
expect(codes('achieved(X) :- speaker(X, dima).')).toEqual(['goal']);
|
|
55
|
+
expect(codes('achieved(me) :- speaker(_, dima).')).toEqual(['goal']);
|
|
56
|
+
expect(codes('wake(L) :- speaker(_, L).')).toEqual(['goal']);
|
|
57
|
+
expect(codes('speaker(F, dima) :- fact(F, _, _, _).')).toEqual(['goal']);
|
|
58
|
+
expect(codes('blocks(A) :- action(A, book_meeting).')).toEqual([]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('reports parse errors and engine checks with positions', ({ expect }) => {
|
|
62
|
+
expect(Compiler.compile('wake(x) :- speaker(F, dima)').diagnostics).toEqual([
|
|
63
|
+
expect.objectContaining({ code: 'parse', position: { line: 1, column: 28 } }),
|
|
64
|
+
]);
|
|
65
|
+
expect(codes('wake(x) :- about(F, T).')).toEqual(['unsafe', 'unsafe']);
|
|
66
|
+
expect(codes('wake(x) :- speaker(F, dima, now).')).toEqual(['arity']);
|
|
67
|
+
expect(codes('p :- not q.\nq :- not p.\nwake(x) :- p.')).toEqual(['unstratifiable']);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('uses a custom vocabulary', ({ expect }) => {
|
|
71
|
+
const vocabulary = Vocabulary.make([{ predicate: 'likes', synonyms: ['enjoys'] }]);
|
|
72
|
+
expect(codes('wake(x) :- likes(alice, X).', { vocabulary })).toEqual([]);
|
|
73
|
+
expect(codes('wake(x) :- enjoys(alice, X).', { vocabulary })).toEqual(['vocabulary']);
|
|
74
|
+
expect(() => Vocabulary.make([{ predicate: 'speaker' }], ['speaker'])).toThrow(/reserved/);
|
|
75
|
+
expect(() => Vocabulary.make([{ predicate: 'Likes' }])).toThrow(/lowercase/);
|
|
76
|
+
expect(() =>
|
|
77
|
+
Vocabulary.make([
|
|
78
|
+
{ predicate: 'likes', synonyms: ['fond-of'] },
|
|
79
|
+
{ predicate: 'loves', synonyms: ['fond of'] },
|
|
80
|
+
]),
|
|
81
|
+
).toThrow(/maps to both/);
|
|
82
|
+
expect(vocabulary.resolve('Enjoys')).toBe('likes');
|
|
83
|
+
expect(vocabulary.resolve('hates')).toBe('hates');
|
|
84
|
+
});
|
|
85
|
+
});
|