@dxos/brain 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/lib/Builtins.mjs +4 -2
  2. package/dist/lib/Builtins.mjs.map +1 -1
  3. package/dist/lib/Encoding.mjs +12 -2
  4. package/dist/lib/Encoding.mjs.map +1 -1
  5. package/dist/lib/Evaluator.mjs +144 -0
  6. package/dist/lib/Evaluator.mjs.map +1 -0
  7. package/dist/lib/GoalRules.mjs +62 -4
  8. package/dist/lib/GoalRules.mjs.map +1 -1
  9. package/dist/lib/Oracle.mjs +169 -0
  10. package/dist/lib/Oracle.mjs.map +1 -0
  11. package/dist/lib/index.mjs +3 -1
  12. package/dist/types/src/Builtins.d.ts +2 -0
  13. package/dist/types/src/Builtins.d.ts.map +1 -1
  14. package/dist/types/src/Encoding.d.ts +4 -0
  15. package/dist/types/src/Encoding.d.ts.map +1 -1
  16. package/dist/types/src/Evaluator.d.ts +77 -0
  17. package/dist/types/src/Evaluator.d.ts.map +1 -0
  18. package/dist/types/src/Evaluator.test.d.ts +2 -0
  19. package/dist/types/src/Evaluator.test.d.ts.map +1 -0
  20. package/dist/types/src/GoalRules.d.ts +6 -0
  21. package/dist/types/src/GoalRules.d.ts.map +1 -1
  22. package/dist/types/src/Oracle.d.ts +126 -0
  23. package/dist/types/src/Oracle.d.ts.map +1 -0
  24. package/dist/types/src/Oracle.test.d.ts +2 -0
  25. package/dist/types/src/Oracle.test.d.ts.map +1 -0
  26. package/dist/types/src/index.d.ts +2 -0
  27. package/dist/types/src/index.d.ts.map +1 -1
  28. package/dist/types/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +15 -5
  30. package/src/Builtins.ts +2 -1
  31. package/src/Encoding.test.ts +14 -0
  32. package/src/Encoding.ts +9 -0
  33. package/src/Evaluator.test.ts +158 -0
  34. package/src/Evaluator.ts +186 -0
  35. package/src/GoalRules.test.ts +8 -0
  36. package/src/GoalRules.ts +81 -4
  37. package/src/Oracle.test.ts +71 -0
  38. package/src/Oracle.ts +182 -0
  39. package/src/index.ts +2 -0
@@ -7,7 +7,8 @@ var Builtins_exports = /* @__PURE__ */ __exportAll({
7
7
  emptyContext: () => emptyContext,
8
8
  keywordMatch: () => keywordMatch,
9
9
  make: () => make,
10
- parseDuration: () => parseDuration
10
+ parseDuration: () => parseDuration,
11
+ parseTime: () => parseTime
11
12
  });
