@dxos/brain 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,6 +52,9 @@ var KeywordIndex = class {
52
52
  add(factId, text) {
53
53
  this.#texts.set(factId, text);
54
54
  }
55
+ remove(factId) {
56
+ this.#texts.delete(factId);
57
+ }
55
58
  matches(factId, query) {
56
59
  return keywordMatch(this.#texts.get(factId) ?? "", query);
57
60
  }
@@ -65,6 +68,9 @@ var MemoryEntityIndex = class {
65
68
  add(factId, entities) {
66
69
  this.#byFact.set(factId, entities);
67
70
  }
71
+ remove(factId) {
72
+ this.#byFact.delete(factId);
73
+ }
68
74
  concerns(factId) {
69
75
  return this.#byFact.get(factId) ?? [];
70
76
  }
@@ -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 /** 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 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 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 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":";;;;;;;;;;;AAwCA,IAAM,6BAAa,IAA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AC1C,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\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,EAA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+2,34 @@ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { KeywordIndex, MemoryEntityIndex, make as make$1 } from "./Builtins.mjs";
3
3
  import { encode, factIds } from "./Encoding.mjs";
4
4
  import { RELATIONS, compileOrThrow, defaultVocabulary } from "./Compiler.mjs";
5
+ import { BaseError } from "@dxos/errors";
5
6
  import { RDF } from "@dxos/pipeline-rdf";
6
7
  import * as Engine from "@dxos/datalog/Engine";
7
8
  //#region src/GoalRules.ts
8
9
  var GoalRules_exports = /* @__PURE__ */ __exportAll({
10
+ CapacityError: () => CapacityError,
9
11
  GoalRules: () => GoalRules,
12
+ MAX_FACTS: () => MAX_FACTS,
13
+ MAX_SUBGOALS: () => 256,
10
14
  make: () => make
11
15
  });
12
16
  /**
17
+ * Size of the evaluator's working memory: past it the oldest facts retire, so a goal that runs
18
+ * indefinitely keeps a bounded engine, text and entity index (and bounded queries over them).
19
+ */
20
+ var MAX_FACTS = 1e4;
21
+ /** Most sub-goals one evaluator tracks; sub-goals are structural, so exceeding it is an error. */
22
+ var MAX_SUBGOALS = 256;
23
+ /** Thrown by `GoalRules.update` when an input would take the evaluator past {@link MAX_SUBGOALS}. */
24
+ var CapacityError = class extends BaseError.extend("CapacityError", "Goal evaluator capacity exceeded") {
25
+ constructor(context) {
26
+ super({
27
+ message: `Goal evaluator would hold ${context.requested} sub-goals; the cap is ${context.max}.`,
28
+ context
29
+ });
30
+ }
31
+ };
32
+ /**
13
33
  * Evaluates one goal's compiled rules over a growing fact stream and a clock. A goal wakes when a
14
34
  * wake rule gains a new binding, when `achieved` first becomes true, and when a sub-goal's status
15
35
  * changes.
@@ -21,15 +41,21 @@ var GoalRules = class {
21
41
  #text;
22
42
  #entities;
23
43
  #concerns;
24
- #saidAt = /* @__PURE__ */ new Map();
44
+ /** Working memory in arrival order. */
45
+ #facts = /* @__PURE__ */ new Map();
25
46
  #subgoals = /* @__PURE__ */ new Map();
47
+ #maxFacts;
48
+ #maxSubgoals;
26
49
  #now;
27
50
  #previous;
28
51
  #achieved = false;
52
+ #sequence = 0;
29
53
  /** @throws Compiler.CompileError if the rules do not compile. */
30
54
  constructor(options) {
31
55
  this.#now = options.createdAt;
32
56
  this.#previous = options.createdAt;
57
+ this.#maxFacts = options.maxFacts ?? 1e4;
58
+ this.#maxSubgoals = options.maxSubgoals ?? 256;
33
59
  this.#vocabulary = options.vocabulary ?? defaultVocabulary();
34
60
  this.#text = options.text ?? new KeywordIndex();
35
61
  this.#entities = options.entities ?? new MemoryEntityIndex();
@@ -39,7 +65,7 @@ var GoalRules = class {
39
65
  now: () => this.#now,
40
66
  previous: () => this.#previous,
41
67
  createdAt: options.createdAt,
42
- saidAt: (factId) => this.#saidAt.get(factId)
68
+ saidAt: (factId) => this.#facts.get(factId)?.saidAt
43
69
  },
44
70
  text: this.#text,
45
71
  entities: this.#entities
@@ -61,17 +87,39 @@ var GoalRules = class {
61
87
  get holds() {
62
88
  return this.#engine.has("holds", ["goal"]);
63
89
  }
64
- /** Adds facts and sub-goal status at time `at`; returns the wakes and the goal's state. */
90
+ /**
91
+ * Adds facts and sub-goal status at time `at`, retiring facts past the working-memory window
92
+ * (see {@link Options.maxFacts}); returns the wakes and the goal's state.
93
+ * @throws CapacityError if the input would exceed the sub-goal cap; nothing is applied.
94
+ */
65
95
  update({ at, facts = [], subgoals = {} }) {
96
+ this.#checkSubgoals(subgoals);
66
97
  this.#previous = this.#now;
67
98
  this.#now = at;
99
+ const arrived = /* @__PURE__ */ new Map();
100
+ for (const fact of facts) if (!this.#facts.has(fact.id) && !arrived.has(fact.id)) arrived.set(fact.id, {
101
+ fact,
102
+ admitted: this.#admit(fact)
103
+ });
104
+ const retired = this.#retire([...arrived.values()].map(({ admitted }) => admitted));
105
+ const retiring = [];
106
+ for (const id of retired) {
107
+ const admitted = this.#facts.get(id);
108
+ if (admitted) {
109
+ retiring.push(...admitted.entries);
110
+ this.#facts.delete(id);
111
+ this.#text.remove(id);
112
+ this.#entities.remove(id);
113
+ }
114
+ }
115
+ if (retiring.length > 0) this.#engine.update({ retract: retiring });
68
116
  const insert = [];
69
117
  const retract = [];
70
- for (const fact of facts) {
71
- this.#saidAt.set(fact.id, Date.parse(fact.attribution.generatedAtTime));
118
+ for (const { fact, admitted } of arrived.values()) if (!retired.has(fact.id)) {
119
+ this.#facts.set(fact.id, admitted);
72
120
  this.#text.add(fact.id, factText(fact));
73
121
  this.#entities.add(fact.id, this.#concerns(fact));
74
- insert.push(...encode(fact, this.#vocabulary));
122
+ insert.push(...admitted.entries);
75
123
  }
76
124
  const wakes = [];
77
125
  for (const [subgoal, status] of Object.entries(subgoals)) {
@@ -122,6 +170,40 @@ var GoalRules = class {
122
170
  holds: this.holds
123
171
  };
124
172
  }
173
+ #checkSubgoals(subgoals) {
174
+ const requested = this.#subgoals.size + Object.keys(subgoals).filter((id) => !this.#subgoals.has(id)).length;
175
+ if (requested > this.#maxSubgoals) throw new CapacityError({
176
+ max: this.#maxSubgoals,
177
+ requested
178
+ });
179
+ }
180
+ #admit(fact) {
181
+ const validTo = fact.assertion.validTo === void 0 ? void 0 : Date.parse(fact.assertion.validTo);
182
+ return {
183
+ id: fact.id,
184
+ sequence: this.#sequence++,
185
+ saidAt: Date.parse(fact.attribution.generatedAtTime),
186
+ validTo: validTo === void 0 || Number.isNaN(validTo) ? void 0 : validTo,
187
+ entries: encode(fact, this.#vocabulary)
188
+ };
189
+ }
190
+ /** Ids to retire from working memory plus the arriving facts: expired first, then oldest past the cap. */
191
+ #retire(arriving) {
192
+ const pinned = new Set(this.achieved ? factIds(this.#engine.provenance("achieved", ["goal"])) : []);
193
+ const retired = /* @__PURE__ */ new Set();
194
+ const kept = [];
195
+ for (const admitted of [...this.#facts.values(), ...arriving]) if (!pinned.has(admitted.id) && admitted.validTo !== void 0 && admitted.validTo < this.#now) retired.add(admitted.id);
196
+ else kept.push(admitted);
197
+ let excess = kept.length - this.#maxFacts;
198
+ if (excess > 0) {
199
+ const oldest = kept.filter(({ id }) => !pinned.has(id)).sort((a, b) => age(a.saidAt) - age(b.saidAt) || a.sequence - b.sequence);
200
+ for (const { id } of oldest) {
201
+ if (excess-- <= 0) break;
202
+ retired.add(id);
203
+ }
204
+ }
205
+ return retired;
206
+ }
125
207
  /** Evaluates the `blocks` rules for a proposed action without keeping it. */
126
208
  checkAction(action) {
127
209
  const entries = [{
@@ -146,6 +228,8 @@ var GoalRules = class {
146
228
  };
147
229
  }
148
230
  };
231
+ /** An unparseable `generatedAtTime` sorts as oldest. */
232
+ var age = (saidAt) => Number.isNaN(saidAt) ? Number.NEGATIVE_INFINITY : saidAt;
149
233
  /** Creates a goal evaluator. */
150
234
  var make = (options) => new GoalRules(options);
151
235
  /** The text `about` matches: what was said plus the triple. */
@@ -156,6 +240,6 @@ var factText = ({ assertion }) => [
156
240
  RDF.termValue(assertion.object)
157
241
  ].join(" ");
158
242
  //#endregion
159
- export { GoalRules, make, GoalRules_exports as t };
243
+ export { CapacityError, GoalRules, MAX_FACTS, MAX_SUBGOALS, make, GoalRules_exports as t };
160
244
 
161
245
  //# sourceMappingURL=GoalRules.mjs.map
@@ -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 { 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,eAAw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AAO;;AAG1E,IAAM,YAAY,EAAE,gBAClB;CAAC,UAAU,SAAS;CAAI,IAAI,UAAU,UAAU,OAAO;CAAG,UAAU;CAAW,IAAI,UAAU,UAAU,MAAM;AAAC,CAAC,CAAC,KAAK,GAAG"}
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;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,YAAY;CACZ,YAAY;;CAGZ,YAAY,SAAkB;EAC5B,KAAK,OAAO,QAAQ;EACpB,KAAK,YAAY,QAAQ;EACzB,KAAK,YAAY,QAAQ,YAAA;EACzB,KAAK,eAAe,QAAQ,eAAA;EAC5B,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,OAAO,IAAI,MAAM,CAAC,EAAE;GAC/C;GACA,MAAM,KAAK;GACX,UAAU,KAAK;EACjB,CAAC;EACD,KAAK,cAAc,eAAwB,QAAQ,QAAQ;GAAE,YAAY,KAAK;GAAa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EAAE,MAAM,KAAK,EAAE,WAAW,EAAE,QAAQ;GAC1E,KAAK,MAAM,EAAE,QAAQ,QAAQ;IAC3B,IAAI,YAAY,GACd;IAEF,QAAQ,IAAI,EAAE;GAChB;EACF;EACA,OAAO;CACT;;CAGA,YAAY,QAA6B;EACvC,MAAM,UAA0B,CAC9B;GAAE,UAAU;GAAU,OAAO,CAAC,OAAO,IAAI,OAAO,IAAI;EAAE,GACtD,GAAG,OAAO,QAAQ,OAAO,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,YAAY;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"}
@@ -2,6 +2,7 @@ import * as Builtin from '@dxos/datalog/Builtin';
2
2
  /** Finds facts about a topic; a semantic index replaces the keyword one without touching rules. */
3
3
  export interface TextIndex {
4
4
  add(factId: string, text: string): void;
5
+ remove(factId: string): void;
5
6
  /** True if the fact is about `query`. */
6
7
  matches(factId: string, query: string): boolean;
7
8
  /** Every fact about `query`. */
@@ -10,6 +11,7 @@ export interface TextIndex {
10
11
  /** The entities each fact concerns (entity resolution), for scoping possessive goals. */
11
12
  export interface EntityIndex {
12
13
  add(factId: string, entities: ReadonlyArray<string>): void;
14
+ remove(factId: string): void;
13
15
  concerns(factId: string): ReadonlyArray<string>;
14
16
  facts(entity: string): Iterable<string>;
15
17
  }
@@ -33,6 +35,7 @@ export declare const keywordMatch: (text: string, query: string) => boolean;
33
35
  export declare class KeywordIndex implements TextIndex {
34
36
  #private;
35
37
  add(factId: string, text: string): void;
38
+ remove(factId: string): void;
36
39
  matches(factId: string, query: string): boolean;
37
40
  search(query: string): Iterable<string>;
38
41
  }
@@ -40,6 +43,7 @@ export declare class KeywordIndex implements TextIndex {
40
43
  export declare class MemoryEntityIndex implements EntityIndex {
41
44
  #private;
42
45
  add(factId: string, entities: ReadonlyArray<string>): void;
46
+ remove(factId: string): void;
43
47
  concerns(factId: string): ReadonlyArray<string>;
44
48
  facts(entity: string): Iterable<string>;
45
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Builtins.d.ts","sourceRoot":"","sources":["../../../src/Builtins.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAEjD,mGAAmG;AACnG,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,yCAAyC;IACzC,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IAChD,gCAAgC;IAChC,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;CACzC;AAED,yFAAyF;AACzF,MAAM,WAAW,WAAW;IAC1B,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAC3D,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC,MA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;GAKG;AACH,eAAO,MAAM,IAAI,8BAA+B,OAAO,KAAG,OAAO,CAAC,QAmGjE,CAAC;AAEF,mGAAmG;AACnG,eAAO,MAAM,YAAY,QAAO,OAI9B,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Encoding.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Encoding.test.d.ts","sourceRoot":"","sources":["../../../src/Encoding.test.ts"],"names":[],"mappings":""}
@@ -1,7 +1,49 @@
1
+ import { BaseError } from '@dxos/errors';
1
2
  import { RDF } from '@dxos/pipeline-rdf';
2
3
  import * as Builtins from './Builtins.ts';
3
4
  import * as Compiler from './Compiler.ts';
4
5
  import type * as Vocabulary from './Vocabulary.ts';
6
+ /**
7
+ * Size of the evaluator's working memory: past it the oldest facts retire, so a goal that runs
8
+ * indefinitely keeps a bounded engine, text and entity index (and bounded queries over them).
9
+ */
10
+ export declare const MAX_FACTS = 10000;
11
+ /** Most sub-goals one evaluator tracks; sub-goals are structural, so exceeding it is an error. */
12
+ export declare const MAX_SUBGOALS = 256;
13
+ declare const CapacityError_base: {
14
+ new (options?: import("@dxos/errors").BaseErrorOptions): {
15
+ cause?: unknown;
16
+ stack?: string;
17
+ name: "CapacityError";
18
+ context: Record<string, unknown>;
19
+ readonly message: string;
20
+ readonly _tag: "CapacityError";
21
+ };
22
+ isError(error: unknown): error is Error;
23
+ name: "CapacityError";
24
+ is(error: unknown): error is BaseError;
25
+ wrap(options?: Omit<import("@dxos/errors").BaseErrorOptions, 'cause'> & {
26
+ ifTypeDiffers?: boolean;
27
+ }): (error: unknown) => {
28
+ cause?: unknown;
29
+ stack?: string;
30
+ name: "CapacityError";
31
+ context: Record<string, unknown>;
32
+ readonly message: string;
33
+ readonly _tag: "CapacityError";
34
+ };
35
+ extend<Name extends string = string>(name: Name, message?: string): any;
36
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
37
+ prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
38
+ stackTraceLimit: number;
39
+ };
40
+ /** Thrown by `GoalRules.update` when an input would take the evaluator past {@link MAX_SUBGOALS}. */
41
+ export declare class CapacityError extends CapacityError_base {
42
+ constructor(context: {
43
+ readonly max: number;
44
+ readonly requested: number;
45
+ });
46
+ }
5
47
  /** A reason to run judgment on the goal. */
6
48
  export type Wake = {
7
49
  /** The wake rule's label, `achieved`, or the sub-goal whose status changed. */
@@ -36,6 +78,18 @@ export type Options = {
36
78
  readonly entities?: Builtins.EntityIndex;
37
79
  /** Entities a fact concerns; defaults to its subject. */
38
80
  readonly concerns?: (fact: RDF.Fact) => ReadonlyArray<string>;
81
+ /**
82
+ * Working-memory size; defaults to {@link MAX_FACTS}. Each `update` first retires facts whose
83
+ * `assertion.validTo` is before the clock, then the oldest (by `generatedAtTime`, then arrival)
84
+ * until at most `maxFacts` remain. Retiring drops a fact from the evaluator only; the feed and any
85
+ * external index keep it, and a re-sent fact with a retired id is admitted again as new.
86
+ * Retirement never wakes the goal, and the facts behind the current `achieved` derivation are
87
+ * never retired, so a goal stays achieved once it is; `holds` and wake bindings may lapse as
88
+ * their facts retire, and a lapsed binding wakes again when new facts restore it.
89
+ */
90
+ readonly maxFacts?: number;
91
+ /** Overrides {@link MAX_SUBGOALS}. */
92
+ readonly maxSubgoals?: number;
39
93
  };
40
94
  export type Input = {
41
95
  /** Evaluation time (epoch ms); a change re-evaluates time built-ins. */
@@ -56,11 +110,16 @@ export declare class GoalRules {
56
110
  constructor(options: Options);
57
111
  get achieved(): boolean;
58
112
  get holds(): boolean;
59
- /** Adds facts and sub-goal status at time `at`; returns the wakes and the goal's state. */
113
+ /**
114
+ * Adds facts and sub-goal status at time `at`, retiring facts past the working-memory window
115
+ * (see {@link Options.maxFacts}); returns the wakes and the goal's state.
116
+ * @throws CapacityError if the input would exceed the sub-goal cap; nothing is applied.
117
+ */
60
118
  update({ at, facts, subgoals }: Input): Evaluation;
61
119
  /** Evaluates the `blocks` rules for a proposed action without keeping it. */
62
120
  checkAction(action: Action): ActionCheck;
63
121
  }
64
122
  /** Creates a goal evaluator. */
65
123
  export declare const make: (options: Options) => GoalRules;
124
+ export {};
66
125
  //# sourceMappingURL=GoalRules.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"GoalRules.d.ts","sourceRoot":"","sources":["../../../src/GoalRules.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAEzC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAE1C,OAAO,KAAK,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAEnD,4CAA4C;AAC5C,MAAM,MAAM,IAAI,GAAG;IACjB,+EAA+E;IAC/E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;IAChD,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACvC,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;IACpC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,8FAA8F;AAC9F,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACjD,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,QAAQ,CAAC,OAAO,EAAE,OAAO,C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