@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.
Files changed (68) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +32 -1
  3. package/dist/lib/Builtins.mjs +178 -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 +161 -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 +57 -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/GoalRules.d.ts +66 -0
  34. package/dist/types/src/GoalRules.d.ts.map +1 -0
  35. package/dist/types/src/GoalRules.test.d.ts +2 -0
  36. package/dist/types/src/GoalRules.test.d.ts.map +1 -0
  37. package/dist/types/src/Vocabulary.d.ts +31 -0
  38. package/dist/types/src/Vocabulary.d.ts.map +1 -0
  39. package/dist/types/src/Vocabulary.test.d.ts +2 -0
  40. package/dist/types/src/Vocabulary.test.d.ts.map +1 -0
  41. package/dist/types/src/index.d.ts +7 -0
  42. package/dist/types/src/index.d.ts.map +1 -0
  43. package/dist/types/src/testing/index.d.ts +4 -0
  44. package/dist/types/src/testing/index.d.ts.map +1 -0
  45. package/dist/types/src/testing/reference.d.ts +9 -0
  46. package/dist/types/src/testing/reference.d.ts.map +1 -0
  47. package/dist/types/src/testing/scenarios.d.ts +73 -0
  48. package/dist/types/src/testing/scenarios.d.ts.map +1 -0
  49. package/dist/types/src/testing/simulate.d.ts +31 -0
  50. package/dist/types/src/testing/simulate.d.ts.map +1 -0
  51. package/dist/types/tsconfig.tsbuildinfo +1 -0
  52. package/package.json +74 -5
  53. package/src/Builtins.test.ts +45 -0
  54. package/src/Builtins.ts +274 -0
  55. package/src/CompilePrompt.test.ts +117 -0
  56. package/src/CompilePrompt.ts +376 -0
  57. package/src/Compiler.test.ts +85 -0
  58. package/src/Compiler.ts +234 -0
  59. package/src/Encoding.ts +99 -0
  60. package/src/GoalRules.test.ts +96 -0
  61. package/src/GoalRules.ts +181 -0
  62. package/src/Vocabulary.test.ts +48 -0
  63. package/src/Vocabulary.ts +88 -0
  64. package/src/index.ts +10 -0
  65. package/src/testing/index.ts +7 -0
  66. package/src/testing/reference.ts +91 -0
  67. package/src/testing/scenarios.ts +604 -0
  68. package/src/testing/simulate.ts +127 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CompilePrompt.mjs","names":[],"sources":["../../src/CompilePrompt.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport { BaseError } from '@dxos/errors';\nimport { trim } from '@dxos/util';\n\nimport * as Compiler from './Compiler.ts';\nimport * as Encoding from './Encoding.ts';\nimport * as Vocabulary from './Vocabulary.ts';\n\n/** How a goal is satisfied; read from the goal text, never hardcoded in the runtime. */\nexport const Kind = Schema.Literals(['outcome', 'condition', 'constraint']);\nexport type Kind = Schema.Schema.Type<typeof Kind>;\n\n/** Runtime mechanisms a goal needs: an index subscription, an alarm, a hook before each action. */\nexport const Driver = Schema.Literals(['fact', 'time', 'action']);\nexport type Driver = Schema.Schema.Type<typeof Driver>;\n\n/** Whether `achieved(goal)` closes the goal on its own or only proposes closing it to judgment. */\nexport const Achievement = Schema.Literals(['rule', 'judgment']);\nexport type Achievement = Schema.Schema.Type<typeof Achievement>;\n\n/** A compilation as the model returned it, before `Compiler.compile` checks the rules. */\nexport const Reply = Schema.Struct({\n kind: Schema.optional(Kind),\n drivers: Schema.Array(Driver),\n achievement: Schema.optional(Achievement),\n datalog: Schema.String,\n notes: Schema.optional(Schema.String),\n});\nexport interface Reply extends Schema.Schema.Type<typeof Reply> {}\n\n/** What the user message tells the compiler about one goal. */\nexport type Goal = {\n readonly goal: string;\n /** Owner-written guidance, e.g. \"follow up after 2 days\". */\n readonly instructions?: string;\n /** Handle of the actor who owns the goal. */\n readonly owner: string;\n /** Creation time (ISO); `elapsed(goal, …)` and `every` count from it. */\n readonly now: string;\n /** Source id of the conversation a session goal is scoped to. */\n readonly session?: string;\n};\n\nexport type ReplyErrorCode =\n | 'missing-datalog'\n | 'empty-datalog'\n | 'invalid-kind'\n | 'invalid-drivers'\n | 'invalid-achievement';\n\n/** Thrown by `parseReply` when the model's reply does not follow the output format. */\nexport class ReplyError extends BaseError.extend('ReplyError', 'Reply does not follow the output format') {\n constructor(\n readonly code: ReplyErrorCode,\n readonly reason: string,\n ) {\n super({ message: reason, context: { code } });\n }\n}\n\n/** One line per fact relation; typed so a new relation cannot be added without describing it. */\nexport const FACT_RELATION_DOCS: Readonly<Record<keyof typeof Encoding.FACT_RELATIONS, string>> = {\n fact: 'fact(F, S, P, O) subject, predicate, object (entities are lowercase handles: rich, dima; the goal itself is the constant goal)',\n speaker: \"speaker(F, X) who said it: a handle, or agent for the agent's own actions\",\n force: 'force(F, X) assertive | directive | commissive | expressive',\n polarity: 'polarity(F, X) \"+\" (affirmed), \"-\" (negated or refused), \"?\" (open question or unknown)',\n mood: 'mood(F, X) declarative | interrogative | imperative',\n factuality: 'factuality(F, X) \"CT+\" (certain), \"PR+\" (probable), \"PS+\" (possible), \"Uu\" (unknown), \"CT-\" …',\n addressee: 'addressee(F, X) who it was said to',\n quote: 'quote(F, Text) the words as said',\n source:\n 'source(F, Src) the message or conversation, e.g. \"chat:general\", \"mailbox:rich\", \"session:s42\", \"goal\"',\n saidAt: 'saidAt(F, T) when it was said (ISO timestamp)',\n surface: 'surface(F, P) the predicate as extracted, before mapping to the canonical one',\n supersedes: 'supersedes(F, Older) F corrects the fact Older',\n validFrom: 'validFrom(F, T) when the statement starts to hold',\n validTo: 'validTo(F, T) when the statement stops holding',\n confidence: 'confidence(F, N) extractor confidence 0..1',\n nature: 'nature(F, X) epistemic | aleatory',\n recordedAt: 'recordedAt(F, T) when it was extracted',\n pass: 'pass(F, Id) the extraction pass that produced it',\n};\n\n/** One line per goal-state relation the runtime maintains. */\nexport const GOAL_RELATION_DOCS: Readonly<Record<keyof typeof Encoding.GOAL_RELATIONS, string>> = {\n subgoal: 'subgoal(goal, G) G is a sub-goal of this goal',\n status: 'status(G, S) current status of a sub-goal: active | paused | achieved | cancelled',\n action: 'action(A, Kind) an action the agent is ABOUT to take (constraints only)',\n actionArg: 'actionArg(A, Key, Value) an argument of that action',\n};\n\n/** One entry per goal built-in, keyed by its name in `Builtins.make`. */\nexport const BUILTIN_DOCS: Readonly<Record<string, string>> = {\n about: trim`\n about(F, \"text\") fact F is about the text (its quote, subject, predicate and object). If F is unbound it\n enumerates every matching fact (an index lookup), so it can start a rule body. Keep the text\n short: the key noun phrase (\"agent plugin\", \"release\"), not a sentence.\n `,\n concerns: trim`\n concerns(F, Entity) fact F concerns that entity (resolved subject or beneficiary, e.g. \"your tax return\" said to\n rich concerns rich). If F is unbound it enumerates the facts concerning the entity.\n `,\n elapsed: 'elapsed(Ref, Dur) at least Dur has passed since Ref: goal (its creation), a fact id, or a timestamp',\n every: \"every(Dur) true once per period of Dur, counted from the goal's creation: a cadence\",\n due: 'due(Time, Lead) now is at or after Time minus Lead (due(\"2027-06-30T00:00:00Z\", 0d): the deadline has passed)',\n weekday: 'weekday(Time, D) D is monday..sunday (UTC); binds D if unbound',\n hour: 'hour(Time, H) H is the UTC hour 0..23; binds H if unbound',\n};\n\n/** One line per head the runtime reads. */\nexport const HEAD_DOCS: Readonly<Record<(typeof Compiler.GOAL_HEADS)[number], string>> = {\n wake: 'wake(label) wake the goal for judgment; label is a constant naming the reason',\n achieved: 'achieved(goal) the outcome has been reached (outcome goals only)',\n holds: 'holds(goal) the maintained state currently holds (condition goals only)',\n blocks: 'blocks(A) the constraint forbids proposed action A (constraints only)',\n};\n\ntype Example = {\n readonly goal: string;\n readonly owner: string;\n readonly kind: Kind;\n readonly drivers: ReadonlyArray<Driver>;\n readonly achievement?: Achievement;\n readonly datalog: string;\n readonly notes: string;\n};\n\n/** Worked examples; tests compile each one so they stay valid in the dialect. */\nexport const EXAMPLES: ReadonlyArray<Example> = [\n {\n goal: 'Tell me when Alice confirms the venue for the offsite',\n owner: 'rich',\n kind: 'outcome',\n drivers: ['fact'],\n achievement: 'rule',\n datalog: trim`\n % anything Alice says about the venue may matter (judgment decides)\n wake(venue_news) :- about(F, \"venue\"), speaker(F, alice), not achieved(goal).\n % a confirmation is an affirmed, non-question statement about the venue\n confirmed(F) :- about(F, \"venue\"), speaker(F, alice), polarity(F, \"+\"), not mood(F, interrogative).\n % the outcome is that the owner was told after a confirmation\n achieved(goal) :- confirmed(F), notified(N, goal, rich), saidAt(F, T1), saidAt(N, T2), T2 >= T1.\n `,\n notes: 'Wakes on any Alice venue statement; judgment decides whether it is a confirmation worth telling.',\n },\n {\n goal: 'Water the plants every 3 days until the end of June',\n owner: 'rich',\n kind: 'outcome',\n drivers: ['time'],\n achievement: 'rule',\n datalog: trim`\n wake(water) :- every(3d), not due(\"2027-06-30T23:59:59Z\", 0d).\n achieved(goal) :- due(\"2027-06-30T23:59:59Z\", 0d).\n `,\n notes: \"Purely time-driven; the cadence is counted from the goal's creation.\",\n },\n {\n goal: \"Don't schedule anything before 9am\",\n owner: 'rich',\n kind: 'constraint',\n drivers: ['action'],\n datalog: trim`\n schedules(A) :- action(A, book_meeting).\n schedules(A) :- action(A, update_meeting).\n blocks(A) :- schedules(A), actionArg(A, start, T), hour(T, H), H < 9.\n `,\n notes: 'Checked before actions only; facts never wake a constraint.',\n },\n];\n\nconst formatExample = ({ goal, owner, kind, drivers, achievement, datalog, notes }: Example, index: number): string =>\n trim`\n ## Example ${String.fromCharCode(65 + index)}\n Goal: \"${goal}\" Owner: ${owner}\n <kind>${kind}</kind>\n <drivers>${drivers.join(', ')}</drivers>\n ${achievement ? `<achievement>${achievement}</achievement>` : ''}\n <datalog>\n ${datalog}\n </datalog>\n <notes>${notes}</notes>\n `\n .split('\\n')\n .filter((line) => line.length > 0)\n .join('\\n');\n\nexport type SystemPromptOptions = {\n /** Canonical predicates the prompt offers as shorthand; defaults to the compiler's vocabulary. */\n readonly vocabulary?: Vocabulary.Vocabulary;\n};\n\n/** The compile prompt; built from the relations, built-ins and vocabulary so it cannot drift from the compiler. */\nexport const systemPrompt = ({ vocabulary = Compiler.defaultVocabulary() }: SystemPromptOptions = {}): string => {\n const lines = (docs: Readonly<Record<string, string>>) =>\n Object.values(docs)\n .map((doc) => `- ${doc.replaceAll('\\n', '\\n ')}`)\n .join('\\n');\n const canonical = vocabulary.entries\n .map(({ predicate, synonyms = [] }) =>\n synonyms.length > 0 ? `- ${predicate} (extracted as: ${synonyms.join(', ')})` : `- ${predicate}`,\n )\n .join('\\n');\n\n return trim`\n You compile an agent's goals into rules that a cheap, deterministic runtime evaluates without a model.\n\n A goal is a plain-text directive owned by an actor. The runtime only needs to know WHEN to wake the goal for model\n judgment, WHEN its outcome is achieved (an outcome goal) or WHEN its state holds (a condition goal), and, for\n constraints, WHICH proposed actions it blocks. Everything else (what to write, whether to act) is judgment and is NOT\n your job. Prefer wake rules that are slightly too broad over ones that miss relevant facts: judgment filters noise, a\n missed wake is lost forever. \\`achieved\\` must be precise: a false achievement closes the goal.\n\n # Facts\n\n The agent's knowledge is a set of fact tuples (one per extracted statement), each with an id F. Statements by people\n and actions the agent itself takes are all facts. Predicates are open vocabulary chosen by an extractor; the\n extractor maps the known surface forms below onto canonical predicates, keeping the original in surface(F, P). Do not\n rely on any other exact predicate string: use about/2 for content.\n\n # Datalog dialect\n\n Syntax: \\`head :- lit, lit, ... .\\` Variables start uppercase or with \\`_\\` (\\`_\\` alone is anonymous). Constants are\n lowercase identifiers (dima, commissive, goal) or \"double-quoted strings\". Durations are constants such as 30m, 12h,\n 2d, 1w. \\`%\\` starts a comment.\n Negation: \\`not p(X)\\` (stratified; every variable in a negated literal must be bound by a positive literal).\n Comparisons: \\`X < Y\\`, \\`X >= Y\\`, \\`X = Y\\`, \\`X != Y\\` (numbers, ISO timestamps or strings; both sides bound).\n Aggregates: \\`N = count : { p(X) }\\`, \\`M = min T : { saidAt(F, T) }\\` (count, min, max, sum).\n You may define helper predicates (lowercase, any arity). No other syntax: no disjunction (\\`;\\`), no arithmetic, no\n lists, no functions; write one rule per alternative instead.\n\n Fact relations (F is a fact id):\n ${lines(FACT_RELATION_DOCS)}\n\n Canonical predicates. Each may be written as shorthand: \\`helps_with(S, O)\\` means \\`fact(_, S, helps_with, O)\\` and\n \\`helps_with(F, S, O)\\` also binds the fact id. Use the canonical name, never a surface form, in fact/4 or shorthand:\n ${canonical}\n\n Goal-state relations (maintained by the runtime):\n ${lines(GOAL_RELATION_DOCS)}\n\n Built-ins (deterministic, evaluated by the runtime):\n ${lines(BUILTIN_DOCS)}\n\n Heads you produce (the runtime reads only these):\n ${lines(HEAD_DOCS)}\n You may reference achieved(goal) and holds(goal) in bodies (e.g. \\`not achieved(goal)\\`). Rules may not define the\n fact or goal-state relations.\n\n # Evaluation semantics\n\n Rules are re-evaluated after every new fact and every clock tick. A wake rule FIRES when it gains a satisfying binding\n of its body variables that it did not have at the previous evaluation. So:\n - a fact-driven wake rule must bind the fact variable (F), so that each new matching fact fires it again;\n - \\`elapsed(goal, 3d)\\` fires once when it first becomes true; \\`every(1d)\\` fires once per period;\n - guard time-driven wakes with \\`not achieved(goal)\\` so a closed goal stops waking;\n - the runtime itself wakes the goal when achieved(goal) first becomes true and whenever a sub-goal's status changes,\n so you need no wake rule for either.\n\n # Known vocabularies\n\n - Agent actions are recorded in the goal's own feed as fact(F, goal, Verb, Obj) with speaker(F, agent) and\n source(F, \"goal\"); the verbs are canonical predicates above (relayed, notified, awaiting, drafted, …).\n - Mailbox: an arriving email is fact(F, Msg, received, inbox) with speaker = sender address and\n source = \"mailbox:<owner>\"; when it leaves the inbox, fact(F, Msg, archived, inbox) or fact(F, Msg, deleted, inbox).\n - Action kinds: book_meeting, update_meeting, cancel_meeting, send_email, send_message, archive_email.\n Arguments: start, end, title, attendees (meetings); to, subject, sendAt (email and messages).\n - A session goal's conversation has source(F, \"<session id>\"), given with the goal.\n\n # Compilation guidance\n\n - Match on CONTENT (about) and POLARITY. Do not require a particular speaker, force or mood for achievement unless the\n goal itself names them (\"get Dima to …\" names Dima and a commitment). Extractor labels such as force are noisy, and\n outcomes are often reported by third parties (\"the accountant filed it\", \"Alice says it shipped\").\n - A goal about a person covers facts the person said AND facts whose subject is that person.\n - Possessive goals (\"my taxes\", \"my inbox\") concern the owner: use concerns(F, <owner>) rather than a speaker.\n - Session goals: scope wakes to the session's own source; facts from other sources do not concern them.\n - Every variable in a negated literal, a comparison or the head must be bound by a positive literal in the same rule.\n\n # Output format\n\n Reply with exactly these sections and nothing else:\n <kind>outcome | condition | constraint</kind>\n <drivers>comma-separated subset of: fact, time, action</drivers>\n <achievement>rule | judgment</achievement> (outcome goals only: rule when achieved(goal) is reliable on its own,\n judgment when the model must confirm it before the goal closes)\n <datalog>\n ...rules...\n </datalog>\n <notes>one or two sentences on the judgment calls you made, or what the rules leave to judgment</notes>\n\n # Worked examples\n\n ${EXAMPLES.map(formatExample).join('\\n\\n')}\n `;\n};\n\n/** The compile prompt over the default vocabulary. */\nexport const SYSTEM_PROMPT: string = systemPrompt();\n\n/** The user message for one goal. */\nexport const userMessage = ({ goal, instructions, owner, now, session }: Goal): string =>\n [\n `Goal: \"${goal}\"`,\n `Owner: ${owner}`,\n `Created: ${now}`,\n session ? `Session goal; current session id: ${session}` : undefined,\n instructions?.trim() ? `Instructions: ${instructions.trim()}` : undefined,\n ]\n .filter((line) => line !== undefined)\n .join('\\n');\n\n/**\n * Extracts the rules and metadata from a model reply. Tolerates a code fence inside or instead of the `<datalog>`\n * section; metadata sections are optional, but a present one must hold a valid value.\n * @throws ReplyError if there are no rules or a metadata section is invalid.\n */\nexport const parseReply = (text: string): Reply => {\n const raw = section(text, 'datalog') ?? fenced(text);\n if (raw === undefined) {\n throw new ReplyError('missing-datalog', 'reply has no <datalog> section');\n }\n const datalog = fenced(raw) ?? raw;\n if (datalog.trim().length === 0) {\n throw new ReplyError('empty-datalog', 'the <datalog> section is empty');\n }\n\n const kind = section(text, 'kind')?.trim().toLowerCase();\n if (kind !== undefined && !isKind(kind)) {\n throw new ReplyError('invalid-kind', `unknown kind \"${kind}\"`);\n }\n\n const driversText = section(text, 'drivers');\n const drivers = (driversText ?? '')\n .split(/[,\\s]+/)\n .map((driver) => driver.trim().toLowerCase())\n .filter((driver) => driver.length > 0);\n const unknown = drivers.filter((driver) => !isDriver(driver));\n if (unknown.length > 0) {\n throw new ReplyError('invalid-drivers', `unknown drivers ${unknown.map((driver) => `\"${driver}\"`).join(', ')}`);\n }\n\n const achievementText = section(text, 'achievement')?.trim().toLowerCase();\n if (achievementText !== undefined && !isAchievement(achievementText)) {\n throw new ReplyError('invalid-achievement', `unknown achievement \"${achievementText}\"`);\n }\n\n const notes = section(text, 'notes')?.trim();\n return {\n ...(kind !== undefined && isKind(kind) ? { kind } : {}),\n drivers: [...new Set(drivers.filter(isDriver))],\n ...(achievementText !== undefined && isAchievement(achievementText) ? { achievement: achievementText } : {}),\n datalog: datalog.trim(),\n ...(notes ? { notes } : {}),\n };\n};\n\nconst section = (text: string, tag: string): string | undefined =>\n new RegExp(`<${tag}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${tag}>`, 'i').exec(text)?.[1];\n\nconst FENCE = /```[a-z]*\\s*\\n([\\s\\S]*?)```/i;\n\nconst fenced = (text: string): string | undefined => FENCE.exec(text)?.[1];\n\nconst isKind = (value: string): value is Kind => Schema.is(Kind)(value);\n\nconst isDriver = (value: string): value is Driver => Schema.is(Driver)(value);\n\nconst isAchievement = (value: string): value is Achievement => Schema.is(Achievement)(value);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,OAAO,OAAO,SAAS;CAAC;CAAW;CAAa;AAAY,CAAC;;AAI1E,IAAa,SAAS,OAAO,SAAS;CAAC;CAAQ;CAAQ;AAAQ,CAAC;;AAIhE,IAAa,cAAc,OAAO,SAAS,CAAC,QAAQ,UAAU,CAAC;;AAI/D,IAAa,QAAQ,OAAO,OAAO;CACjC,MAAM,OAAO,SAAS,IAAI;CAC1B,SAAS,OAAO,MAAM,MAAM;CAC5B,aAAa,OAAO,SAAS,WAAW;CACxC,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,MAAM;AACtC,CAAC;;AAwBD,IAAa,aAAb,cAAgC,UAAU,OAAO,cAAc,yCAAyC,CAAC,CAAC;CAE7F;CACA;CAFX,YACE,MACA,QACA;EACA,MAAM;GAAE,SAAS;GAAQ,SAAS,EAAE,KAAK;EAAE,CAAC;EAHnC,KAAA,OAAA;EACA,KAAA,SAAA;CAGX;AACF;;AAGA,IAAa,qBAAqF;CAChG,MAAM;CACN,SAAS;CACT,OAAO;CACP,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AAC,CAAC,KAAK;AAEtE,IAAM,YAAY,UAAmC,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK;AAE5E,IAAM,iBAAiB,UAAwC,OAAO,GAAG,WAAW,CAAC,CAAC,KAAK"}