12
13
  var STOP_WORDS = /* @__PURE__ */ new Set([
13
14
  "the",
@@ -100,6 +101,7 @@ var WEEKDAYS = [
100
101
  "friday",
101
102
  "saturday"
102
103
  ];
104
+ /** Parses an epoch-ms number or an ISO timestamp. */
103
105
  var parseTime = (value) => {
104
106
  const time = typeof value === "number" ? value : Date.parse(value);
105
107
  return Number.isNaN(time) ? void 0 : time;
@@ -179,6 +181,6 @@ var emptyContext = () => ({
179
181
  entities: new MemoryEntityIndex()
180
182
  });
181
183
  //#endregion
182
- export { KeywordIndex, MemoryEntityIndex, emptyContext, keywordMatch, make, parseDuration, Builtins_exports as t };
184
+ export { KeywordIndex, MemoryEntityIndex, emptyContext, keywordMatch, make, parseDuration, parseTime, Builtins_exports as t };
183
185
 
184
186
  //# sourceMappingURL=Builtins.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Builtins.mjs","names":[],"sources":["../../src/Builtins.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Builtin from '@dxos/datalog/Builtin';\n\n/** Finds facts about a topic; a semantic index replaces the keyword one without touching rules. */\nexport interface TextIndex {\n add(factId: string, text: string): void;\n remove(factId: string): void;\n /** True if the fact is about `query`. */\n matches(factId: string, query: string): boolean;\n /** Every fact about `query`. */\n search(query: string): Iterable<string>;\n}\n\n/** The entities each fact concerns (entity resolution), for scoping possessive goals. */\nexport interface EntityIndex {\n add(factId: string, entities: ReadonlyArray<string>): void;\n remove(factId: string): void;\n concerns(factId: string): ReadonlyArray<string>;\n facts(entity: string): Iterable<string>;\n}\n\n/** What the time built-ins read; `previous` is the time of the evaluation before this one. */\nexport type Clock = {\n readonly now: () => number;\n readonly previous: () => number;\n /** When the goal was created; `elapsed(goal, …)` measures from it. */\n readonly createdAt: number;\n /** When a fact was said, for `elapsed(F, …)`. */\n readonly saidAt: (factId: string) => number | undefined;\n};\n\nexport type Context = {\n readonly clock: Clock;\n readonly text: TextIndex;\n readonly entities: EntityIndex;\n};\n\nconst STOP_WORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'of',\n 'to',\n 'on',\n 'in',\n 'for',\n 'and',\n 'or',\n 'with',\n 'about',\n 'is',\n 'my',\n 'me',\n 'this',\n 'that',\n 'at',\n 'by',\n 'it',\n]);\n\nconst stem = (word: string): string => {\n let stemmed = word.toLowerCase();\n if (stemmed.length > 4 && stemmed.endsWith('ing')) {\n stemmed = stemmed.slice(0, -3);\n } else if (stemmed.length > 3 && (stemmed.endsWith('ed') || stemmed.endsWith('es'))) {\n stemmed = stemmed.slice(0, -2);\n } else if (stemmed.length > 2 && stemmed.endsWith('s')) {\n stemmed = stemmed.slice(0, -1);\n }\n if (stemmed.length > 3 && stemmed.at(-1) === stemmed.at(-2)) {\n stemmed = stemmed.slice(0, -1);\n }\n return stemmed;\n};\n\nconst words = (text: string): string[] =>\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n\n/** True if every non-stop keyword of `query` (stemmed, prefix-tolerant) occurs in `text`. */\nexport const keywordMatch = (text: string, query: string): boolean => {\n const stems = new Set(words(text).map(stem));\n const keywords = words(query)\n .filter((word) => !STOP_WORDS.has(word))\n .map(stem);\n return (\n keywords.length > 0 &&\n keywords.every((keyword) =>\n [...stems].some(\n (candidate) =>\n candidate === keyword ||\n (keyword.length >= 4 && candidate.startsWith(keyword)) ||\n (candidate.length >= 4 && keyword.startsWith(candidate)),\n ),\n )\n );\n};\n\n/** Keyword stand-in for a semantic index. */\nexport class KeywordIndex implements TextIndex {\n readonly #texts = new Map<string, string>();\n\n add(factId: string, text: string): void {\n this.#texts.set(factId, text);\n }\n\n remove(factId: string): void {\n this.#texts.delete(factId);\n }\n\n matches(factId: string, query: string): boolean {\n return keywordMatch(this.#texts.get(factId) ?? '', query);\n }\n\n *search(query: string): Iterable<string> {\n for (const [factId, text] of this.#texts) {\n if (keywordMatch(text, query)) {\n yield factId;\n }\n }\n }\n}\n\n/** In-memory entity index. */\nexport class MemoryEntityIndex implements EntityIndex {\n readonly #byFact = new Map<string, ReadonlyArray<string>>();\n\n add(factId: string, entities: ReadonlyArray<string>): void {\n this.#byFact.set(factId, entities);\n }\n\n remove(factId: string): void {\n this.#byFact.delete(factId);\n }\n\n concerns(factId: string): ReadonlyArray<string> {\n return this.#byFact.get(factId) ?? [];\n }\n\n *facts(entity: string): Iterable<string> {\n for (const [factId, entities] of this.#byFact) {\n if (entities.includes(entity)) {\n yield factId;\n }\n }\n }\n}\n\nconst DURATION_UNITS: Record<string, number> = { s: 1e3, m: 6e4, h: 36e5, d: 864e5, w: 6048e5 };\n\n/** Parses `30s`, `5m`, `2h`, `2d`, `1w` (optionally ISO-prefixed `P`/`PT`) to milliseconds. */\nexport const parseDuration = (duration: string | number): number | undefined => {\n const match = /^P?T?(\\d+(?:\\.\\d+)?)\\s*([smhdw])$/i.exec(String(duration).trim());\n const unit = match ? DURATION_UNITS[match[2].toLowerCase()] : undefined;\n return match && unit !== undefined ? Number(match[1]) * unit : undefined;\n};\n\nconst WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\n\nconst parseTime = (value: string | number): number | undefined => {\n const time = typeof value === 'number' ? value : Date.parse(value);\n return Number.isNaN(time) ? undefined : time;\n};\n\n/**\n * The goal built-ins: `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`),\n * `elapsed(Ref, Duration)` (`Ref` is `goal`, a fact id or a time), `every(Duration)` (a period\n * boundary passed since the previous evaluation), `due(Time, Lead)`, `weekday(Time, Day)` and\n * `hour(Time, Hour)` (UTC).\n */\nexport const make = ({ clock, text, entities }: Context): Builtin.Registry => {\n const reference = (value: string | number): number | undefined =>\n value === 'goal' ? clock.createdAt : (clock.saidAt(String(value)) ?? parseTime(value));\n\n return Builtin.registry(\n Builtin.make({\n name: 'about',\n arity: 2,\n modes: ['fb'],\n evaluate: ([factId, query]) => {\n if (query === undefined) {\n return [];\n }\n if (factId === undefined) {\n return [...text.search(String(query))].map((id) => [id, query]);\n }\n return text.matches(String(factId), String(query)) ? [[factId, query]] : [];\n },\n }),\n Builtin.make({\n name: 'concerns',\n arity: 2,\n modes: ['fb'],\n evaluate: ([factId, entity]) => {\n if (entity === undefined) {\n return [];\n }\n if (factId === undefined) {\n return [...entities.facts(String(entity))].map((id) => [id, entity]);\n }\n return entities.concerns(String(factId)).includes(String(entity)) ? [[factId, entity]] : [];\n },\n }),\n Builtin.predicate(\n 'elapsed',\n 2,\n ([ref, duration]) => {\n const start = reference(ref);\n const length = parseDuration(duration);\n return start !== undefined && length !== undefined && clock.now() - start >= length;\n },\n { volatile: true },\n ),\n Builtin.predicate(\n 'every',\n 1,\n ([duration]) => {\n const period = parseDuration(duration);\n if (period === undefined || period <= 0) {\n return false;\n }\n const tick = (time: number) => Math.floor((time - clock.createdAt) / period);\n return tick(clock.now()) > tick(clock.previous());\n },\n { volatile: true },\n ),\n Builtin.predicate(\n 'due',\n 2,\n ([time, lead]) => {\n const deadline = parseTime(time);\n const length = parseDuration(lead);\n return deadline !== undefined && length !== undefined && clock.now() >= deadline - length;\n },\n { volatile: true },\n ),\n Builtin.make({\n name: 'weekday',\n arity: 2,\n modes: ['bf'],\n evaluate: ([time, day]) => {\n const parsed = time === undefined ? undefined : parseTime(time);\n if (time === undefined || parsed === undefined) {\n return [];\n }\n const weekday = WEEKDAYS[new Date(parsed).getUTCDay()];\n if (day === undefined) {\n return [[time, weekday]];\n }\n return String(day).toLowerCase() === weekday ? [[time, day]] : [];\n },\n }),\n Builtin.make({\n name: 'hour',\n arity: 2,\n modes: ['bf'],\n evaluate: ([time, hour]) => {\n const parsed = time === undefined ? undefined : parseTime(time);\n if (time === undefined || parsed === undefined) {\n return [];\n }\n const value = new Date(parsed).getUTCHours();\n if (hour === undefined) {\n return [[time, value]];\n }\n return Number(hour) === value ? [[time, hour]] : [];\n },\n }),\n );\n};\n\n/** A context with empty indexes and a frozen clock, for checking rules without evaluating them. */\nexport const emptyContext = (): Context => ({\n clock: { now: () => 0, previous: () => 0, createdAt: 0, saidAt: () => undefined },\n text: new KeywordIndex(),\n entities: new MemoryEntityIndex(),\n});\n"],"mappings":";;;;;;;;;;;AA0CA,IAAM,6BAAa,IAAI,IAAI;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,QAAQ,SAAyB;CACrC,IAAI,UAAU,KAAK,YAAY;CAC/B,IAAI,QAAQ,SAAS,KAAK,QAAQ,SAAS,KAAK,GAC9C,UAAU,QAAQ,MAAM,GAAG,EAAE;MACxB,IAAI,QAAQ,SAAS,MAAM,QAAQ,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI,IAC/E,UAAU,QAAQ,MAAM,GAAG,EAAE;MACxB,IAAI,QAAQ,SAAS,KAAK,QAAQ,SAAS,GAAG,GACnD,UAAU,QAAQ,MAAM,GAAG,EAAE;CAE/B,IAAI,QAAQ,SAAS,KAAK,QAAQ,GAAG,EAAE,MAAM,QAAQ,GAAG,EAAE,GACxD,UAAU,QAAQ,MAAM,GAAG,EAAE;CAE/B,OAAO;AACT;AAEA,IAAM,SAAS,SACb,KACG,YAAY,CAAA,CACZ,MAAM,YAAY,CAAA,CAClB,OAAO,OAAO;;AAGnB,IAAa,gBAAgB,MAAc,UAA2B;CACpE,MAAM,QAAQ,IAAI,IAAI,MAAM,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC;CAC3C,MAAM,WAAW,MAAM,KAAK,CAAA,CACzB,QAAQ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AAM,GAAG,CAAC,IAAI,CAAC;EAClE;CACF,CAAC,GACD,QAAQ,KAAK;EACX,MAAM;EACN,OAAO;EACP,OAAO,CAAC,IAAI;EACZ,WAAW,CAAC,MAAM,UAAU;GAC1B,MAAM,SAAS,SAAS,KAAA,IAAY,KAAA,IAAY,UAAU,IAAI;GAC9D,IAAI,SAAS,KAAA,KAAa,WAAW,KAAA,GACnC,OAAO,CAAC;GAEV,MAAM,QAAQ,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;GAC3C,IAAI,SAAS,KAAA,GACX,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC;GAEvB,OAAO,OAAO,IAAI,MAAM,QAAQ,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC;EACpD;CACF,CAAC,CACH;AACF;;AAGA,IAAa,sBAA+B;CAC1C,OAAO;EAAE,WAAW;EAAG,gBAAgB;EAAG,WAAW;EAAG,cAAc,KAAA;CAAU;CAChF,MAAM,IAAI,aAAa;CACvB,UAAU,IAAI,kBAAkB;AAClC"}
1
+ {"version":3,"file":"Builtins.mjs","names":[],"sources":["../../src/Builtins.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Builtin from '@dxos/datalog/Builtin';\n\n/** Finds facts about a topic; a semantic index replaces the keyword one without touching rules. */\nexport interface TextIndex {\n add(factId: string, text: string): void;\n remove(factId: string): void;\n /** True if the fact is about `query`. */\n matches(factId: string, query: string): boolean;\n /** Every fact about `query`. */\n search(query: string): Iterable<string>;\n}\n\n/** The entities each fact concerns (entity resolution), for scoping possessive goals. */\nexport interface EntityIndex {\n add(factId: string, entities: ReadonlyArray<string>): void;\n remove(factId: string): void;\n concerns(factId: string): ReadonlyArray<string>;\n facts(entity: string): Iterable<string>;\n}\n\n/** What the time built-ins read; `previous` is the time of the evaluation before this one. */\nexport type Clock = {\n readonly now: () => number;\n readonly previous: () => number;\n /** When the goal was created; `elapsed(goal, …)` measures from it. */\n readonly createdAt: number;\n /** When a fact was said, for `elapsed(F, …)`. */\n readonly saidAt: (factId: string) => number | undefined;\n};\n\nexport type Context = {\n readonly clock: Clock;\n readonly text: TextIndex;\n readonly entities: EntityIndex;\n};\n\nconst STOP_WORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'of',\n 'to',\n 'on',\n 'in',\n 'for',\n 'and',\n 'or',\n 'with',\n 'about',\n 'is',\n 'my',\n 'me',\n 'this',\n 'that',\n 'at',\n 'by',\n 'it',\n]);\n\nconst stem = (word: string): string => {\n let stemmed = word.toLowerCase();\n if (stemmed.length > 4 && stemmed.endsWith('ing')) {\n stemmed = stemmed.slice(0, -3);\n } else if (stemmed.length > 3 && (stemmed.endsWith('ed') || stemmed.endsWith('es'))) {\n stemmed = stemmed.slice(0, -2);\n } else if (stemmed.length > 2 && stemmed.endsWith('s')) {\n stemmed = stemmed.slice(0, -1);\n }\n if (stemmed.length > 3 && stemmed.at(-1) === stemmed.at(-2)) {\n stemmed = stemmed.slice(0, -1);\n }\n return stemmed;\n};\n\nconst words = (text: string): string[] =>\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n\n/** True if every non-stop keyword of `query` (stemmed, prefix-tolerant) occurs in `text`. */\nexport const keywordMatch = (text: string, query: string): boolean => {\n const stems = new Set(words(text).map(stem));\n const keywords = words(query)\n .filter((word) => !STOP_WORDS.has(word))\n .map(stem);\n return (\n keywords.length > 0 &&\n keywords.every((keyword) =>\n [...stems].some(\n (candidate) =>\n candidate === keyword ||\n (keyword.length >= 4 && candidate.startsWith(keyword)) ||\n (candidate.length >= 4 && keyword.startsWith(candidate)),\n ),\n )\n );\n};\n\n/** Keyword stand-in for a semantic index. */\nexport class KeywordIndex implements TextIndex {\n readonly #texts = new Map<string, string>();\n\n add(factId: string, text: string): void {\n this.#texts.set(factId, text);\n }\n\n remove(factId: string): void {\n this.#texts.delete(factId);\n }\n\n matches(factId: string, query: string): boolean {\n return keywordMatch(this.#texts.get(factId) ?? '', query);\n }\n\n *search(query: string): Iterable<string> {\n for (const [factId, text] of this.#texts) {\n if (keywordMatch(text, query)) {\n yield factId;\n }\n }\n }\n}\n\n/** In-memory entity index. */\nexport class MemoryEntityIndex implements EntityIndex {\n readonly #byFact = new Map<string, ReadonlyArray<string>>();\n\n add(factId: string, entities: ReadonlyArray<string>): void {\n this.#byFact.set(factId, entities);\n }\n\n remove(factId: string): void {\n this.#byFact.delete(factId);\n }\n\n concerns(factId: string): ReadonlyArray<string> {\n return this.#byFact.get(factId) ?? [];\n }\n\n *facts(entity: string): Iterable<string> {\n for (const [factId, entities] of this.#byFact) {\n if (entities.includes(entity)) {\n yield factId;\n }\n }\n }\n}\n\nconst DURATION_UNITS: Record<string, number> = { s: 1e3, m: 6e4, h: 36e5, d: 864e5, w: 6048e5 };\n\n/** Parses `30s`, `5m`, `2h`, `2d`, `1w` (optionally ISO-prefixed `P`/`PT`) to milliseconds. */\nexport const parseDuration = (duration: string | number): number | undefined => {\n const match = /^P?T?(\\d+(?:\\.\\d+)?)\\s*([smhdw])$/i.exec(String(duration).trim());\n const unit = match ? DURATION_UNITS[match[2].toLowerCase()] : undefined;\n return match && unit !== undefined ? Number(match[1]) * unit : undefined;\n};\n\nconst WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\n\n/** Parses an epoch-ms number or an ISO timestamp. */\nexport const parseTime = (value: string | number): number | undefined => {\n const time = typeof value === 'number' ? value : Date.parse(value);\n return Number.isNaN(time) ? undefined : time;\n};\n\n/**\n * The goal built-ins: `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`),\n * `elapsed(Ref, Duration)` (`Ref` is `goal`, a fact id or a time), `every(Duration)` (a period\n * boundary passed since the previous evaluation), `due(Time, Lead)`, `weekday(Time, Day)` and\n * `hour(Time, Hour)` (UTC).\n */\nexport const make = ({ clock, text, entities }: Context): Builtin.Registry => {\n const reference = (value: string | number): number | undefined =>\n value === 'goal' ? clock.createdAt : (clock.saidAt(String(value)) ?? parseTime(value));\n\n return Builtin.registry(\n Builtin.make({\n name: 'about',\n arity: 2,\n modes: ['fb'],\n evaluate: ([factId, query]) => {\n if (query === undefined) {\n return [];\n }\n if (factId === undefined) {\n return [...text.search(String(query))].map((id) => [id, query]);\n }\n return text.matches(String(factId), String(query)) ? [[factId, query]] : [];\n },\n }),\n Builtin.make({\n name: 'concerns',\n arity: 2,\n modes: ['fb'],\n evaluate: ([factId, entity]) => {\n if (entity === undefined) {\n return [];\n }\n if (factId === undefined) {\n return [...entities.facts(String(entity))].map((id) => [id, entity]);\n }\n return entities.concerns(String(factId)).includes(String(entity)) ? [[factId, entity]] : [];\n },\n }),\n Builtin.predicate(\n 'elapsed',\n 2,\n ([ref, duration]) => {\n const start = reference(ref);\n const length = parseDuration(duration);\n return start !== undefined && length !== undefined && clock.now() - start >= length;\n },\n { volatile: true },\n ),\n Builtin.predicate(\n 'every',\n 1,\n ([duration]) => {\n const period = parseDuration(duration);\n if (period === undefined || period <= 0) {\n return false;\n }\n const tick = (time: number) => Math.floor((time - clock.createdAt) / period);\n return tick(clock.now()) > tick(clock.previous());\n },\n { volatile: true },\n ),\n Builtin.predicate(\n 'due',\n 2,\n ([time, lead]) => {\n const deadline = parseTime(time);\n const length = parseDuration(lead);\n return deadline !== undefined && length !== undefined && clock.now() >= deadline - length;\n },\n { volatile: true },\n ),\n Builtin.make({\n name: 'weekday',\n arity: 2,\n modes: ['bf'],\n evaluate: ([time, day]) => {\n const parsed = time === undefined ? undefined : parseTime(time);\n if (time === undefined || parsed === undefined) {\n return [];\n }\n const weekday = WEEKDAYS[new Date(parsed).getUTCDay()];\n if (day === undefined) {\n return [[time, weekday]];\n }\n return String(day).toLowerCase() === weekday ? [[time, day]] : [];\n },\n }),\n Builtin.make({\n name: 'hour',\n arity: 2,\n modes: ['bf'],\n evaluate: ([time, hour]) => {\n const parsed = time === undefined ? undefined : parseTime(time);\n if (time === undefined || parsed === undefined) {\n return [];\n }\n const value = new Date(parsed).getUTCHours();\n if (hour === undefined) {\n return [[time, value]];\n }\n return Number(hour) === value ? [[time, hour]] : [];\n },\n }),\n );\n};\n\n/** A context with empty indexes and a frozen clock, for checking rules without evaluating them. */\nexport const emptyContext = (): Context => ({\n clock: { now: () => 0, previous: () => 0, createdAt: 0, saidAt: () => undefined },\n text: new KeywordIndex(),\n entities: new MemoryEntityIndex(),\n});\n"],"mappings":";;;;;;;;;;;;AA0CA,IAAM,6BAAa,IAAI,IAAI;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,QAAQ,SAAyB;CACrC,IAAI,UAAU,KAAK,YAAY;CAC/B,IAAI,QAAQ,SAAS,KAAK,QAAQ,SAAS,KAAK,GAC9C,UAAU,QAAQ,MAAM,GAAG,EAAE;MACxB,IAAI,QAAQ,SAAS,MAAM,QAAQ,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI,IAC/E,UAAU,QAAQ,MAAM,GAAG,EAAE;MACxB,IAAI,QAAQ,SAAS,KAAK,QAAQ,SAAS,GAAG,GACnD,UAAU,QAAQ,MAAM,GAAG,EAAE;CAE/B,IAAI,QAAQ,SAAS,KAAK,QAAQ,GAAG,EAAE,MAAM,QAAQ,GAAG,EAAE,GACxD,UAAU,QAAQ,MAAM,GAAG,EAAE;CAE/B,OAAO;AACT;AAEA,IAAM,SAAS,SACb,KACG,YAAY,CAAA,CACZ,MAAM,YAAY,CAAA,CAClB,OAAO,OAAO;;AAGnB,IAAa,gBAAgB,MAAc,UAA2B;CACpE,MAAM,QAAQ,IAAI,IAAI,MAAM,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC;CAC3C,MAAM,WAAW,MAAM,KAAK,CAAA,CACzB,QAAQ,SAAS,CAAC,WAAW,IAAI,IAAI,CAAC,CAAA,CACtC,IAAI,IAAI;CACX,OACE,SAAS,SAAS,KAClB,SAAS,OAAO,YACd,CA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EACZ,WAAW,CAAC,MAAM,UAAU;GAC1B,MAAM,SAAS,SAAS,KAAA,IAAY,KAAA,IAAY,UAAU,IAAI;GAC9D,IAAI,SAAS,KAAA,KAAa,WAAW,KAAA,GACnC,OAAO,CAAC;GAEV,MAAM,QAAQ,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;GAC3C,IAAI,SAAS,KAAA,GACX,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC;GAEvB,OAAO,OAAO,IAAI,MAAM,QAAQ,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC;EACpD;CACF,CAAC,CACH;AACF;;AAGA,IAAa,sBAA+B;CAC1C,OAAO;EAAE,WAAW;EAAG,gBAAgB;EAAG,WAAW;EAAG,cAAc,KAAA;CAAU;CAChF,MAAM,IAAI,aAAa;CACvB,UAAU,IAAI,kBAAkB;AAClC"}
@@ -1,4 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import * as Ast from "@dxos/datalog/Ast";
2
3
  import { RDF } from "@dxos/pipeline-rdf";
3
4
  //#region src/Encoding.ts
4
5
  var Encoding_exports = /* @__PURE__ */ __exportAll({
@@ -6,7 +7,9 @@ var Encoding_exports = /* @__PURE__ */ __exportAll({
6
7
  GOAL_RELATIONS: () => GOAL_RELATIONS,
7
8
  RELATIONS: () => RELATIONS,
8
9
  encode: () => encode,
9
- factIds: () => factIds
10
+ factIds: () => factIds,
11
+ format: () => format,
12
+ formatEntry: () => formatEntry
10
13
  });
11
14
  /** Relations every fact contributes to, keyed by the fact id `F`. */
12
15
  var FACT_RELATIONS = {
@@ -110,7 +113,14 @@ var encode = (fact, vocabulary) => {
110
113
  };
111
114
  /** The fact ids among base entries (from provenance). */
112
115
  var factIds = (entries) => [...new Set(entries.flatMap(({ relation, tuple }) => relation in FACT_RELATIONS && typeof tuple[0] === "string" ? [tuple[0]] : []))];
116
+ /** An entry as a ground Datalog fact in the dialect goal rules are written in, e.g. `speaker("fact-1", dima).`. */
117
+ var formatEntry = ({ relation, tuple }) => Ast.formatRule({
118
+ head: Ast.atom(relation, tuple.map(Ast.constant)),
119
+ body: []
120
+ });
121
+ /** The relations the rules engine sees for a fact ({@link encode}), one ground Datalog fact per line. */
122
+ var format = (fact, vocabulary) => encode(fact, vocabulary).map(formatEntry);
113
123
  //#endregion
114
- export { FACT_RELATIONS, GOAL_RELATIONS, RELATIONS, encode, factIds, Encoding_exports as t };
124
+ export { FACT_RELATIONS, GOAL_RELATIONS, RELATIONS, encode, factIds, format, formatEntry, Encoding_exports as t };
115
125
 
116
126
  //# sourceMappingURL=Encoding.mjs.map
@@ -1 +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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AAI,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"}
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 * as Ast from '@dxos/datalog/Ast';\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\n/** An entry as a ground Datalog fact in the dialect goal rules are written in, e.g. `speaker(\"fact-1\", dima).`. */\nexport const formatEntry = ({ relation, tuple }: Engine.Entry): string =>\n Ast.formatRule({ head: Ast.atom(relation, tuple.map(Ast.constant)), body: [] });\n\n/** The relations the rules engine sees for a fact ({@link encode}), one ground Datalog fact per line. */\nexport const format = (fact: RDF.Fact, vocabulary?: Vocabulary.Vocabulary): string[] =>\n encode(fact, vocabulary).map(formatEntry);\n"],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,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;;AAGA,IAAa,eAAe,EAAE,UAAU,YACtC,IAAI,WAAW;CAAE,MAAM,IAAI,KAAK,UAAU,MAAM,IAAI,IAAI,QAAQ,CAAC;CAAG,MAAM,CAAC;AAAE,CAAC;;AAGhF,IAAa,UAAU,MAAgB,eACrC,OAAO,MAAM,UAAU,CAAC,CAAC,IAAI,WAAW"}
@@ -0,0 +1,144 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { MAX_FACTS, make as make$1 } from "./GoalRules.mjs";
3
+ //#region src/Evaluator.ts
4
+ var Evaluator_exports = /* @__PURE__ */ __exportAll({
5
+ Evaluator: () => Evaluator,
6
+ eventId: () => eventId,
7
+ make: () => make
8
+ });
9
+ /** The id of an event: see {@link Event.id}. */
10
+ var eventId = (subscription, label, facts, at) => facts.length > 0 ? `${subscription}:${label}:${[...facts].sort().join(",")}` : `${subscription}:${label}@${at}`;
11
+ /**
12
+ * Evaluates every subscription of one brain over a shared fact stream. Synchronous and in memory: a
13
+ * host keeps the facts and the outboxes in its own store, feeds pushes and clock ticks through
14
+ * {@link Evaluator.push} and {@link Evaluator.tick}, and after a restart rebuilds the evaluator with
15
+ * {@link Evaluator.hydrate}, which re-derives the rules' state without emitting events.
16
+ */
17
+ var Evaluator = class {
18
+ #goals = /* @__PURE__ */ new Map();
19
+ /** Recent facts, which seed a subscription added later and resolve the facts behind a wake. */
20
+ #facts = /* @__PURE__ */ new Map();
21
+ #maxFacts;
22
+ #at = 0;
23
+ constructor({ maxFacts = MAX_FACTS } = {}) {
24
+ this.#maxFacts = maxFacts;
25
+ }
26
+ /** The subscriptions, in the order they were added. */
27
+ get subscriptions() {
28
+ return [...this.#goals.values()].map(({ subscription }) => subscription);
29
+ }
30
+ has(id) {
31
+ return this.#goals.has(id);
32
+ }
33
+ /**
34
+ * Adds or replaces a subscription. It sees the facts already held (said before it began, so its
35
+ * rules can read history) without waking on them.
36
+ * @throws Compiler.CompileError if the rules do not compile; nothing is changed.
37
+ */
38
+ add(subscription) {
39
+ const rules = makeRules(subscription);
40
+ if (this.#facts.size > 0) rules.update({
41
+ at: Math.max(this.#at, startOf(subscription)),
42
+ facts: [...this.#facts.values()]
43
+ });
44
+ this.#goals.set(subscription.id, {
45
+ subscription,
46
+ rules
47
+ });
48
+ }
49
+ /** Removes a subscription; false when it was not held. */
50
+ remove(id) {
51
+ return this.#goals.delete(id);
52
+ }
53
+ /** Evaluates new facts at time `at`; returns the wakes, one event each. */
54
+ push(facts, { at, quiet = [] }) {
55
+ const quietIds = new Set(facts.filter(({ attribution }) => attribution.agent !== void 0 && quiet.includes(attribution.agent)).map(({ id }) => id));
56
+ this.#remember(facts);
57
+ return this.#evaluate({
58
+ at,
59
+ facts
60
+ }, quietIds);
61
+ }
62
+ /** Re-evaluates the clock at time `at` (a scheduled tick); returns the wakes. */
63
+ tick(at) {
64
+ return this.#evaluate({ at }, /* @__PURE__ */ new Set());
65
+ }
66
+ /**
67
+ * Rebuilds state after a restart: adds the subscriptions and replays the facts as of `at` (the last
68
+ * evaluation before the restart), emitting nothing. Wakes due since then come from the next
69
+ * {@link tick} or {@link push}.
70
+ * @throws Compiler.CompileError if a subscription's rules do not compile.
71
+ */
72
+ hydrate(subscriptions, facts, at) {
73
+ this.#goals.clear();
74
+ this.#facts.clear();
75
+ this.#remember(facts);
76
+ this.#at = at;
77
+ for (const subscription of subscriptions) {
78
+ const rules = makeRules(subscription);
79
+ rules.update({
80
+ at: Math.max(at, startOf(subscription)),
81
+ facts: [...this.#facts.values()]
82
+ });
83
+ this.#goals.set(subscription.id, {
84
+ subscription,
85
+ rules
86
+ });
87
+ }
88
+ }
89
+ /** The earliest time any subscription's clock can next change; see `GoalRules.nextDueAt`. */
90
+ nextDueAt() {
91
+ const due = [...this.#goals.values()].map(({ rules }) => rules.nextDueAt()).filter((time) => time !== void 0);
92
+ return due.length === 0 ? void 0 : Math.min(...due);
93
+ }
94
+ #evaluate(input, quiet) {
95
+ this.#at = Math.max(this.#at, input.at);
96
+ const events = [];
97
+ for (const { subscription, rules } of this.#goals.values()) {
98
+ const { wakes } = rules.update({
99
+ at: input.at,
100
+ facts: input.facts
101
+ });
102
+ for (const wake of wakes) {
103
+ if (wake.facts.length > 0 && wake.facts.every((id) => quiet.has(id))) continue;
104
+ events.push({
105
+ id: eventId(subscription.id, wake.label, wake.facts, input.at),
106
+ subscription: subscription.id,
107
+ label: wake.label,
108
+ cause: wake.cause,
109
+ facts: wake.facts.flatMap((id) => {
110
+ const fact = this.#facts.get(id);
111
+ return fact ? [fact] : [];
112
+ }),
113
+ at: input.at
114
+ });
115
+ }
116
+ }
117
+ return events;
118
+ }
119
+ /** Keeps the newest facts, at most `maxFacts`, in arrival order. */
120
+ #remember(facts) {
121
+ for (const fact of facts) {
122
+ this.#facts.delete(fact.id);
123
+ this.#facts.set(fact.id, fact);
124
+ }
125
+ for (const id of this.#facts.keys()) {
126
+ if (this.#facts.size <= this.#maxFacts) break;
127
+ this.#facts.delete(id);
128
+ }
129
+ }
130
+ };
131
+ var startOf = ({ createdAt }) => {
132
+ const time = Date.parse(createdAt);
133
+ return Number.isNaN(time) ? 0 : time;
134
+ };
135
+ var makeRules = (subscription) => make$1({
136
+ source: subscription.rules,
137
+ createdAt: startOf(subscription)
138
+ });
139
+ /** Creates an evaluator. */
140
+ var make = (options) => new Evaluator(options);
141
+ //#endregion
142
+ export { Evaluator, eventId, make, Evaluator_exports as t };
143
+
144
+ //# sourceMappingURL=Evaluator.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Evaluator.mjs","names":[],"sources":["../../src/Evaluator.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { type RDF } from '@dxos/pipeline-rdf';\n\nimport * as GoalRules from './GoalRules.ts';\n\n/** A standing goal the evaluator watches: its compiled rules and when it began. */\nexport type Subscription = {\n readonly id: string;\n /** A goal program (`wake`, `achieved`, `holds`, `blocks`); see `Compiler`. */\n readonly rules: string;\n /** ISO time the subscription began; the rules' clock starts here. */\n readonly createdAt: string;\n};\n\n/** A wake of one subscription, ready to queue in its outbox. */\nexport type Event = {\n /**\n * Stable for the same wake: the subscription, the wake label and the facts behind it (or, for a\n * wake no fact caused, the evaluation time), so a host that re-derives a wake queues it once.\n */\n readonly id: string;\n readonly subscription: string;\n readonly label: string;\n readonly cause: GoalRules.Wake['cause'];\n /** The facts behind the wake, in the order they arrived. */\n readonly facts: ReadonlyArray<RDF.Fact>;\n /** Evaluation time (epoch ms). */\n readonly at: number;\n};\n\nexport type PushOptions = {\n /** Evaluation time (epoch ms). */\n readonly at: number;\n /**\n * Speakers (entity ids) whose facts are evaluated but wake nothing on their own: an agent's own\n * words must not wake it. A wake resting on a quiet fact and another one still wakes.\n */\n readonly quiet?: ReadonlyArray<string>;\n};\n\n/** The id of an event: see {@link Event.id}. */\nexport const eventId = (subscription: string, label: string, facts: ReadonlyArray<string>, at: number): string =>\n facts.length > 0 ? `${subscription}:${label}:${[...facts].sort().join(',')}` : `${subscription}:${label}@${at}`;\n\n/**\n * Evaluates every subscription of one brain over a shared fact stream. Synchronous and in memory: a\n * host keeps the facts and the outboxes in its own store, feeds pushes and clock ticks through\n * {@link Evaluator.push} and {@link Evaluator.tick}, and after a restart rebuilds the evaluator with\n * {@link Evaluator.hydrate}, which re-derives the rules' state without emitting events.\n */\nexport class Evaluator {\n readonly #goals = new Map<string, { subscription: Subscription; rules: GoalRules.GoalRules }>();\n /** Recent facts, which seed a subscription added later and resolve the facts behind a wake. */\n readonly #facts = new Map<string, RDF.Fact>();\n readonly #maxFacts: number;\n #at = 0;\n\n constructor({ maxFacts = GoalRules.MAX_FACTS }: { maxFacts?: number } = {}) {\n this.#maxFacts = maxFacts;\n }\n\n /** The subscriptions, in the order they were added. */\n get subscriptions(): Subscription[] {\n return [...this.#goals.values()].map(({ subscription }) => subscription);\n }\n\n has(id: string): boolean {\n return this.#goals.has(id);\n }\n\n /**\n * Adds or replaces a subscription. It sees the facts already held (said before it began, so its\n * rules can read history) without waking on them.\n * @throws Compiler.CompileError if the rules do not compile; nothing is changed.\n */\n add(subscription: Subscription): void {\n const rules = makeRules(subscription);\n if (this.#facts.size > 0) {\n // Wakes on facts said before the subscription existed are discarded: it watches from now on.\n rules.update({ at: Math.max(this.#at, startOf(subscription)), facts: [...this.#facts.values()] });\n }\n this.#goals.set(subscription.id, { subscription, rules });\n }\n\n /** Removes a subscription; false when it was not held. */\n remove(id: string): boolean {\n return this.#goals.delete(id);\n }\n\n /** Evaluates new facts at time `at`; returns the wakes, one event each. */\n push(facts: ReadonlyArray<RDF.Fact>, { at, quiet = [] }: PushOptions): Event[] {\n const quietIds = new Set(\n facts\n .filter(({ attribution }) => attribution.agent !== undefined && quiet.includes(attribution.agent))\n .map(({ id }) => id),\n );\n this.#remember(facts);\n return this.#evaluate({ at, facts }, quietIds);\n }\n\n /** Re-evaluates the clock at time `at` (a scheduled tick); returns the wakes. */\n tick(at: number): Event[] {\n return this.#evaluate({ at }, new Set());\n }\n\n /**\n * Rebuilds state after a restart: adds the subscriptions and replays the facts as of `at` (the last\n * evaluation before the restart), emitting nothing. Wakes due since then come from the next\n * {@link tick} or {@link push}.\n * @throws Compiler.CompileError if a subscription's rules do not compile.\n */\n hydrate(subscriptions: ReadonlyArray<Subscription>, facts: ReadonlyArray<RDF.Fact>, at: number): void {\n this.#goals.clear();\n this.#facts.clear();\n this.#remember(facts);\n this.#at = at;\n for (const subscription of subscriptions) {\n const rules = makeRules(subscription);\n rules.update({ at: Math.max(at, startOf(subscription)), facts: [...this.#facts.values()] });\n this.#goals.set(subscription.id, { subscription, rules });\n }\n }\n\n /** The earliest time any subscription's clock can next change; see `GoalRules.nextDueAt`. */\n nextDueAt(): number | undefined {\n const due = [...this.#goals.values()]\n .map(({ rules }) => rules.nextDueAt())\n .filter((time): time is number => time !== undefined);\n return due.length === 0 ? undefined : Math.min(...due);\n }\n\n #evaluate(input: { at: number; facts?: ReadonlyArray<RDF.Fact> }, quiet: ReadonlySet<string>): Event[] {\n this.#at = Math.max(this.#at, input.at);\n const events: Event[] = [];\n for (const { subscription, rules } of this.#goals.values()) {\n const { wakes } = rules.update({ at: input.at, facts: input.facts });\n for (const wake of wakes) {\n if (wake.facts.length > 0 && wake.facts.every((id) => quiet.has(id))) {\n continue;\n }\n events.push({\n id: eventId(subscription.id, wake.label, wake.facts, input.at),\n subscription: subscription.id,\n label: wake.label,\n cause: wake.cause,\n facts: wake.facts.flatMap((id) => {\n const fact = this.#facts.get(id);\n return fact ? [fact] : [];\n }),\n at: input.at,\n });\n }\n }\n return events;\n }\n\n /** Keeps the newest facts, at most `maxFacts`, in arrival order. */\n #remember(facts: ReadonlyArray<RDF.Fact>): void {\n for (const fact of facts) {\n this.#facts.delete(fact.id);\n this.#facts.set(fact.id, fact);\n }\n for (const id of this.#facts.keys()) {\n if (this.#facts.size <= this.#maxFacts) {\n break;\n }\n this.#facts.delete(id);\n }\n }\n}\n\nconst startOf = ({ createdAt }: Subscription): number => {\n const time = Date.parse(createdAt);\n return Number.isNaN(time) ? 0 : time;\n};\n\nconst makeRules = (subscription: Subscription): GoalRules.GoalRules =>\n GoalRules.make({ source: subscription.rules, createdAt: startOf(subscription) });\n\n/** Creates an evaluator. */\nexport const make = (options?: { maxFacts?: number }): Evaluator => new Evaluator(options);\n"],"mappings":";;;;;;;;;AA8CA,IAAa,WAAW,cAAsB,OAAe,OAA8B,OACzF,MAAM,SAAS,IAAI,GAAG,aAAa,GAAG,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,MAAM,GAAG,aAAa,GAAG,MAAM,GAAG;;;;;;;AAQ7G,IAAa,YAAb,MAAuB;CACrB,yBAAkB,IAAI,IAAwE;;CAE9F,yBAAkB,IAAI,IAAsB;CAC5C;CACA,MAAM;CAEN,YAAY,EAAE,WAAW,cAA+C,CAAC,GAAG;EAC1E,KAAK,YAAY;CACnB;;CAGA,IAAI,gBAAgC;EAClC,OAAO,CAAC,GAAG,KAAK,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,mBAAmB,YAAY;CACzE;CAEA,IAAI,IAAqB;EACvB,OAAO,KAAK,OAAO,IAAI,EAAE;CAC3B;;;;;;CAOA,IAAI,cAAkC;EACpC,MAAM,QAAQ,UAAU,YAAY;EACpC,IAAI,KAAK,OAAO,OAAO,GAErB,MAAM,OAAO;GAAE,IAAI,KAAK,IAAI,KAAK,KAAK,QAAQ,YAAY,CAAC;GAAG,OAAO,CAAC,GAAG,KAAK,OAAO,OAAO,CAAC;EAAE,CAAC;EAElG,KAAK,OAAO,IAAI,aAAa,IAAI;GAAE;GAAc;EAAM,CAAC;CAC1D;;CAGA,OAAO,IAAqB;EAC1B,OAAO,KAAK,OAAO,OAAO,EAAE;CAC9B;;CAGA,KAAK,OAAgC,EAAE,IAAI,QAAQ,CAAC,KAA2B;EAC7E,MAAM,WAAW,IAAI,IACnB,MACG,QAAQ,EAAE,kBAAkB,YAAY,UAAU,KAAA,KAAa,MAAM,SAAS,YAAY,KAAK,CAAC,CAAA,CAChG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AAI,QAAQ,aAAa,IAAI,KAAK,OAAO,KAAK,OAAO,MAAM,EAAE;KAC7D,cAAc,aAAa;KAC3B,OAAO,KAAK;KACZ,OAAO,KAAK;KACZ,OAAO,KAAK,MAAM,SAAS,OAAO;MAChC,MAAM,OAAO,KAAK,OAAO,IAAI,EAAE;MAC/B,OAAO,OAAO,CAAC,IAAI,IAAI,CAAC;KAC1B,CAAC;KACD,IAAI,MAAM;IACZ,CAAC;GACH;EACF;EACA,OAAO;CACT;;CAGA,UAAU,OAAsC;EAC9C,KAAK,MAAM,QAAQ,OAAO;GACxB,KAAK,OAAO,OAAO,KAAK,EAAE;GAC1B,KAAK,OAAO,IAAI,KAAK,IAAI,IAAI;EAC/B;EACA,KAAK,MAAM,MAAM,KAAK,OAAO,KAAK,GAAG;GACnC,IAAI,KAAK,OAAO,QAAQ,KAAK,WAC3B;GAEF,KAAK,OAAO,OAAO,EAAE;EACvB;CACF;AACF;AAEA,IAAM,WAAW,EAAE,gBAAsC;CACvD,MAAM,OAAO,KAAK,MAAM,SAAS;CACjC,OAAO,OAAO,MAAM,IAAI,IAAI,IAAI;AAClC;AAEA,IAAM,aAAa,iBACjB,OAAe;CAAE,QAAQ,aAAa;CAAO,WAAW,QAAQ,YAAY;AAAE,CAAC;;AAGjF,IAAa,QAAQ,YAA+C,IAAI,UAAU,OAAO"}
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { KeywordIndex, MemoryEntityIndex, make as make$1 } from "./Builtins.mjs";
2
+ import { KeywordIndex, MemoryEntityIndex, make as make$1, parseDuration, parseTime } from "./Builtins.mjs";
3
3
  import { encode, factIds } from "./Encoding.mjs";
4
4
  import { RELATIONS, compileOrThrow, defaultVocabulary } from "./Compiler.mjs";
5
5
  import { BaseError } from "@dxos/errors";
@@ -46,12 +46,14 @@ var GoalRules = class {
46
46
  #subgoals = /* @__PURE__ */ new Map();
47
47
  #maxFacts;
48
48
  #maxSubgoals;
49
+ #createdAt;
49
50
  #now;
50
51
  #previous;
51
52
  #achieved = false;
52
53
  #sequence = 0;
53
54
  /** @throws Compiler.CompileError if the rules do not compile. */
54
55
  constructor(options) {
56
+ this.#createdAt = options.createdAt;
55
57
  this.#now = options.createdAt;
56
58
  this.#previous = options.createdAt;
57
59
  this.#maxFacts = options.maxFacts ?? 1e4;
@@ -146,10 +148,17 @@ var GoalRules = class {
146
148
  });
147
149
  this.#subgoals.set(subgoal, status);
148
150
  }
151
+ const refresh = this.#now !== this.#previous;
152
+ if (refresh) {
153
+ const now = this.#now;
154
+ this.#now = this.#previous;
155
+ this.#engine.update({ refresh: true });
156
+ this.#now = now;
157
+ }
149
158
  const changes = this.#engine.update({
150
159
  insert,
151
160
  retract,
152
- refresh: this.#now !== this.#previous
161
+ refresh
153
162
  });