@@ -0,0 +1,212 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { emptyContext, make } from "./Builtins.mjs";
3
+ import { RELATIONS as RELATIONS$1 } from "./Encoding.mjs";
4
+ import { DEFAULT_ENTRIES, make as make$1 } from "./Vocabulary.mjs";
5
+ import { BaseError } from "@dxos/errors";
6
+ import * as Ast from "@dxos/datalog/Ast";
7
+ import * as Checker from "@dxos/datalog/Checker";
8
+ import * as Parser from "@dxos/datalog/Parser";
9
+ //#region src/Compiler.ts
10
+ var Compiler_exports = /* @__PURE__ */ __exportAll({
11
+ CompileError: () => CompileError,
12
+ GOAL_HEADS: () => GOAL_HEADS,
13
+ RELATIONS: () => RELATIONS,
14
+ compile: () => compile,
15
+ compileOrThrow: () => compileOrThrow,
16
+ defaultVocabulary: () => defaultVocabulary,
17
+ formatDiagnostic: () => formatDiagnostic
18
+ });
19
+ /** Heads a goal program may define: `achieved(goal)`, `holds(goal)`, `wake(Label)`, `blocks(Action)`. */
20
+ var GOAL_HEADS = [
21
+ "achieved",
22
+ "holds",
23
+ "wake",
24
+ "blocks"
25
+ ];
26
+ /** Relations goal rules may read; goal heads a program leaves undefined are empty. */
27
+ var RELATIONS = {
28
+ ...RELATIONS$1,
29
+ ...Object.fromEntries(GOAL_HEADS.map((head) => [head, 1]))
30
+ };
31
+ /** Thrown by `compileOrThrow` and `GoalRules` when compilation reports diagnostics. */
32
+ var CompileError = class extends BaseError.extend("CompileError", "Goal rules do not compile") {
33
+ diagnostics;
34
+ constructor(diagnostics) {
35
+ super({ message: `Goal rules do not compile:\n${diagnostics.map(formatDiagnostic).join("\n")}` });
36
+ this.diagnostics = diagnostics;
37
+ }
38
+ };
39
+ /** Formats a diagnostic as `line:column code: message`. */
40
+ var formatDiagnostic = ({ code, message, position }) => `${position ? `${position.line}:${position.column} ` : ""}${code}: ${message}`;
41
+ /** The vocabulary used when none is given. */
42
+ var defaultVocabulary = () => make$1(DEFAULT_ENTRIES, [...Object.keys(RELATIONS$1), ...GOAL_HEADS]);
43
+ /**
44
+ * Compiles goal rules: parses, expands predicate shorthand for canonical vocabulary predicates
45
+ * (`helps_with(S, O)` → `fact(_, S, helps_with, O)`, `helps_with(F, S, O)` exposes the id),
46
+ * checks goal heads, then runs the engine's static checks against the fact relations.
47
+ */
48
+ var compile = (source, options = {}) => {
49
+ const vocabulary = options.vocabulary ?? defaultVocabulary();
50
+ const builtins = options.builtins ?? make(emptyContext());
51
+ let parsed;
52
+ try {
53
+ parsed = Parser.parse(source);
54
+ } catch (error) {
55
+ if (error instanceof Parser.ParseError) return { diagnostics: [{
56
+ code: "parse",
57
+ message: error.reason,
58
+ position: error.position
59
+ }] };
60
+ throw error;
61
+ }
62
+ const diagnostics = [];
63
+ const defined = new Set(parsed.rules.map((rule) => rule.head.predicate));
64
+ let anonymous = 0;
65
+ const rewriteAtom = (literal, fallback) => {
66
+ const { predicate, terms } = literal.atom;
67
+ const position = literal.position ?? fallback;
68
+ if (predicate === "fact") {
69
+ const stored = terms[2];
70
+ if (stored?.type === "constant") {
71
+ const canonical = vocabulary.canonical(String(stored.value));
72
+ if (canonical !== void 0 && canonical !== stored.value) diagnostics.push({
73
+ code: "vocabulary",
74
+ message: `predicate "${stored.value}" is stored as ${canonical}; use ${canonical}`,
75
+ position
76
+ });
77
+ }
78
+ return literal;
79
+ }
80
+ if (predicate in RELATIONS$1 || builtins.has(predicate) || defined.has(predicate)) return literal;
81
+ if (vocabulary.isCanonical(predicate)) {
82
+ if (terms.length !== 2 && terms.length !== 3) {
83
+ diagnostics.push({
84
+ code: "vocabulary",
85
+ message: `shorthand ${predicate} takes (Subject, Object) or (Fact, Subject, Object), not ${terms.length} arguments`,
86
+ position
87
+ });
88
+ return literal;
89
+ }
90
+ const id = terms.length === 3 ? terms[0] : {
91
+ type: "variable",
92
+ name: `_shorthand${anonymous++}`,
93
+ anonymous: true
94
+ };
95
+ const [subject, object] = terms.length === 3 ? [terms[1], terms[2]] : [terms[0], terms[1]];
96
+ return {
97
+ ...literal,
98
+ atom: Ast.atom("fact", [
99
+ id,
100
+ subject,
101
+ Ast.constant(predicate),
102
+ object
103
+ ])
104
+ };
105
+ }
106
+ const canonical = vocabulary.canonical(predicate);
107
+ if (canonical !== void 0) diagnostics.push({
108
+ code: "vocabulary",
109
+ message: `${predicate} is a synonym; shorthand must use the canonical predicate ${canonical}`,
110
+ position
111
+ });
112
+ return literal;
113
+ };
114
+ const rewriteLiteral = (literal, fallback) => {
115
+ switch (literal.type) {
116
+ case "atom": return rewriteAtom(literal, fallback);
117
+ case "comparison": return literal;
118
+ case "aggregate": return {
119
+ ...literal,
120
+ body: literal.body.map((inner) => rewriteLiteral(inner, literal.position ?? fallback))
121
+ };
122
+ }
123
+ };
124
+ const rules = [];
125
+ const wakes = /* @__PURE__ */ new Map();
126
+ parsed.rules.forEach((parsedRule, index) => {
127
+ const rule = {
128
+ ...parsedRule,
129
+ body: parsedRule.body.map((literal) => rewriteLiteral(literal, parsedRule.position))
130
+ };
131
+ const { predicate, terms } = rule.head;
132
+ if (predicate in RELATIONS$1) diagnostics.push({
133
+ code: "goal",
134
+ message: `rules cannot define the base relation ${predicate}`,
135
+ position: rule.position
136
+ });
137
+ if (isGoalHead(predicate)) {
138
+ const [argument] = terms;
139
+ if (terms.length !== 1) diagnostics.push({
140
+ code: "goal",
141
+ message: `${predicate} takes one argument`,
142
+ position: rule.position
143
+ });
144
+ else if (predicate !== "blocks" && argument.type !== "constant") diagnostics.push({
145
+ code: "goal",
146
+ message: `${predicate} takes a constant argument`,
147
+ position: rule.position
148
+ });
149
+ else if ((predicate === "achieved" || predicate === "holds") && (argument.type !== "constant" || argument.value !== "goal")) diagnostics.push({
150
+ code: "goal",
151
+ message: `${predicate} must be written ${predicate}(goal)`,
152
+ position: rule.position
153
+ });
154
+ }
155
+ const label = terms[0];
156
+ if (predicate === "wake" && terms.length === 1 && label.type === "constant" && rule.body.length > 0) {
157
+ const relation = `wake#${index}`;
158
+ const variables = bodyVariables(rule.body).map((name) => Ast.variable(name));
159
+ wakes.set(relation, String(label.value));
160
+ rules.push({
161
+ ...rule,
162
+ head: Ast.atom(relation, [label, ...variables])
163
+ });
164
+ rules.push({
165
+ head: rule.head,
166
+ body: [{
167
+ type: "atom",
168
+ negated: false,
169
+ atom: Ast.atom(relation, [label, ...variables])
170
+ }],
171
+ position: rule.position
172
+ });
173
+ } else rules.push(rule);
174
+ });
175
+ const program = { rules };
176
+ if (diagnostics.length > 0) return { diagnostics };
177
+ for (const diagnostic of Checker.check(program, {
178
+ builtins,
179
+ relations: RELATIONS
180
+ })) diagnostics.push({
181
+ code: diagnostic.code,
182
+ message: diagnostic.message,
183
+ position: diagnostic.position
184
+ });
185
+ return diagnostics.length > 0 ? { diagnostics } : {
186
+ compilation: {
187
+ source,
188
+ program,
189
+ wakes
190
+ },
191
+ diagnostics
192
+ };
193
+ };
194
+ /** Compiles goal rules, throwing on any diagnostic. */
195
+ var compileOrThrow = (source, options = {}) => {
196
+ const { compilation, diagnostics } = compile(source, options);
197
+ if (!compilation) throw new CompileError(diagnostics);
198
+ return compilation;
199
+ };
200
+ var isGoalHead = (predicate) => GOAL_HEADS.some((head) => head === predicate);
201
+ /** Variables a safe body binds: those of positive literals, comparisons and aggregate results. */
202
+ var bodyVariables = (body) => {
203
+ const names = /* @__PURE__ */ new Set();
204
+ for (const literal of body) if (literal.type === "atom" && !literal.negated) Ast.variablesOf(literal.atom.terms).forEach((name) => names.add(name));
205
+ else if (literal.type === "comparison") Ast.variablesOf([literal.left, literal.right]).forEach((name) => names.add(name));
206
+ else if (literal.type === "aggregate") Ast.variablesOf([literal.result]).forEach((name) => names.add(name));
207
+ return [...names];
208
+ };
209
+ //#endregion
210
+ export { CompileError, GOAL_HEADS, RELATIONS, compile, compileOrThrow, defaultVocabulary, formatDiagnostic, Compiler_exports as t };
211
+
212
+ //# sourceMappingURL=Compiler.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Compiler.mjs","names":[],"sources":["../../src/Compiler.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Ast from '@dxos/datalog/Ast';\nimport type * as Builtin from '@dxos/datalog/Builtin';\nimport * as Checker from '@dxos/datalog/Checker';\nimport * as Parser from '@dxos/datalog/Parser';\nimport { BaseError } from '@dxos/errors';\n\nimport * as Builtins from './Builtins.ts';\nimport * as Encoding from './Encoding.ts';\nimport * as Vocabulary from './Vocabulary.ts';\n\n/** Heads a goal program may define: `achieved(goal)`, `holds(goal)`, `wake(Label)`, `blocks(Action)`. */\nexport const GOAL_HEADS = ['achieved', 'holds', 'wake', 'blocks'] as const;\n\n/** Relations goal rules may read; goal heads a program leaves undefined are empty. */\nexport const RELATIONS: Readonly<Record<string, number>> = {\n ...Encoding.RELATIONS,\n ...Object.fromEntries(GOAL_HEADS.map((head) => [head, 1])),\n};\n\nexport type DiagnosticCode = Checker.DiagnosticCode | 'parse' | 'vocabulary' | 'goal';\n\nexport type Diagnostic = {\n readonly code: DiagnosticCode;\n readonly message: string;\n readonly position?: Ast.Position;\n};\n\n/** A checked goal program ready for evaluation. */\nexport type Compilation = {\n readonly source: string;\n readonly program: Ast.Program;\n /** Per-rule wake relations (one tuple per binding) and the label each one wakes. */\n readonly wakes: ReadonlyMap<string, string>;\n};\n\nexport type Options = {\n readonly vocabulary?: Vocabulary.Vocabulary;\n /** Defaults to the goal built-ins over an empty context (signatures are all checking needs). */\n readonly builtins?: Builtin.Registry;\n};\n\n/** Thrown by `compileOrThrow` and `GoalRules` when compilation reports diagnostics. */\nexport class CompileError extends BaseError.extend('CompileError', 'Goal rules do not compile') {\n // A typed field rather than `context`, which would repeat every diagnostic in the message as JSON.\n readonly diagnostics: ReadonlyArray<Diagnostic>;\n\n constructor(diagnostics: ReadonlyArray<Diagnostic>) {\n super({ message: `Goal rules do not compile:\\n${diagnostics.map(formatDiagnostic).join('\\n')}` });\n this.diagnostics = diagnostics;\n }\n}\n\n/** Formats a diagnostic as `line:column code: message`. */\nexport const formatDiagnostic = ({ code, message, position }: Diagnostic): string =>\n `${position ? `${position.line}:${position.column} ` : ''}${code}: ${message}`;\n\n/** The vocabulary used when none is given. */\nexport const defaultVocabulary = (): Vocabulary.Vocabulary =>\n Vocabulary.make(Vocabulary.DEFAULT_ENTRIES, [...Object.keys(Encoding.RELATIONS), ...GOAL_HEADS]);\n\n/**\n * Compiles goal rules: parses, expands predicate shorthand for canonical vocabulary predicates\n * (`helps_with(S, O)` → `fact(_, S, helps_with, O)`, `helps_with(F, S, O)` exposes the id),\n * checks goal heads, then runs the engine's static checks against the fact relations.\n */\nexport const compile = (\n source: string,\n options: Options = {},\n): { compilation?: Compilation; diagnostics: Diagnostic[] } => {\n const vocabulary = options.vocabulary ?? defaultVocabulary();\n const builtins = options.builtins ?? Builtins.make(Builtins.emptyContext());\n\n let parsed: Ast.Program;\n try {\n parsed = Parser.parse(source);\n } catch (error) {\n if (error instanceof Parser.ParseError) {\n return { diagnostics: [{ code: 'parse', message: error.reason, position: error.position }] };\n }\n throw error;\n }\n\n const diagnostics: Diagnostic[] = [];\n const defined = new Set(parsed.rules.map((rule) => rule.head.predicate));\n let anonymous = 0;\n\n const rewriteAtom = (literal: Ast.AtomLiteral, fallback: Ast.Position | undefined): Ast.AtomLiteral => {\n const { predicate, terms } = literal.atom;\n const position = literal.position ?? fallback;\n if (predicate === 'fact') {\n const stored = terms[2];\n if (stored?.type === 'constant') {\n const canonical = vocabulary.canonical(String(stored.value));\n if (canonical !== undefined && canonical !== stored.value) {\n diagnostics.push({\n code: 'vocabulary',\n message: `predicate \"${stored.value}\" is stored as ${canonical}; use ${canonical}`,\n position,\n });\n }\n }\n return literal;\n }\n if (predicate in Encoding.RELATIONS || builtins.has(predicate) || defined.has(predicate)) {\n return literal;\n }\n if (vocabulary.isCanonical(predicate)) {\n if (terms.length !== 2 && terms.length !== 3) {\n diagnostics.push({\n code: 'vocabulary',\n message: `shorthand ${predicate} takes (Subject, Object) or (Fact, Subject, Object), not ${terms.length} arguments`,\n position,\n });\n return literal;\n }\n const id: Ast.Term =\n terms.length === 3 ? terms[0] : { type: 'variable', name: `_shorthand${anonymous++}`, anonymous: true };\n const [subject, object] = terms.length === 3 ? [terms[1], terms[2]] : [terms[0], terms[1]];\n return { ...literal, atom: Ast.atom('fact', [id, subject, Ast.constant(predicate), object]) };\n }\n const canonical = vocabulary.canonical(predicate);\n if (canonical !== undefined) {\n diagnostics.push({\n code: 'vocabulary',\n message: `${predicate} is a synonym; shorthand must use the canonical predicate ${canonical}`,\n position,\n });\n }\n return literal;\n };\n\n const rewriteLiteral = (literal: Ast.Literal, fallback: Ast.Position | undefined): Ast.Literal => {\n switch (literal.type) {\n case 'atom':\n return rewriteAtom(literal, fallback);\n case 'comparison':\n return literal;\n case 'aggregate':\n return { ...literal, body: literal.body.map((inner) => rewriteLiteral(inner, literal.position ?? fallback)) };\n }\n };\n\n const rules: Ast.Rule[] = [];\n const wakes = new Map<string, string>();\n parsed.rules.forEach((parsedRule, index) => {\n const rule = {\n ...parsedRule,\n body: parsedRule.body.map((literal) => rewriteLiteral(literal, parsedRule.position)),\n };\n const { predicate, terms } = rule.head;\n if (predicate in Encoding.RELATIONS) {\n diagnostics.push({\n code: 'goal',\n message: `rules cannot define the base relation ${predicate}`,\n position: rule.position,\n });\n }\n if (isGoalHead(predicate)) {\n const [argument] = terms;\n if (terms.length !== 1) {\n diagnostics.push({ code: 'goal', message: `${predicate} takes one argument`, position: rule.position });\n } else if (predicate !== 'blocks' && argument.type !== 'constant') {\n diagnostics.push({ code: 'goal', message: `${predicate} takes a constant argument`, position: rule.position });\n } else if (\n (predicate === 'achieved' || predicate === 'holds') &&\n (argument.type !== 'constant' || argument.value !== 'goal')\n ) {\n diagnostics.push({\n code: 'goal',\n message: `${predicate} must be written ${predicate}(goal)`,\n position: rule.position,\n });\n }\n }\n\n const label = terms[0];\n if (predicate === 'wake' && terms.length === 1 && label.type === 'constant' && rule.body.length > 0) {\n // One relation per wake rule, carrying its body bindings, so each new binding is a new tuple.\n const relation = `wake#${index}`;\n const variables = bodyVariables(rule.body).map((name) => Ast.variable(name));\n wakes.set(relation, String(label.value));\n rules.push({ ...rule, head: Ast.atom(relation, [label, ...variables]) });\n rules.push({\n head: rule.head,\n body: [{ type: 'atom', negated: false, atom: Ast.atom(relation, [label, ...variables]) }],\n position: rule.position,\n });\n } else {\n rules.push(rule);\n }\n });\n\n const program: Ast.Program = { rules };\n if (diagnostics.length > 0) {\n // Engine checks would repeat each vocabulary error as an undefined predicate.\n return { diagnostics };\n }\n for (const diagnostic of Checker.check(program, { builtins, relations: RELATIONS })) {\n diagnostics.push({ code: diagnostic.code, message: diagnostic.message, position: diagnostic.position });\n }\n return diagnostics.length > 0 ? { diagnostics } : { compilation: { source, program, wakes }, diagnostics };\n};\n\n/** Compiles goal rules, throwing on any diagnostic. */\nexport const compileOrThrow = (source: string, options: Options = {}): Compilation => {\n const { compilation, diagnostics } = compile(source, options);\n if (!compilation) {\n throw new CompileError(diagnostics);\n }\n return compilation;\n};\n\nconst isGoalHead = (predicate: string): boolean => GOAL_HEADS.some((head) => head === predicate);\n\n/** Variables a safe body binds: those of positive literals, comparisons and aggregate results. */\nconst bodyVariables = (body: ReadonlyArray<Ast.Literal>): string[] => {\n const names = new Set<string>();\n for (const literal of body) {\n if (literal.type === 'atom' && !literal.negated) {\n Ast.variablesOf(literal.atom.terms).forEach((name) => names.add(name));\n } else if (literal.type === 'comparison') {\n Ast.variablesOf([literal.left, literal.right]).forEach((name) => names.add(name));\n } else if (literal.type === 'aggregate') {\n Ast.variablesOf([literal.result]).forEach((name) => names.add(name));\n }\n }\n return [...names];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,IAAa,aAAa;CAAC;CAAY;CAAS;CA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olldown-runtime.mjs";
2
+ import { RDF } from "@dxos/pipeline-rdf";
3
+ //#region src/Encoding.ts
4
+ var Encoding_exports = /* @__PURE__ */ __exportAll({
5
+ FACT_RELATIONS: () => FACT_RELATIONS,
6
+ GOAL_RELATIONS: () => GOAL_RELATIONS,
7
+ RELATIONS: () => RELATIONS,
8
+ encode: () => encode,
9
+ factIds: () => factIds
10
+ });
11
+ /** Relations every fact contributes to, keyed by the fact id `F`. */
12
+ var FACT_RELATIONS = {
13
+ fact: 4,
14
+ speaker: 2,
15
+ force: 2,
16
+ polarity: 2,
17
+ mood: 2,
18
+ factuality: 2,
19
+ addressee: 2,
20
+ quote: 2,
21
+ source: 2,
22
+ saidAt: 2,
23
+ surface: 2,
24
+ supersedes: 2,
25
+ validFrom: 2,
26
+ validTo: 2,
27
+ confidence: 2,
28
+ nature: 2,
29
+ recordedAt: 2,
30
+ pass: 2
31
+ };
32
+ /** Relations the goal runtime maintains: sub-goal status and proposed actions. */
33
+ var GOAL_RELATIONS = {
34
+ subgoal: 2,
35
+ status: 2,
36
+ action: 2,
37
+ actionArg: 3
38
+ };
39
+ /** Every base relation a goal rule may read. */
40
+ var RELATIONS = {
41
+ ...FACT_RELATIONS,
42
+ ...GOAL_RELATIONS
43
+ };
44
+ /**
45
+ * Encodes a fact as `fact(F, S, P, O)` plus one metadata relation per present field. `P` is the
46
+ * canonical predicate when the vocabulary knows the surface form, which `surface(F, …)` keeps; a fact
47
+ * without an illocution is `assertive`, and `supersedes` lists `attribution.wasDerivedFrom`.
48
+ */
49
+ var encode = (fact, vocabulary) => {
50
+ const { id, assertion, factuality, illocution, attribution } = fact;
51
+ const entries = [
52
+ {
53
+ relation: "fact",
54
+ tuple: [
55
+ id,
56
+ RDF.termValue(assertion.subject),
57
+ vocabulary?.resolve(assertion.predicate) ?? assertion.predicate,
58
+ RDF.termValue(assertion.object)
59
+ ]
60
+ },
61
+ {
62
+ relation: "surface",
63
+ tuple: [id, assertion.predicate]
64
+ },
65
+ {
66
+ relation: "force",
67
+ tuple: [id, illocution?.force ?? "assertive"]
68
+ },
69
+ {
70
+ relation: "polarity",
71
+ tuple: [id, factuality.polarity]
72
+ },
73
+ {
74
+ relation: "factuality",
75
+ tuple: [id, factuality.value]
76
+ },
77
+ {
78
+ relation: "source",
79
+ tuple: [id, attribution.source]
80
+ },
81
+ {
82
+ relation: "saidAt",
83
+ tuple: [id, attribution.generatedAtTime]
84
+ },
85
+ {
86
+ relation: "recordedAt",
87
+ tuple: [id, fact.recordedAt]
88
+ }
89
+ ];
90
+ const optional = [
91
+ ["speaker", attribution.agent],
92
+ ["mood", illocution?.mood],
93
+ ["addressee", illocution?.addressee],
94
+ ["quote", assertion.quote],
95
+ ["validFrom", assertion.validFrom],
96
+ ["validTo", assertion.validTo],
97
+ ["confidence", factuality.confidence],
98
+ ["nature", factuality.nature],
99
+ ["pass", fact.pass]
100
+ ];
101
+ for (const [relation, value] of optional) if (value !== void 0) entries.push({
102
+ relation,
103
+ tuple: [id, value]
104
+ });
105
+ for (const superseded of attribution.wasDerivedFrom ?? []) entries.push({
106
+ relation: "supersedes",
107
+ tuple: [id, superseded]
108
+ });
109
+ return entries;
110
+ };
111
+ /** The fact ids among base entries (from provenance). */
112
+ var factIds = (entries) => [...new Set(entries.flatMap(({ relation, tuple }) => relation in FACT_RELATIONS && typeof tuple[0] === "string" ? [tuple[0]] : []))];
113
+ //#endregion
114
+ export { FACT_RELATIONS, GOAL_RELATIONS, RELATIONS, encode, factIds, Encoding_exports as t };
115
+
116
+ //# sourceMappingURL=Encoding.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Encoding.mjs","names":[],"sources":["../../src/Encoding.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as Engine from '@dxos/datalog/Engine';\nimport { RDF } from '@dxos/pipeline-rdf';\n\nimport type * as Vocabulary from './Vocabulary.ts';\n\n/** Relations every fact contributes to, keyed by the fact id `F`. */\nexport const FACT_RELATIONS = {\n fact: 4,\n speaker: 2,\n force: 2,\n polarity: 2,\n mood: 2,\n factuality: 2,\n addressee: 2,\n quote: 2,\n source: 2,\n saidAt: 2,\n surface: 2,\n supersedes: 2,\n validFrom: 2,\n validTo: 2,\n confidence: 2,\n nature: 2,\n recordedAt: 2,\n pass: 2,\n} as const;\n\n/** Relations the goal runtime maintains: sub-goal status and proposed actions. */\nexport const GOAL_RELATIONS = {\n subgoal: 2,\n status: 2,\n action: 2,\n actionArg: 3,\n} as const;\n\n/** Every base relation a goal rule may read. */\nexport const RELATIONS: Readonly<Record<string, number>> = { ...FACT_RELATIONS, ...GOAL_RELATIONS };\n\n/**\n * Encodes a fact as `fact(F, S, P, O)` plus one metadata relation per present field. `P` is the\n * canonical predicate when the vocabulary knows the surface form, which `surface(F, …)` keeps; a fact\n * without an illocution is `assertive`, and `supersedes` lists `attribution.wasDerivedFrom`.\n */\nexport const encode = (fact: RDF.Fact, vocabulary?: Vocabulary.Vocabulary): Engine.Entry[] => {\n const { id, assertion, factuality, illocution, attribution } = fact;\n const entries: Engine.Entry[] = [\n {\n relation: 'fact',\n tuple: [\n id,\n RDF.termValue(assertion.subject),\n vocabulary?.resolve(assertion.predicate) ?? assertion.predicate,\n RDF.termValue(assertion.object),\n ],\n },\n { relation: 'surface', tuple: [id, assertion.predicate] },\n { relation: 'force', tuple: [id, illocution?.force ?? 'assertive'] },\n { relation: 'polarity', tuple: [id, factuality.polarity] },\n { relation: 'factuality', tuple: [id, factuality.value] },\n { relation: 'source', tuple: [id, attribution.source] },\n { relation: 'saidAt', tuple: [id, attribution.generatedAtTime] },\n { relation: 'recordedAt', tuple: [id, fact.recordedAt] },\n ];\n const optional: ReadonlyArray<[string, string | number | undefined]> = [\n ['speaker', attribution.agent],\n ['mood', illocution?.mood],\n ['addressee', illocution?.addressee],\n ['quote', assertion.quote],\n ['validFrom', assertion.validFrom],\n ['validTo', assertion.validTo],\n ['confidence', factuality.confidence],\n ['nature', factuality.nature],\n ['pass', fact.pass],\n ];\n for (const [relation, value] of optional) {\n if (value !== undefined) {\n entries.push({ relation, tuple: [id, value] });\n }\n }\n for (const superseded of attribution.wasDerivedFrom ?? []) {\n entries.push({ relation: 'supersedes', tuple: [id, superseded] });\n }\n return entries;\n};\n\n/** The fact ids among base entries (from provenance). */\nexport const factIds = (entries: ReadonlyArray<Engine.Entry>): string[] => [\n ...new Set(\n entries.flatMap(({ relation, tuple }) =>\n relation in FACT_RELATIONS && typeof tuple[0] === 'string' ? [tuple[0]] : [],\n ),\n ),\n];\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,iBAAiB;CAC5B,MAAM;CACN,SAAS;CACT,OAAO;CACP,UAAU;CACV,MAAM;CACN,YAAY;CACZ,WAAW;CACX,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,YAAY;CACZ,WAAW;CACX,SAAS;CACT,YAAY;CACZ,QAAQ;CACR,YAAY;CACZ,MAAM;AACR;;AAGA,IAAa,iBAAiB;CAC5B,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,WAAW;AACb;;AAGA,IAAa,YAA8C;CAAE,GAAG;CAAgB,GAAG;AAAe;;;;;;AAOlG,IAAa,UAAU,MAAgB,eAAuD;CAC5F,MAAM,EAAE,IAAI,WAAW,YAAY,YAAY,gBAAgB;CAC/D,MAAM,UAA0B;EAC9B;GACE,UAAU;GACV,OAAO;IACL;IACA,IAAI,UAAU,UAAU,OAAO;IAC/B,YAAY,QAAQ,UAAU,SAAS,KAAK,UAAU;IACtD,IAAI,UAAU,UAAU,MAAM;GAChC;EACF;EACA;GAAE,UAAU;GAAW,OAAO,CAAC,IAAI,UAAU,SAAS;EAAE;EACxD;GAAE,UAAU;GAAS,OAAO,CAAC,IAAI,YAAY,SAAS,WAAW;EAAE;EACnE;GAAE,UAAU;GAAY,OAAO,CAAC,IAAI,WAAW,QAAQ;EAAE;EACzD;GAAE,UAAU;GAAc,OAAO,CAAC,IAAI,WAAW,KAAK;EAAE;EACxD;GAAE,UAAU;GAAU,OAAO,CAAC,IAAI,YAAY,MAAM;EAAE;EACtD;GAAE,UAAU;GAAU,OAAO,CAAC,IAAI,YAAY,eAAe;EAAE;EAC/D;GAAE,UAAU;GAAc,OAAO,CAAC,IAAI,KAAK,UAAU;EAAE;CACzD;CACA,MAAM,WAAiE;EACrE,CAAC,WAAW,YAAY,KAAK;EAC7B,CAAC,QAAQ,YAAY,IAAI;EACzB,CAAC,aAAa,YAAY,SAAS;EACnC,CAAC,SAAS,UAAU,KAAK;EACzB,CAAC,aAAa,UAAU,SAAS;EACjC,CAAC,WAAW,UAAU,OAAO;EAC7B,CAAC,cAAc,WAAW,UAAU;EACpC,CAAC,UAAU,WAAW,MAAM;EAC5B,CAAC,QAAQ,KAAK,IAAI;CACpB;CACA,KAAK,MAAM,CAAC,UAAU,UAAU,UAC9B,IAAI,UAAU,KAAA,GACZ,QAAQ,KAAK;EAAE;EAAU,OAAO,CAAC,IAAI,KAAK;CAAE,CAAC;CAGjD,KAAK,MAAM,cAAc,YAAY,kBAAkB,CAAC,GACtD,QAAQ,KAAK;EAAE,UAAU;EAAc,OAAO,CAAC,IAAI,UAAU;CAAE,CAAC;CAElE,OAAO;AACT;;AAGA,IAAa,WAAW,YAAmD,CACzE,GAAG,IAAI,IACL,QAAQ,SAAS,EAAE,UAAU,YAC3B,YAAY,kBAAkB,OAAO,MAAM,OAAO,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAC7E,CACF,CACF"}
@@ -0,0 +1,161 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { KeywordIndex, MemoryEntityIndex, make as make$1 } from "./Builtins.mjs";
3
+ import { encode, factIds } from "./Encoding.mjs";
4
+ import { RELATIONS, compileOrThrow, defaultVocabulary } from "./Compiler.mjs";
5
+ import { RDF } from "@dxos/pipeline-rdf";
6
+ import * as Engine from "@dxos/datalog/Engine";
7
+ //#region src/GoalRules.ts
8
+ var GoalRules_exports = /* @__PURE__ */ __exportAll({
9
+ GoalRules: () => GoalRules,
10
+ make: () => make
11
+ });
12
+ /**
13
+ * Evaluates one goal's compiled rules over a growing fact stream and a clock. A goal wakes when a
14
+ * wake rule gains a new binding, when `achieved` first becomes true, and when a sub-goal's status
15
+ * changes.
16
+ */
17
+ var GoalRules = class {
18
+ compilation;
19
+ #engine;
20
+ #vocabulary;
21
+ #text;
22
+ #entities;
23
+ #concerns;
24
+ #saidAt = /* @__PURE__ */ new Map();
25
+ #subgoals = /* @__PURE__ */ new Map();
26
+ #now;
27
+ #previous;
28
+ #achieved = false;
29
+ /** @throws Compiler.CompileError if the rules do not compile. */
30
+ constructor(options) {
31
+ this.#now = options.createdAt;
32
+ this.#previous = options.createdAt;
33
+ this.#vocabulary = options.vocabulary ?? defaultVocabulary();
34
+ this.#text = options.text ?? new KeywordIndex();
35
+ this.#entities = options.entities ?? new MemoryEntityIndex();
36
+ this.#concerns = options.concerns ?? ((fact) => [RDF.termValue(fact.assertion.subject)]);
37
+ const builtins = make$1({
38
+ clock: {
39
+ now: () => this.#now,
40
+ previous: () => this.#previous,
41
+ createdAt: options.createdAt,
42
+ saidAt: (factId) => this.#saidAt.get(factId)
43
+ },
44
+ text: this.#text,
45
+ entities: this.#entities
46
+ });
47
+ this.compilation = compileOrThrow(options.source, {
48
+ vocabulary: this.#vocabulary,
49
+ builtins
50
+ });
51
+ this.#engine = Engine.make({
52
+ program: this.compilation.program,
53
+ builtins,
54
+ relations: RELATIONS
55
+ });
56
+ this.#achieved = this.achieved;
57
+ }
58
+ get achieved() {
59
+ return this.#engine.has("achieved", ["goal"]);
60
+ }
61
+ get holds() {
62
+ return this.#engine.has("holds", ["goal"]);
63
+ }
64
+ /** Adds facts and sub-goal status at time `at`; returns the wakes and the goal's state. */
65
+ update({ at, facts = [], subgoals = {} }) {
66
+ this.#previous = this.#now;
67
+ this.#now = at;
68
+ const insert = [];
69
+ const retract = [];
70
+ for (const fact of facts) {
71
+ this.#saidAt.set(fact.id, Date.parse(fact.attribution.generatedAtTime));
72
+ this.#text.add(fact.id, factText(fact));
73
+ this.#entities.add(fact.id, this.#concerns(fact));
74
+ insert.push(...encode(fact, this.#vocabulary));
75
+ }
76
+ const wakes = [];
77
+ for (const [subgoal, status] of Object.entries(subgoals)) {
78
+ const previous = this.#subgoals.get(subgoal);
79
+ if (previous === status) continue;
80
+ if (previous === void 0) insert.push({
81
+ relation: "subgoal",
82
+ tuple: ["goal", subgoal]
83
+ });
84
+ else {
85
+ retract.push({
86
+ relation: "status",
87
+ tuple: [subgoal, previous]
88
+ });
89
+ wakes.push({
90
+ label: subgoal,
91
+ cause: "subgoal",
92
+ facts: []
93
+ });
94
+ }
95
+ insert.push({
96
+ relation: "status",
97
+ tuple: [subgoal, status]
98
+ });
99
+ this.#subgoals.set(subgoal, status);
100
+ }
101
+ const changes = this.#engine.update({
102
+ insert,
103
+ retract,
104
+ refresh: this.#now !== this.#previous
105
+ });
106
+ for (const [relation, label] of this.compilation.wakes) for (const tuple of changes.added.get(relation) ?? []) wakes.push({
107
+ label,
108
+ cause: "rule",
109
+ facts: factIds(this.#engine.provenance(relation, tuple))
110
+ });
111
+ const achieved = this.achieved;
112
+ if (achieved && !this.#achieved) wakes.push({
113
+ label: "achieved",
114
+ cause: "achieved",
115
+ facts: factIds(this.#engine.provenance("achieved", ["goal"]))
116
+ });
117
+ this.#achieved = achieved;
118
+ return {
119
+ at,
120
+ wakes,
121
+ achieved,
122
+ holds: this.holds
123
+ };
124
+ }
125
+ /** Evaluates the `blocks` rules for a proposed action without keeping it. */
126
+ checkAction(action) {
127
+ const entries = [{
128
+ relation: "action",
129
+ tuple: [action.id, action.kind]
130
+ }, ...Object.entries(action.args).map(([key, value]) => ({
131
+ relation: "actionArg",
132
+ tuple: [
133
+ action.id,
134
+ key,
135
+ value
136
+ ]
137
+ }))];
138
+ this.#engine.update({ insert: entries });
139
+ const tuple = [action.id];
140
+ const blocked = this.#engine.has("blocks", tuple);
141
+ const facts = blocked ? factIds(this.#engine.provenance("blocks", tuple)) : [];
142
+ this.#engine.update({ retract: entries });
143
+ return {
144
+ blocked,
145
+ facts
146
+ };
147
+ }
148
+ };
149
+ /** Creates a goal evaluator. */
150
+ var make = (options) => new GoalRules(options);
151
+ /** The text `about` matches: what was said plus the triple. */
152
+ var factText = ({ assertion }) => [
153
+ assertion.quote ?? "",
154
+ RDF.termValue(assertion.subject),
155
+ assertion.predicate,
156
+ RDF.termValue(assertion.object)
157
+ ].join(" ");
158
+ //#endregion
159
+ export { GoalRules, make, GoalRules_exports as t };
160
+
161
+ //# sourceMappingURL=GoalRules.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GoalRules.mjs","names":[],"sources":["../../src/GoalRules.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as Ast from '@dxos/datalog/Ast';\nimport * as Engine from '@dxos/datalog/Engine';\nimport { RDF } from '@dxos/pipeline-rdf';\n\nimport * as Builtins from './Builtins.ts';\nimport * as Compiler from './Compiler.ts';\nimport * as Encoding from './Encoding.ts';\nimport type * as Vocabulary from './Vocabulary.ts';\n\n/** A reason to run judgment on the goal. */\nexport type Wake = {\n /** The wake rule's label, `achieved`, or the sub-goal whose status changed. */\n readonly label: string;\n readonly cause: 'rule' | 'achieved' | 'subgoal';\n /** Ids of the facts the waking derivation rests on. */\n readonly facts: ReadonlyArray<string>;\n};\n\nexport type Evaluation = {\n readonly at: number;\n readonly wakes: ReadonlyArray<Wake>;\n readonly achieved: boolean;\n readonly holds: boolean;\n};\n\n/** An action the agent proposes, checked against the goal's `blocks` rules before it runs. */\nexport type Action = {\n readonly id: string;\n readonly kind: string;\n readonly args: Readonly<Record<string, string>>;\n};\n\nexport type ActionCheck = {\n readonly blocked: boolean;\n /** Ids of the facts that contributed to the block (empty when only the action did). */\n readonly facts: ReadonlyArray<string>;\n};\n\nexport type Options = {\n readonly source: string;\n /** When the goal was created (epoch ms); also the clock's starting time. */\n readonly createdAt: number;\n readonly vocabulary?: Vocabulary.Vocabulary;\n readonly text?: Builtins.TextIndex;\n readonly entities?: Builtins.EntityIndex;\n /** Entities a fact concerns; defaults to its subject. */\n readonly concerns?: (fact: RDF.Fact) => ReadonlyArray<string>;\n};\n\nexport type Input = {\n /** Evaluation time (epoch ms); a change re-evaluates time built-ins. */\n readonly at: number;\n readonly facts?: ReadonlyArray<RDF.Fact>;\n /** Current status of each sub-goal; a new id adds the sub-goal. */\n readonly subgoals?: Readonly<Record<string, string>>;\n};\n\n/**\n * Evaluates one goal's compiled rules over a growing fact stream and a clock. A goal wakes when a\n * wake rule gains a new binding, when `achieved` first becomes true, and when a sub-goal's status\n * changes.\n */\nexport class GoalRules {\n readonly compilation: Compiler.Compilation;\n readonly #engine: Engine.Engine;\n readonly #vocabulary: Vocabulary.Vocabulary;\n readonly #text: Builtins.TextIndex;\n readonly #entities: Builtins.EntityIndex;\n readonly #concerns: (fact: RDF.Fact) => ReadonlyArray<string>;\n readonly #saidAt = new Map<string, number>();\n readonly #subgoals = new Map<string, string>();\n #now: number;\n #previous: number;\n #achieved = false;\n\n /** @throws Compiler.CompileError if the rules do not compile. */\n constructor(options: Options) {\n this.#now = options.createdAt;\n this.#previous = options.createdAt;\n this.#vocabulary = options.vocabulary ?? Compiler.defaultVocabulary();\n this.#text = options.text ?? new Builtins.KeywordIndex();\n this.#entities = options.entities ?? new Builtins.MemoryEntityIndex();\n this.#concerns = options.concerns ?? ((fact) => [RDF.termValue(fact.assertion.subject)]);\n const builtins = Builtins.make({\n clock: {\n now: () => this.#now,\n previous: () => this.#previous,\n createdAt: options.createdAt,\n saidAt: (factId) => this.#saidAt.get(factId),\n },\n text: this.#text,\n entities: this.#entities,\n });\n this.compilation = Compiler.compileOrThrow(options.source, { vocabulary: this.#vocabulary, builtins });\n this.#engine = Engine.make({ program: this.compilation.program, builtins, relations: Compiler.RELATIONS });\n this.#achieved = this.achieved;\n }\n\n get achieved(): boolean {\n return this.#engine.has('achieved', ['goal']);\n }\n\n get holds(): boolean {\n return this.#engine.has('holds', ['goal']);\n }\n\n /** Adds facts and sub-goal status at time `at`; returns the wakes and the goal's state. */\n update({ at, facts = [], subgoals = {} }: Input): Evaluation {\n this.#previous = this.#now;\n this.#now = at;\n const insert: Engine.Entry[] = [];\n const retract: Engine.Entry[] = [];\n for (const fact of facts) {\n this.#saidAt.set(fact.id, Date.parse(fact.attribution.generatedAtTime));\n this.#text.add(fact.id, factText(fact));\n this.#entities.add(fact.id, this.#concerns(fact));\n insert.push(...Encoding.encode(fact, this.#vocabulary));\n }\n\n const wakes: Wake[] = [];\n for (const [subgoal, status] of Object.entries(subgoals)) {\n const previous = this.#subgoals.get(subgoal);\n if (previous === status) {\n continue;\n }\n if (previous === undefined) {\n insert.push({ relation: 'subgoal', tuple: ['goal', subgoal] });\n } else {\n retract.push({ relation: 'status', tuple: [subgoal, previous] });\n wakes.push({ label: subgoal, cause: 'subgoal', facts: [] });\n }\n insert.push({ relation: 'status', tuple: [subgoal, status] });\n this.#subgoals.set(subgoal, status);\n }\n\n const changes = this.#engine.update({ insert, retract, refresh: this.#now !== this.#previous });\n for (const [relation, label] of this.compilation.wakes) {\n for (const tuple of changes.added.get(relation) ?? []) {\n wakes.push({ label, cause: 'rule', facts: Encoding.factIds(this.#engine.provenance(relation, tuple)) });\n }\n }\n\n const achieved = this.achieved;\n if (achieved && !this.#achieved) {\n wakes.push({\n label: 'achieved',\n cause: 'achieved',\n facts: Encoding.factIds(this.#engine.provenance('achieved', ['goal'])),\n });\n }\n this.#achieved = achieved;\n return { at, wakes, achieved, holds: this.holds };\n }\n\n /** Evaluates the `blocks` rules for a proposed action without keeping it. */\n checkAction(action: Action): ActionCheck {\n const entries: Engine.Entry[] = [\n { relation: 'action', tuple: [action.id, action.kind] },\n ...Object.entries(action.args).map(([key, value]) => ({ relation: 'actionArg', tuple: [action.id, key, value] })),\n ];\n this.#engine.update({ insert: entries });\n const tuple: Ast.Tuple = [action.id];\n const blocked = this.#engine.has('blocks', tuple);\n const facts = blocked ? Encoding.factIds(this.#engine.provenance('blocks', tuple)) : [];\n this.#engine.update({ retract: entries });\n return { blocked, facts };\n }\n}\n\n/** Creates a goal evaluator. */\nexport const make = (options: Options): GoalRules => new GoalRules(options);\n\n/** The text `about` matches: what was said plus the triple. */\nconst factText = ({ assertion }: RDF.Fact): string =>\n [assertion.quote ?? '', RDF.termValue(assertion.subject), assertion.predicate, RDF.termValue(assertion.object)].join(' ');\n"],"mappings":";;;;;;;;;;;;;;;;AAoEA,IAAa,YAAb,MAAuB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA,0BAAmB,IAAI,IAAoB;CAC3C,4BAAqB,IAAI,IAAoB;CAC7C;CACA;CACA,YAAY;;CAGZ,YAAY,SAAkB;EAC5B,KAAK,OAAO,QAAQ;EACpB,KAAK,YAAY,QAAQ;EACzB,KAAK,cAAc,QAAQ,cAAc,kBAA2B;EACpE,KAAK,QAAQ,QAAQ,QAAQ,IAAI,aAAsB;EACvD,KAAK,YAAY,QAAQ,YAAY,IAAI,kBAA2B;EACpE,KAAK,YAAY,QAAQ,cAAc,SAAS,CAAC,IAAI,UAAU,KAAK,UAAU,OAAO,CAAC;EACtF,MAAM,WAAW,OAAc;GAC7B,OAAO;IACL,WAAW,KAAK;IAChB,gBAAgB,KAAK;IACrB,WAAW,QAAQ;IACnB,SAAS,WAAW,KAAK,QAAQ,IAAI,MAAM;GAC7C;GACA,MAAM,KAAK;GACX,UAAU,KAAK;EACjB,CAAC;EACD,KAAK,cAAc,eAAwB,QAAQ,QAAQ;GAAE,YAAY,KAAK;GAAa;EAAS,CAAC;EACrG,KAAK,UAAU,OAAO,KAAK;GAAE,SAAS,KAAK,YAAY;GAAS;GAAU,WAAW;EAAmB,CAAC;EACzG,KAAK,YAAY,KAAK;CACxB;CAEA,IAAI,WAAoB;EACtB,OAAO,KAAK,QAAQ,IAAI,YAAY,CAAC,MAAM,CAAC;CAC9C;CAEA,IAAI,QAAiB;EACnB,OAAO,KAAK,QAAQ,IAAI,SAAS,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