154
163
  for (const [relation, label] of this.compilation.wakes) for (const tuple of changes.added.get(relation) ?? []) wakes.push({
155
164
  label,
@@ -204,6 +213,53 @@ var GoalRules = class {
204
213
  }
205
214
  return retired;
206
215
  }
216
+ /**
217
+ * The earliest time after the last evaluation at which a time built-in can change its answer
218
+ * (`elapsed`, `every`, `due`), so a host schedules its next {@link update} rather than polling;
219
+ * `undefined` when the rules read no clock.
220
+ */
221
+ nextDueAt() {
222
+ const candidates = [];
223
+ const after = (time) => {
224
+ if (time !== void 0 && time > this.#now) candidates.push(time);
225
+ };
226
+ const constant = (term) => term?.type === "constant" ? term.value : void 0;
227
+ const visit = (literal) => {
228
+ if (literal.type === "aggregate") {
229
+ literal.body.forEach(visit);
230
+ return;
231
+ }
232
+ if (literal.type !== "atom") return;
233
+ const [first, second] = literal.atom.terms;
234
+ switch (literal.atom.predicate) {
235
+ case "elapsed": {
236
+ const length = parseDuration(constant(second) ?? "");
237
+ if (length === void 0) return;
238
+ const ref = constant(first);
239
+ if (ref === void 0) for (const { saidAt } of this.#facts.values()) after(saidAt + length);
240
+ else if (ref === "goal") after(this.#createdAt + length);
241
+ else {
242
+ const start = this.#facts.get(String(ref))?.saidAt ?? parseTime(ref);
243
+ after(start === void 0 ? void 0 : start + length);
244
+ }
245
+ return;
246
+ }
247
+ case "every": {
248
+ const period = parseDuration(constant(first) ?? "");
249
+ if (period !== void 0 && period > 0) after(this.#createdAt + (Math.floor((this.#now - this.#createdAt) / period) + 1) * period);
250
+ return;
251
+ }
252
+ case "due": {
253
+ const deadline = parseTime(constant(first) ?? "");
254
+ const lead = parseDuration(constant(second) ?? "");
255
+ after(deadline === void 0 || lead === void 0 ? void 0 : deadline - lead);
256
+ return;
257
+ }
258
+ }
259
+ };
260
+ for (const rule of this.compilation.program.rules) rule.body.forEach(visit);
261
+ return candidates.length === 0 ? void 0 : Math.min(...candidates);
262
+ }
207
263
  /** Evaluates the `blocks` rules for a proposed action without keeping it. */
208
264
  checkAction(action) {
209
265
  const entries = [{
@@ -232,12 +288,14 @@ var GoalRules = class {
232
288
  var age = (saidAt) => Number.isNaN(saidAt) ? Number.NEGATIVE_INFINITY : saidAt;
233
289
  /** Creates a goal evaluator. */
234
290
  var make = (options) => new GoalRules(options);
291
+ /** A term's id and, for an entity known by an opaque id (a DID), its label, so `about` matches the name. */
292
+ var termText = (term) => term.kind === "entity" && term.label !== void 0 ? `${term.entity} ${term.label}` : RDF.termValue(term);
235
293
  /** The text `about` matches: what was said plus the triple. */
236
294
  var factText = ({ assertion }) => [
237
295
  assertion.quote ?? "",
238
- RDF.termValue(assertion.subject),
296
+ termText(assertion.subject),
239
297
  assertion.predicate,
240
- RDF.termValue(assertion.object)
298
+ termText(assertion.object)
241
299
  ].join(" ");
242
300
  //#endregion
243
301
  export { CapacityError, GoalRules, MAX_FACTS, MAX_SUBGOALS, make, GoalRules_exports as t };
@@ -1 +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 { BaseError } from '@dxos/errors';\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/**\n * Size of the evaluator's working memory: past it the oldest facts retire, so a goal that runs\n * indefinitely keeps a bounded engine, text and entity index (and bounded queries over them).\n */\nexport const MAX_FACTS = 10_000;\n\n/** Most sub-goals one evaluator tracks; sub-goals are structural, so exceeding it is an error. */\nexport const MAX_SUBGOALS = 256;\n\n/** Thrown by `GoalRules.update` when an input would take the evaluator past {@link MAX_SUBGOALS}. */\nexport class CapacityError extends BaseError.extend('CapacityError', 'Goal evaluator capacity exceeded') {\n constructor(context: { readonly max: number; readonly requested: number }) {\n super({ message: `Goal evaluator would hold ${context.requested} sub-goals; the cap is ${context.max}.`, context });\n }\n}\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 * Working-memory size; defaults to {@link MAX_FACTS}. Each `update` first retires facts whose\n * `assertion.validTo` is before the clock, then the oldest (by `generatedAtTime`, then arrival)\n * until at most `maxFacts` remain. Retiring drops a fact from the evaluator only; the feed and any\n * external index keep it, and a re-sent fact with a retired id is admitted again as new.\n * Retirement never wakes the goal, and the facts behind the current `achieved` derivation are\n * never retired, so a goal stays achieved once it is; `holds` and wake bindings may lapse as\n * their facts retire, and a lapsed binding wakes again when new facts restore it.\n */\n readonly maxFacts?: number;\n /** Overrides {@link MAX_SUBGOALS}. */\n readonly maxSubgoals?: number;\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 /** Working memory in arrival order. */\n readonly #facts = new Map<string, Admitted>();\n readonly #subgoals = new Map<string, string>();\n readonly #maxFacts: number;\n readonly #maxSubgoals: number;\n #now: number;\n #previous: number;\n #achieved = false;\n #sequence = 0;\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.#maxFacts = options.maxFacts ?? MAX_FACTS;\n this.#maxSubgoals = options.maxSubgoals ?? MAX_SUBGOALS;\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.#facts.get(factId)?.saidAt,\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 /**\n * Adds facts and sub-goal status at time `at`, retiring facts past the working-memory window\n * (see {@link Options.maxFacts}); returns the wakes and the goal's state.\n * @throws CapacityError if the input would exceed the sub-goal cap; nothing is applied.\n */\n update({ at, facts = [], subgoals = {} }: Input): Evaluation {\n this.#checkSubgoals(subgoals);\n this.#previous = this.#now;\n this.#now = at;\n\n const arrived = new Map<string, { fact: RDF.Fact; admitted: Admitted }>();\n for (const fact of facts) {\n if (!this.#facts.has(fact.id) && !arrived.has(fact.id)) {\n arrived.set(fact.id, { fact, admitted: this.#admit(fact) });\n }\n }\n const retired = this.#retire([...arrived.values()].map(({ admitted }) => admitted));\n const retiring: Engine.Entry[] = [];\n for (const id of retired) {\n const admitted = this.#facts.get(id);\n if (admitted) {\n retiring.push(...admitted.entries);\n this.#facts.delete(id);\n this.#text.remove(id);\n this.#entities.remove(id);\n }\n }\n if (retiring.length > 0) {\n // A separate pass whose changes are discarded, so retirement never wakes the goal.\n this.#engine.update({ retract: retiring });\n }\n\n const insert: Engine.Entry[] = [];\n const retract: Engine.Entry[] = [];\n for (const { fact, admitted } of arrived.values()) {\n if (!retired.has(fact.id)) {\n this.#facts.set(fact.id, admitted);\n this.#text.add(fact.id, factText(fact));\n this.#entities.add(fact.id, this.#concerns(fact));\n insert.push(...admitted.entries);\n }\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 #checkSubgoals(subgoals: Readonly<Record<string, string>>): void {\n const requested = this.#subgoals.size + Object.keys(subgoals).filter((id) => !this.#subgoals.has(id)).length;\n if (requested > this.#maxSubgoals) {\n throw new CapacityError({ max: this.#maxSubgoals, requested });\n }\n }\n\n #admit(fact: RDF.Fact): Admitted {\n const validTo = fact.assertion.validTo === undefined ? undefined : Date.parse(fact.assertion.validTo);\n return {\n id: fact.id,\n sequence: this.#sequence++,\n saidAt: Date.parse(fact.attribution.generatedAtTime),\n validTo: validTo === undefined || Number.isNaN(validTo) ? undefined : validTo,\n entries: Encoding.encode(fact, this.#vocabulary),\n };\n }\n\n /** Ids to retire from working memory plus the arriving facts: expired first, then oldest past the cap. */\n #retire(arriving: ReadonlyArray<Admitted>): Set<string> {\n const pinned = new Set(this.achieved ? Encoding.factIds(this.#engine.provenance('achieved', ['goal'])) : []);\n const retired = new Set<string>();\n const kept: Admitted[] = [];\n for (const admitted of [...this.#facts.values(), ...arriving]) {\n if (!pinned.has(admitted.id) && admitted.validTo !== undefined && admitted.validTo < this.#now) {\n retired.add(admitted.id);\n } else {\n kept.push(admitted);\n }\n }\n let excess = kept.length - this.#maxFacts;\n if (excess > 0) {\n const oldest = kept\n .filter(({ id }) => !pinned.has(id))\n .sort((a, b) => age(a.saidAt) - age(b.saidAt) || a.sequence - b.sequence);\n for (const { id } of oldest) {\n if (excess-- <= 0) {\n break;\n }\n retired.add(id);\n }\n }\n return retired;\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/** A fact in working memory, with what retirement needs to order and retract it. */\ntype Admitted = {\n readonly id: string;\n /** Arrival order, the tie-break between facts said at the same time. */\n readonly sequence: number;\n readonly saidAt: number;\n readonly validTo?: number;\n readonly entries: ReadonlyArray<Engine.Entry>;\n};\n\n/** An unparseable `generatedAtTime` sorts as oldest. */\nconst age = (saidAt: number): number => (Number.isNaN(saidAt) ? Number.NEGATIVE_INFINITY : saidAt);\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 ' ',\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,IAAa,YAAY;;AAGzB,IAAa,eAAe;;AAG5B,IAAa,gBAAb,cAAmC,UAAU,OAAO,iBAAiB,kCAAkC,CAAC,CAAC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;GAAE,UAAU;GAAa,OAAO;IAAC,OAAO;IAAI;IAAK;GAAK;EAAE,EAAE,CAClH;EACA,KAAK,QAAQ,OAAO,EAAE,QAAQ,QAAQ,CAAC;EACvC,MAAM,QAAmB,CAAC,OAAO,EAAE;EACnC,MAAM,UAAU,KAAK,QAAQ,IAAI,UAAU,KAAK;EAChD,MAAM,QAAQ,UAAU,QAAiB,KAAK,QAAQ,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC;EACtF,KAAK,QAAQ,OAAO,EAAE,SAAS,QAAQ,CAAC;EACxC,OAAO;GAAE;GAAS;EAAM;CAC1B;AACF;;AAaA,IAAM,OAAO,WAA4B,OAAO,MAAM,MAAM,IAAI,OAAO,oBAAoB;;AAG3F,IAAa,QAAQ,YAAgC,IAAI,UAAU,OAAO;;AAG1E,IAAM,YAAY,EAAE,gBAClB;CAAC,UAAU,SAAS;CAAI,IAAI,UAAU,UAAU,OAAO;CAAG,UAAU;CAAW,IAAI,UAAU,UAAU,MAAM;AAAC,CAAC,CAAC,KAC9G,GACF"}
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 { BaseError } from '@dxos/errors';\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/**\n * Size of the evaluator's working memory: past it the oldest facts retire, so a goal that runs\n * indefinitely keeps a bounded engine, text and entity index (and bounded queries over them).\n */\nexport const MAX_FACTS = 10_000;\n\n/** Most sub-goals one evaluator tracks; sub-goals are structural, so exceeding it is an error. */\nexport const MAX_SUBGOALS = 256;\n\n/** Thrown by `GoalRules.update` when an input would take the evaluator past {@link MAX_SUBGOALS}. */\nexport class CapacityError extends BaseError.extend('CapacityError', 'Goal evaluator capacity exceeded') {\n constructor(context: { readonly max: number; readonly requested: number }) {\n super({ message: `Goal evaluator would hold ${context.requested} sub-goals; the cap is ${context.max}.`, context });\n }\n}\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 * Working-memory size; defaults to {@link MAX_FACTS}. Each `update` first retires facts whose\n * `assertion.validTo` is before the clock, then the oldest (by `generatedAtTime`, then arrival)\n * until at most `maxFacts` remain. Retiring drops a fact from the evaluator only; the feed and any\n * external index keep it, and a re-sent fact with a retired id is admitted again as new.\n * Retirement never wakes the goal, and the facts behind the current `achieved` derivation are\n * never retired, so a goal stays achieved once it is; `holds` and wake bindings may lapse as\n * their facts retire, and a lapsed binding wakes again when new facts restore it.\n */\n readonly maxFacts?: number;\n /** Overrides {@link MAX_SUBGOALS}. */\n readonly maxSubgoals?: number;\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 /** Working memory in arrival order. */\n readonly #facts = new Map<string, Admitted>();\n readonly #subgoals = new Map<string, string>();\n readonly #maxFacts: number;\n readonly #maxSubgoals: number;\n readonly #createdAt: number;\n #now: number;\n #previous: number;\n #achieved = false;\n #sequence = 0;\n\n /** @throws Compiler.CompileError if the rules do not compile. */\n constructor(options: Options) {\n this.#createdAt = options.createdAt;\n this.#now = options.createdAt;\n this.#previous = options.createdAt;\n this.#maxFacts = options.maxFacts ?? MAX_FACTS;\n this.#maxSubgoals = options.maxSubgoals ?? MAX_SUBGOALS;\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.#facts.get(factId)?.saidAt,\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 /**\n * Adds facts and sub-goal status at time `at`, retiring facts past the working-memory window\n * (see {@link Options.maxFacts}); returns the wakes and the goal's state.\n * @throws CapacityError if the input would exceed the sub-goal cap; nothing is applied.\n */\n update({ at, facts = [], subgoals = {} }: Input): Evaluation {\n this.#checkSubgoals(subgoals);\n this.#previous = this.#now;\n this.#now = at;\n\n const arrived = new Map<string, { fact: RDF.Fact; admitted: Admitted }>();\n for (const fact of facts) {\n if (!this.#facts.has(fact.id) && !arrived.has(fact.id)) {\n arrived.set(fact.id, { fact, admitted: this.#admit(fact) });\n }\n }\n const retired = this.#retire([...arrived.values()].map(({ admitted }) => admitted));\n const retiring: Engine.Entry[] = [];\n for (const id of retired) {\n const admitted = this.#facts.get(id);\n if (admitted) {\n retiring.push(...admitted.entries);\n this.#facts.delete(id);\n this.#text.remove(id);\n this.#entities.remove(id);\n }\n }\n if (retiring.length > 0) {\n // A separate pass whose changes are discarded, so retirement never wakes the goal.\n this.#engine.update({ retract: retiring });\n }\n\n const insert: Engine.Entry[] = [];\n const retract: Engine.Entry[] = [];\n for (const { fact, admitted } of arrived.values()) {\n if (!retired.has(fact.id)) {\n this.#facts.set(fact.id, admitted);\n this.#text.add(fact.id, factText(fact));\n this.#entities.add(fact.id, this.#concerns(fact));\n insert.push(...admitted.entries);\n }\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 refresh = this.#now !== this.#previous;\n if (refresh) {\n // Re-evaluate at the previous time with no period boundary crossed, discarding the changes: otherwise a\n // binding `every` held at the previous evaluation is still present, and the next boundary adds nothing new.\n const now = this.#now;\n this.#now = this.#previous;\n this.#engine.update({ refresh: true });\n this.#now = now;\n }\n const changes = this.#engine.update({ insert, retract, refresh });\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 #checkSubgoals(subgoals: Readonly<Record<string, string>>): void {\n const requested = this.#subgoals.size + Object.keys(subgoals).filter((id) => !this.#subgoals.has(id)).length;\n if (requested > this.#maxSubgoals) {\n throw new CapacityError({ max: this.#maxSubgoals, requested });\n }\n }\n\n #admit(fact: RDF.Fact): Admitted {\n const validTo = fact.assertion.validTo === undefined ? undefined : Date.parse(fact.assertion.validTo);\n return {\n id: fact.id,\n sequence: this.#sequence++,\n saidAt: Date.parse(fact.attribution.generatedAtTime),\n validTo: validTo === undefined || Number.isNaN(validTo) ? undefined : validTo,\n entries: Encoding.encode(fact, this.#vocabulary),\n };\n }\n\n /** Ids to retire from working memory plus the arriving facts: expired first, then oldest past the cap. */\n #retire(arriving: ReadonlyArray<Admitted>): Set<string> {\n const pinned = new Set(this.achieved ? Encoding.factIds(this.#engine.provenance('achieved', ['goal'])) : []);\n const retired = new Set<string>();\n const kept: Admitted[] = [];\n for (const admitted of [...this.#facts.values(), ...arriving]) {\n if (!pinned.has(admitted.id) && admitted.validTo !== undefined && admitted.validTo < this.#now) {\n retired.add(admitted.id);\n } else {\n kept.push(admitted);\n }\n }\n let excess = kept.length - this.#maxFacts;\n if (excess > 0) {\n const oldest = kept\n .filter(({ id }) => !pinned.has(id))\n .sort((a, b) => age(a.saidAt) - age(b.saidAt) || a.sequence - b.sequence);\n for (const { id } of oldest) {\n if (excess-- <= 0) {\n break;\n }\n retired.add(id);\n }\n }\n return retired;\n }\n\n /**\n * The earliest time after the last evaluation at which a time built-in can change its answer\n * (`elapsed`, `every`, `due`), so a host schedules its next {@link update} rather than polling;\n * `undefined` when the rules read no clock.\n */\n nextDueAt(): number | undefined {\n const candidates: number[] = [];\n const after = (time: number | undefined) => {\n if (time !== undefined && time > this.#now) {\n candidates.push(time);\n }\n };\n const constant = (term: Ast.Term | undefined): Ast.Value | undefined =>\n term?.type === 'constant' ? term.value : undefined;\n const visit = (literal: Ast.Literal): void => {\n if (literal.type === 'aggregate') {\n literal.body.forEach(visit);\n return;\n }\n if (literal.type !== 'atom') {\n return;\n }\n const [first, second] = literal.atom.terms;\n switch (literal.atom.predicate) {\n case 'elapsed': {\n const length = Builtins.parseDuration(constant(second) ?? '');\n if (length === undefined) {\n return;\n }\n const ref = constant(first);\n if (ref === undefined) {\n // `elapsed(F, …)` over facts: each fact in working memory starts its own clock.\n for (const { saidAt } of this.#facts.values()) {\n after(saidAt + length);\n }\n } else if (ref === 'goal') {\n after(this.#createdAt + length);\n } else {\n const start = this.#facts.get(String(ref))?.saidAt ?? Builtins.parseTime(ref);\n after(start === undefined ? undefined : start + length);\n }\n return;\n }\n case 'every': {\n const period = Builtins.parseDuration(constant(first) ?? '');\n if (period !== undefined && period > 0) {\n after(this.#createdAt + (Math.floor((this.#now - this.#createdAt) / period) + 1) * period);\n }\n return;\n }\n case 'due': {\n const deadline = Builtins.parseTime(constant(first) ?? '');\n const lead = Builtins.parseDuration(constant(second) ?? '');\n after(deadline === undefined || lead === undefined ? undefined : deadline - lead);\n return;\n }\n }\n };\n for (const rule of this.compilation.program.rules) {\n rule.body.forEach(visit);\n }\n return candidates.length === 0 ? undefined : Math.min(...candidates);\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/** A fact in working memory, with what retirement needs to order and retract it. */\ntype Admitted = {\n readonly id: string;\n /** Arrival order, the tie-break between facts said at the same time. */\n readonly sequence: number;\n readonly saidAt: number;\n readonly validTo?: number;\n readonly entries: ReadonlyArray<Engine.Entry>;\n};\n\n/** An unparseable `generatedAtTime` sorts as oldest. */\nconst age = (saidAt: number): number => (Number.isNaN(saidAt) ? Number.NEGATIVE_INFINITY : saidAt);\n\n/** Creates a goal evaluator. */\nexport const make = (options: Options): GoalRules => new GoalRules(options);\n\n/** A term's id and, for an entity known by an opaque id (a DID), its label, so `about` matches the name. */\nconst termText = (term: RDF.Term): string =>\n term.kind === 'entity' && term.label !== undefined ? `${term.entity} ${term.label}` : RDF.termValue(term);\n\n/** The text `about` matches: what was said plus the triple. */\nconst factText = ({ assertion }: RDF.Fact): string =>\n [assertion.quote ?? '', termText(assertion.subject), assertion.predicate, termText(assertion.object)].join(' ');\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,IAAa,YAAY;;AAGzB,IAAa,eAAe;;AAG5B,IAAa,gBAAb,cAAmC,UAAU,OAAO,iBAAiB,kCAAkC,CAAC,CAAC;CACvG,YAAY,SAA+D;EACzE,MAAM;GAAE,SAAS,6BAA6B,QAAQ,UAAU,yBAAyB,QAAQ,IAAI;GAAI;EAAQ,CAAC;CACpH;AACF;;;;;;AAmEA,IAAa,YAAb,MAAuB;CACrB;CACA;CACA;CACA;CACA;CACA;;CAEA,yBAAkB,IAAI,IAAsB;CAC5C,4BAAqB,IAAI,IAAoB;CAC7C;CACA;CACA;CACA;CACA;CACA,YAAY;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