@dxos/brain 0.12.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 (41) hide show
  1. package/dist/lib/Builtins.mjs +10 -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 +153 -11
  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 +6 -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/Encoding.test.d.ts +2 -0
  17. package/dist/types/src/Encoding.test.d.ts.map +1 -0
  18. package/dist/types/src/Evaluator.d.ts +77 -0
  19. package/dist/types/src/Evaluator.d.ts.map +1 -0
  20. package/dist/types/src/Evaluator.test.d.ts +2 -0
  21. package/dist/types/src/Evaluator.test.d.ts.map +1 -0
  22. package/dist/types/src/GoalRules.d.ts +66 -1
  23. package/dist/types/src/GoalRules.d.ts.map +1 -1
  24. package/dist/types/src/Oracle.d.ts +126 -0
  25. package/dist/types/src/Oracle.d.ts.map +1 -0
  26. package/dist/types/src/Oracle.test.d.ts +2 -0
  27. package/dist/types/src/Oracle.test.d.ts.map +1 -0
  28. package/dist/types/src/index.d.ts +2 -0
  29. package/dist/types/src/index.d.ts.map +1 -1
  30. package/dist/types/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +15 -5
  32. package/src/Builtins.ts +12 -1
  33. package/src/Encoding.test.ts +93 -0
  34. package/src/Encoding.ts +9 -0
  35. package/src/Evaluator.test.ts +158 -0
  36. package/src/Evaluator.ts +186 -0
  37. package/src/GoalRules.test.ts +98 -0
  38. package/src/GoalRules.ts +212 -10
  39. package/src/Oracle.test.ts +71 -0
  40. package/src/Oracle.ts +182 -0
  41. package/src/index.ts +2 -0
@@ -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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CAAC,MAAM,CAAC,CAAC;EACvE,CAAC;EAEH,KAAK,YAAY;EACjB,OAAO;GAAE;GAAI;GAAO;GAAU,OAAO,KAAK;EAAM;CAClD;;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;;AAGA,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,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 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,6BA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AAQ,KAAK,YAAY,QAAQ,OAC1C,KAAK,KAAK,QAAQ,KAAK;EAEzB,OAAO,WAAW,WAAW,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,UAAU;CACrE;;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,SAChB,KAAK,SAAS,YAAY,KAAK,UAAU,KAAA,IAAY,GAAG,KAAK,OAAO,GAAG,KAAK,UAAU,IAAI,UAAU,IAAI;;AAG1G,IAAM,YAAY,EAAE,gBAClB;CAAC,UAAU,SAAS;CAAI,SAAS,UAAU,OAAO;CAAG,UAAU;CAAW,SAAS,UAAU,MAAM;AAAC,CAAC,CAAC,KAAK,GAAG"}
@@ -0,0 +1,169 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { parseDuration } from "./Builtins.mjs";
3
+ import { CompileError, formatDiagnostic } from "./Compiler.mjs";
4
+ import { make } from "./GoalRules.mjs";
5
+ import * as Schema from "effect/Schema";
6
+ import { BaseError } from "@dxos/errors";
7
+ import { trim } from "@dxos/util";
8
+ //#region src/Oracle.ts
9
+ var Oracle_exports = /* @__PURE__ */ __exportAll({
10
+ Reply: () => Reply,
11
+ ReplyError: () => ReplyError,
12
+ SYSTEM_PROMPT: () => SYSTEM_PROMPT,
13
+ Statement: () => Statement,
14
+ Step: () => Step,
15
+ parseReply: () => parseReply,
16
+ replay: () => replay,
17
+ userMessage: () => userMessage
18
+ });
19
+ /**
20
+ * The replay gate's oracle (BRAIN.md, "Compilation"): a model call that sees only the goal's text and
21
+ * writes a short timeline of statements with what each should do to the goal. A compilation goes active
22
+ * only if it replays that timeline correctly; the oracle never sees the rules, so it cannot share the
23
+ * compiler's misreading of the goal.
24
+ */
25
+ /** One statement in a test timeline; people and things are named by the ids the goal was given. */
26
+ var Statement = Schema.Struct({
27
+ speaker: Schema.String,
28
+ quote: Schema.String,
29
+ subject: Schema.String,
30
+ predicate: Schema.String,
31
+ object: Schema.String,
32
+ force: Schema.optional(Schema.Literals([
33
+ "assertive",
34
+ "directive",
35
+ "commissive",
36
+ "expressive"
37
+ ])),
38
+ polarity: Schema.optional(Schema.Literals(["+", "-"]))
39
+ });
40
+ /** A step of the timeline: when it happens after the goal is set, what is said, and what should follow. */
41
+ var Step = Schema.Struct({
42
+ /** A duration after the goal was set, e.g. `10m`, `1h`, `3d`. */
43
+ after: Schema.String,
44
+ says: Schema.Array(Statement),
45
+ /** Whether the goal should wake (be judged) at this step. */
46
+ wake: Schema.Boolean,
47
+ /** Whether the goal should be achieved after this step; absent when either is acceptable. */
48
+ achieved: Schema.optional(Schema.Boolean),
49
+ note: Schema.optional(Schema.String)
50
+ });
51
+ var Reply = Schema.Struct({ steps: Schema.Array(Step) });
52
+ /** Thrown by {@link parseReply} when the reply is not a timeline. */
53
+ var ReplyError = class extends BaseError.extend("OracleReplyError", "Oracle reply is not a timeline") {};
54
+ /** The oracle's instructions. */
55
+ var SYSTEM_PROMPT = trim`
56
+ You write acceptance tests for an agent's goal. A goal is a plain-text directive; a runtime will decide,
57
+ after every statement anyone makes, whether the goal should WAKE (the agent looks at it again because
58
+ something relevant happened) and whether it is ACHIEVED (its outcome happened). You do not see how the
59
+ runtime decides; you only describe what a careful person would expect.
60
+
61
+ Write a short timeline of 3 to 6 steps after the goal is set. Include at least one step that should
62
+ wake the goal and at least one near miss that should not (the wrong person, an unrelated topic, a
63
+ refusal or a question instead of a statement). Say only what is needed; each step usually has one
64
+ statement.
65
+
66
+ Each statement is one fact as an extractor would record it: who said it (speaker), the words as said
67
+ (quote), and a subject–predicate–object triple. Name people by the ids given with the goal, exactly as
68
+ given (e.g. "did:halo:…"); name other things with lowercase hyphenated words ("indexer-migration").
69
+ force is assertive (states), directive (asks), commissive (promises or agrees) or expressive; polarity
70
+ is "+" (affirmed) or "-" (denied, refused).
71
+
72
+ Reply with JSON only:
73
+ {"steps":[{"after":"10m","says":[{"speaker":"…","quote":"…","subject":"…","predicate":"…","object":"…","force":"assertive","polarity":"+"}],"wake":true,"achieved":false,"note":"why"}]}
74
+ "after" is a duration since the goal was set (10m, 2h, 3d) and must increase from step to step.
75
+ Leave "achieved" out when either answer would be acceptable.
76
+ `;
77
+ /** The user message for one goal. */
78
+ var userMessage = ({ goal, instructions, owner, people = [] }) => [
79
+ `Goal: "${goal}"`,
80
+ `Owner: ${owner}`,
81
+ instructions?.trim() ? `Instructions: ${instructions.trim()}` : void 0,
82
+ people.length > 0 ? `People (use these ids): ${people.map(({ name, id }) => `${name} = ${id}`).join("; ")}` : void 0
83
+ ].filter((line) => line !== void 0).join("\n");
84
+ var decode = Schema.decodeUnknownSync(Reply);
85
+ /**
86
+ * Extracts the timeline from the oracle's reply; tolerates a code fence or prose around the JSON.
87
+ * @throws ReplyError if there is no valid timeline.
88
+ */
89
+ var parseReply = (text) => {
90
+ const start = text.indexOf("{");
91
+ const end = text.lastIndexOf("}");
92
+ if (start < 0 || end <= start) throw new ReplyError({ message: "the reply has no JSON object" });
93
+ try {
94
+ const reply = decode(JSON.parse(text.slice(start, end + 1)));
95
+ if (reply.steps.length === 0) throw new ReplyError({ message: "the timeline is empty" });
96
+ return reply;
97
+ } catch (error) {
98
+ throw error instanceof ReplyError ? error : new ReplyError({ message: error instanceof Error ? error.message : String(error) });
99
+ }
100
+ };
101
+ /** A statement as the fact the extractor would record. */
102
+ var toFact = (statement, id, saidAt) => ({
103
+ id,
104
+ assertion: {
105
+ subject: {
106
+ kind: "entity",
107
+ entity: statement.subject
108
+ },
109
+ predicate: statement.predicate,
110
+ object: {
111
+ kind: "entity",
112
+ entity: statement.object
113
+ },
114
+ quote: statement.quote
115
+ },
116
+ factuality: {
117
+ value: statement.polarity === "-" ? "CT-" : "CT+",
118
+ polarity: statement.polarity ?? "+"
119
+ },
120
+ illocution: { force: statement.force ?? "assertive" },
121
+ attribution: {
122
+ agent: statement.speaker,
123
+ source: "oracle",
124
+ generatedAtTime: saidAt
125
+ },
126
+ recordedAt: saidAt,
127
+ extractor: {
128
+ id: "oracle",
129
+ model: "none",
130
+ version: "1"
131
+ },
132
+ sourceHash: id
133
+ });
134
+ /** Replays the oracle's timeline against compiled rules; a compile error is a failure. */
135
+ var replay = (source, { createdAt, steps }) => {
136
+ let rules;
137
+ try {
138
+ rules = make({
139
+ source,
140
+ createdAt
141
+ });
142
+ } catch (error) {
143
+ if (error instanceof CompileError) return {
144
+ ok: false,
145
+ failures: error.diagnostics.map(formatDiagnostic)
146
+ };
147
+ throw error;
148
+ }
149
+ const failures = [];
150
+ steps.forEach((step, index) => {
151
+ const offset = parseDuration(step.after) ?? 0;
152
+ const saidAt = new Date(createdAt + offset).toISOString();
153
+ const { wakes, achieved } = rules.update({
154
+ at: createdAt + offset,
155
+ facts: step.says.map((statement, position) => toFact(statement, `oracle-${index}-${position}`, saidAt))
156
+ });
157
+ const label = `step ${index + 1} (${step.note ?? step.says.map(({ quote }) => quote).join(" / ")})`;
158
+ if (wakes.length > 0 !== step.wake) failures.push(`${label}: wake=${wakes.length > 0}, expected ${step.wake}`);
159
+ if (step.achieved !== void 0 && achieved !== step.achieved) failures.push(`${label}: achieved=${achieved}, expected ${step.achieved}`);
160
+ });
161
+ return {
162
+ ok: failures.length === 0,
163
+ failures
164
+ };
165
+ };
166
+ //#endregion
167
+ export { Reply, ReplyError, SYSTEM_PROMPT, Statement, Step, parseReply, replay, Oracle_exports as t, userMessage };
168
+
169
+ //# sourceMappingURL=Oracle.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Oracle.mjs","names":[],"sources":["../../src/Oracle.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport { BaseError } from '@dxos/errors';\nimport { type RDF } from '@dxos/pipeline-rdf';\nimport { trim } from '@dxos/util';\n\nimport * as Builtins from './Builtins.ts';\nimport * as Compiler from './Compiler.ts';\nimport * as GoalRules from './GoalRules.ts';\n\n/**\n * The replay gate's oracle (BRAIN.md, \"Compilation\"): a model call that sees only the goal's text and\n * writes a short timeline of statements with what each should do to the goal. A compilation goes active\n * only if it replays that timeline correctly; the oracle never sees the rules, so it cannot share the\n * compiler's misreading of the goal.\n */\n\n/** One statement in a test timeline; people and things are named by the ids the goal was given. */\nexport const Statement = Schema.Struct({\n speaker: Schema.String,\n quote: Schema.String,\n subject: Schema.String,\n predicate: Schema.String,\n object: Schema.String,\n force: Schema.optional(Schema.Literals(['assertive', 'directive', 'commissive', 'expressive'])),\n polarity: Schema.optional(Schema.Literals(['+', '-'])),\n});\nexport interface Statement extends Schema.Schema.Type<typeof Statement> {}\n\n/** A step of the timeline: when it happens after the goal is set, what is said, and what should follow. */\nexport const Step = Schema.Struct({\n /** A duration after the goal was set, e.g. `10m`, `1h`, `3d`. */\n after: Schema.String,\n says: Schema.Array(Statement),\n /** Whether the goal should wake (be judged) at this step. */\n wake: Schema.Boolean,\n /** Whether the goal should be achieved after this step; absent when either is acceptable. */\n achieved: Schema.optional(Schema.Boolean),\n note: Schema.optional(Schema.String),\n});\nexport interface Step extends Schema.Schema.Type<typeof Step> {}\n\nexport const Reply = Schema.Struct({ steps: Schema.Array(Step) });\nexport interface Reply extends Schema.Schema.Type<typeof Reply> {}\n\nexport type Person = { readonly name: string; readonly id: string };\n\nexport type Goal = {\n readonly goal: string;\n readonly instructions?: string;\n /** Id of the goal's owner. */\n readonly owner: string;\n /** People the goal may concern, with the ids statements must use for them. */\n readonly people?: ReadonlyArray<Person>;\n};\n\n/** Thrown by {@link parseReply} when the reply is not a timeline. */\nexport class ReplyError extends BaseError.extend('OracleReplyError', 'Oracle reply is not a timeline') {}\n\n/** The oracle's instructions. */\nexport const SYSTEM_PROMPT = trim`\n You write acceptance tests for an agent's goal. A goal is a plain-text directive; a runtime will decide,\n after every statement anyone makes, whether the goal should WAKE (the agent looks at it again because\n something relevant happened) and whether it is ACHIEVED (its outcome happened). You do not see how the\n runtime decides; you only describe what a careful person would expect.\n\n Write a short timeline of 3 to 6 steps after the goal is set. Include at least one step that should\n wake the goal and at least one near miss that should not (the wrong person, an unrelated topic, a\n refusal or a question instead of a statement). Say only what is needed; each step usually has one\n statement.\n\n Each statement is one fact as an extractor would record it: who said it (speaker), the words as said\n (quote), and a subject–predicate–object triple. Name people by the ids given with the goal, exactly as\n given (e.g. \"did:halo:…\"); name other things with lowercase hyphenated words (\"indexer-migration\").\n force is assertive (states), directive (asks), commissive (promises or agrees) or expressive; polarity\n is \"+\" (affirmed) or \"-\" (denied, refused).\n\n Reply with JSON only:\n {\"steps\":[{\"after\":\"10m\",\"says\":[{\"speaker\":\"…\",\"quote\":\"…\",\"subject\":\"…\",\"predicate\":\"…\",\"object\":\"…\",\"force\":\"assertive\",\"polarity\":\"+\"}],\"wake\":true,\"achieved\":false,\"note\":\"why\"}]}\n \"after\" is a duration since the goal was set (10m, 2h, 3d) and must increase from step to step.\n Leave \"achieved\" out when either answer would be acceptable.\n`;\n\n/** The user message for one goal. */\nexport const userMessage = ({ goal, instructions, owner, people = [] }: Goal): string =>\n [\n `Goal: \"${goal}\"`,\n `Owner: ${owner}`,\n instructions?.trim() ? `Instructions: ${instructions.trim()}` : undefined,\n people.length > 0\n ? `People (use these ids): ${people.map(({ name, id }) => `${name} = ${id}`).join('; ')}`\n : undefined,\n ]\n .filter((line) => line !== undefined)\n .join('\\n');\n\nconst decode = Schema.decodeUnknownSync(Reply);\n\n/**\n * Extracts the timeline from the oracle's reply; tolerates a code fence or prose around the JSON.\n * @throws ReplyError if there is no valid timeline.\n */\nexport const parseReply = (text: string): Reply => {\n const start = text.indexOf('{');\n const end = text.lastIndexOf('}');\n if (start < 0 || end <= start) {\n throw new ReplyError({ message: 'the reply has no JSON object' });\n }\n try {\n const reply = decode(JSON.parse(text.slice(start, end + 1)));\n if (reply.steps.length === 0) {\n throw new ReplyError({ message: 'the timeline is empty' });\n }\n return reply;\n } catch (error) {\n throw error instanceof ReplyError\n ? error\n : new ReplyError({ message: error instanceof Error ? error.message : String(error) });\n }\n};\n\n/** A statement as the fact the extractor would record. */\nconst toFact = (statement: Statement, id: string, saidAt: string): RDF.Fact => ({\n id,\n assertion: {\n subject: { kind: 'entity', entity: statement.subject },\n predicate: statement.predicate,\n object: { kind: 'entity', entity: statement.object },\n quote: statement.quote,\n },\n factuality: { value: statement.polarity === '-' ? 'CT-' : 'CT+', polarity: statement.polarity ?? '+' },\n illocution: { force: statement.force ?? 'assertive' },\n attribution: { agent: statement.speaker, source: 'oracle', generatedAtTime: saidAt },\n recordedAt: saidAt,\n extractor: { id: 'oracle', model: 'none', version: '1' },\n sourceHash: id,\n});\n\nexport type Result = {\n readonly ok: boolean;\n /** One line per expectation the rules violate. */\n readonly failures: ReadonlyArray<string>;\n};\n\n/** Replays the oracle's timeline against compiled rules; a compile error is a failure. */\nexport const replay = (\n source: string,\n { createdAt, steps }: { createdAt: number; steps: ReadonlyArray<Step> },\n): Result => {\n let rules: GoalRules.GoalRules;\n try {\n rules = GoalRules.make({ source, createdAt });\n } catch (error) {\n if (error instanceof Compiler.CompileError) {\n return { ok: false, failures: error.diagnostics.map(Compiler.formatDiagnostic) };\n }\n throw error;\n }\n const failures: string[] = [];\n steps.forEach((step, index) => {\n const offset = Builtins.parseDuration(step.after) ?? 0;\n const saidAt = new Date(createdAt + offset).toISOString();\n const { wakes, achieved } = rules.update({\n at: createdAt + offset,\n facts: step.says.map((statement, position) => toFact(statement, `oracle-${index}-${position}`, saidAt)),\n });\n const label = `step ${index + 1} (${step.note ?? step.says.map(({ quote }) => quote).join(' / ')})`;\n if (wakes.length > 0 !== step.wake) {\n failures.push(`${label}: wake=${wakes.length > 0}, expected ${step.wake}`);\n }\n if (step.achieved !== undefined && achieved !== step.achieved) {\n failures.push(`${label}: achieved=${achieved}, expected ${step.achieved}`);\n }\n });\n return { ok: failures.length === 0, failures };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,YAAY,OAAO,OAAO;CACrC,SAAS,OAAO;CAChB,OAAO,OAAO;CACd,SAAS,OAAO;CAChB,WAAW,OAAO;CAClB,QAAQ,OAAO;CACf,OAAO,OAAO,SAAS,OAAO,SAAS;EAAC;EAAa;EAAa;EAAc;CAAY,CAAC,CAAC;CAC9F,UAAU,OAAO,SAAS,OAAO,SAAS,CAAC,KAAK,GAAG,CAAC,CAAC;AACvD,CAAC;;AAID,IAAa,OAAO,OAAO,OAAO;;CAEhC,OAAO,OAAO;CACd,MAAM,OAAO,MAAM,SAAS;;CAE5B,MAAM,OAAO;;CAEb,UAAU,OAAO,SAAS,OAAO,OAAO;CACxC,MAAM,OAAO,SAAS,OAAO,MAAM;AACrC,CAAC;AAGD,IAAa,QAAQ,OAAO,OAAO,EAAE,OAAO,OAAO,MAAM,IAAI,EAAE,CAAC;;AAehE,IAAa,aAAb,cAAgC,UAAU,OAAO,oBAAoB,gCAAgC,CAAC,CAAC,CAAC;;AAGxG,IAAa,gBAAgB,IAAI;;;;;;;;;;;;;;;;;;;;;;;AAwBjC,IAAa,eAAe,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U,iBAAiB;CAAO;CACnF,YAAY;CACZ,WAAW;EAAE,IAAI;EAAU,OAAO;EAAQ,SAAS;CAAI;CACvD,YAAY;AACd;;AASA,IAAa,UACX,QACA,EAAE,WAAW,YACF;CACX,IAAI;CACJ,IAAI;EACF,QAAQ,KAAe;GAAE;GAAQ;EAAU,CAAC;CAC9C,SAAS,OAAO;EACd,IAAI,iBAAiB,cACnB,OAAO;GAAE,IAAI;GAAO,UAAU,MAAM,YAAY,IAAI,gBAAyB;EAAE;EAEjF,MAAM;CACR;CACA,MAAM,WAAqB,CAAC;CAC5B,MAAM,SAAS,MAAM,UAAU;EAC7B,MAAM,SAAS,cAAuB,KAAK,KAAK,KAAK;EACrD,MAAM,SAAS,IAAI,KAAK,YAAY,MAAM,CAAC,CAAC,YAAY;EACxD,MAAM,EAAE,OAAO,aAAa,MAAM,OAAO;GACvC,IAAI,YAAY;GAChB,OAAO,KAAK,KAAK,KAAK,WAAW,aAAa,OAAO,WAAW,UAAU,MAAM,GAAG,YAAY,MAAM,CAAC;EACxG,CAAC;EACD,MAAM,QAAQ,QAAQ,QAAQ,EAAE,IAAI,KAAK,QAAQ,KAAK,KAAK,KAAK,EAAE,YAAY,KAAK,CAAC,CAAC,KAAK,KAAK,EAAE;EACjG,IAAI,MAAM,SAAS,MAAM,KAAK,MAC5B,SAAS,KAAK,GAAG,MAAM,SAAS,MAAM,SAAS,EAAE,aAAa,KAAK,MAAM;EAE3E,IAAI,KAAK,aAAa,KAAA,KAAa,aAAa,KAAK,UACnD,SAAS,KAAK,GAAG,MAAM,aAAa,SAAS,aAAa,KAAK,UAAU;CAE7E,CAAC;CACD,OAAO;EAAE,IAAI,SAAS,WAAW;EAAG;CAAS;AAC/C"}
@@ -4,4 +4,6 @@ import { t as Vocabulary_exports } from "./Vocabulary.mjs";
4
4
  import { t as Compiler_exports } from "./Compiler.mjs";
5
5
  import { t as CompilePrompt_exports } from "./CompilePrompt.mjs";
6
6
  import { t as GoalRules_exports } from "./GoalRules.mjs";
7
- export { Builtins_exports as Builtins, CompilePrompt_exports as CompilePrompt, Compiler_exports as Compiler, Encoding_exports as Encoding, GoalRules_exports as GoalRules, Vocabulary_exports as Vocabulary };
7
+ import { t as Evaluator_exports } from "./Evaluator.mjs";
8
+ import { t as Oracle_exports } from "./Oracle.mjs";
9
+ export { Builtins_exports as Builtins, CompilePrompt_exports as CompilePrompt, Compiler_exports as Compiler, Encoding_exports as Encoding, Evaluator_exports as Evaluator, GoalRules_exports as GoalRules, Oracle_exports as Oracle, Vocabulary_exports as Vocabulary };
@@ -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,11 +43,14 @@ 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
  }
46
50
  /** Parses `30s`, `5m`, `2h`, `2d`, `1w` (optionally ISO-prefixed `P`/`PT`) to milliseconds. */
47
51
  export declare const parseDuration: (duration: string | number) => number | undefined;
52
+ /** Parses an epoch-ms number or an ISO timestamp. */
53
+ export declare const parseTime: (value: string | number) => number | undefined;
48
54
  /**
49
55
  * The goal built-ins: `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`),
50
56
  * `elapsed(Ref, Duration)` (`Ref` is `goal`, a fact id or a time), `every(Duration)` (a period
@@ -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,MAAM,CAAC,CAAC;IAChD,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;CACzC;AAED,8FAA8F;AAC9F,MAAM,MAAM,KAAK,GAAG;IAClB,QAAQ,CAAC,GAAG,EAAE,MAAM,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,MAAM,CAAC;IAChC,sEAAsE;IACtE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,QAAQ,CAAC,MA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) => Engine.Entry[];
40
40
  /** The fact ids among base entries (from provenance). */
41
41
  export declare const factIds: (entries: ReadonlyArray<Engine.Entry>) => string[];
42
+ /** An entry as a ground Datalog fact in the dialect goal rules are written in, e.g. `speaker("fact-1", dima).`. */
43
+ export declare const formatEntry: ({ relation, tuple }: Engine.Entry) => string;
44
+ /** The relations the rules engine sees for a fact ({@link encode}), one ground Datalog fact per line. */
45
+ export declare const format: (fact: RDF.Fact, vocabulary?: Vocabulary.Vocabulary) => string[];
42
46
  //# sourceMappingURL=Encoding.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Encoding.d.ts","sourceRoot":"","sources":["../../../src/Encoding.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,MAAM,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAEzC,OAAO,KAAK,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAEnD,qEAAqE;AACrE,eAAO,MAAM,cAAc;aACzB,IAAI,EAAE,CAAC;aACP,OAAO,EAAE,CAAC;aACV,KAAK,EAAE,CAAC;aACR,QAAQ,EAAE,CAAC;aACX,IAAI,EAAE,CAAC;aACP,UAAU,EAAE,CAAC;aACb,SAAS,EAAE,CAAC;aACZ,KAAK,EAAE,CAAC;aACR,MAAM,EAAE,CAAC;aACT,MAAM,EAAE,CAAC;aACT,OAAO,EAAE,CAAC;aACV,UAAU,EAAE,CAAC;aACb,SAAS,EAAE,CAAC;aACZ,OAAO,EAAE,CAAC;aACV,UAAU,EAAE,CAAC;aACb,MAAM,EAAE,CAAC;aACT,UAAU,EAAE,CAAC;aACb,IAAI,EAAE,CAAC;CACC,CAAC;AAEX,kFAAkF;AAClF,eAAO,MAAM,cAAc;aACzB,OAAO,EAAE,CAAC;aACV,MAAM,EAAE,CAAC;aACT,MAAM,EAAE,CAAC;aACT,SAAS,EAAE,CAAC;CACJ,CAAC;AAEX,gDAAgD;AAChD,eAAO,MAAM,SAAS,E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,CAA4C,CAAC;AAEpG;;;;GAIG;AACH,eAAO,MAAM,MAAM,SAAU,GAAG,CAAC,IAAI,eAAe,UAAU,CAAC,UAAU,KAAG,MAAM,CAAC,KAAK,EAwCvF,CAAC;AAEF,yDAAyD;AACzD,eAAO,MAAM,OAAO,YAAa,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,KAAG,MAAM,EAMpE,CAAC;AAEF,mHAAmH;AACnH,eAAO,MAAM,WAAW,wBAAyB,MAAM,CAAC,KAAK,KAAG,MACiB,CAAC;AAElF,yGAAyG;AACzG,eAAO,MAAM,MAAM,SAAU,GAAG,CAAC,IAAI,eAAe,UAAU,CAAC,UAAU,KAAG,MAAM,EACvC,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":""}
@@ -0,0 +1,77 @@
1
+ import { type RDF } from '@dxos/pipeline-rdf';
2
+ import * as GoalRules from './GoalRules.ts';
3
+ /** A standing goal the evaluator watches: its compiled rules and when it began. */
4
+ export type Subscription = {
5
+ readonly id: string;
6
+ /** A goal program (`wake`, `achieved`, `holds`, `blocks`); see `Compiler`. */
7
+ readonly rules: string;
8
+ /** ISO time the subscription began; the rules' clock starts here. */
9
+ readonly createdAt: string;
10
+ };
11
+ /** A wake of one subscription, ready to queue in its outbox. */
12
+ export type Event = {
13
+ /**
14
+ * Stable for the same wake: the subscription, the wake label and the facts behind it (or, for a
15
+ * wake no fact caused, the evaluation time), so a host that re-derives a wake queues it once.
16
+ */
17
+ readonly id: string;
18
+ readonly subscription: string;
19
+ readonly label: string;
20
+ readonly cause: GoalRules.Wake['cause'];
21
+ /** The facts behind the wake, in the order they arrived. */
22
+ readonly facts: ReadonlyArray<RDF.Fact>;
23
+ /** Evaluation time (epoch ms). */
24
+ readonly at: number;
25
+ };
26
+ export type PushOptions = {
27
+ /** Evaluation time (epoch ms). */
28
+ readonly at: number;
29
+ /**
30
+ * Speakers (entity ids) whose facts are evaluated but wake nothing on their own: an agent's own
31
+ * words must not wake it. A wake resting on a quiet fact and another one still wakes.
32
+ */
33
+ readonly quiet?: ReadonlyArray<string>;
34
+ };
35
+ /** The id of an event: see {@link Event.id}. */
36
+ export declare const eventId: (subscription: string, label: string, facts: ReadonlyArray<string>, at: number) => string;
37
+ /**
38
+ * Evaluates every subscription of one brain over a shared fact stream. Synchronous and in memory: a
39
+ * host keeps the facts and the outboxes in its own store, feeds pushes and clock ticks through
40
+ * {@link Evaluator.push} and {@link Evaluator.tick}, and after a restart rebuilds the evaluator with
41
+ * {@link Evaluator.hydrate}, which re-derives the rules' state without emitting events.
42
+ */
43
+ export declare class Evaluator {
44
+ #private;
45
+ constructor({ maxFacts }?: {
46
+ maxFacts?: number;
47
+ });
48
+ /** The subscriptions, in the order they were added. */
49
+ get subscriptions(): Subscription[];
50
+ has(id: string): boolean;
51
+ /**
52
+ * Adds or replaces a subscription. It sees the facts already held (said before it began, so its
53
+ * rules can read history) without waking on them.
54
+ * @throws Compiler.CompileError if the rules do not compile; nothing is changed.
55
+ */
56
+ add(subscription: Subscription): void;
57
+ /** Removes a subscription; false when it was not held. */
58
+ remove(id: string): boolean;
59
+ /** Evaluates new facts at time `at`; returns the wakes, one event each. */
60
+ push(facts: ReadonlyArray<RDF.Fact>, { at, quiet }: PushOptions): Event[];
61
+ /** Re-evaluates the clock at time `at` (a scheduled tick); returns the wakes. */
62
+ tick(at: number): Event[];
63
+ /**
64
+ * Rebuilds state after a restart: adds the subscriptions and replays the facts as of `at` (the last
65
+ * evaluation before the restart), emitting nothing. Wakes due since then come from the next
66
+ * {@link tick} or {@link push}.
67
+ * @throws Compiler.CompileError if a subscription's rules do not compile.
68
+ */
69
+ hydrate(subscriptions: ReadonlyArray<Subscription>, facts: ReadonlyArray<RDF.Fact>, at: number): void;
70
+ /** The earliest time any subscription's clock can next change; see `GoalRules.nextDueAt`. */
71
+ nextDueAt(): number | undefined;
72
+ }
73
+ /** Creates an evaluator. */
74
+ export declare const make: (options?: {
75
+ maxFacts?: number;
76
+ }) => Evaluator;
77
+ //# sourceMappingURL=Evaluator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Evaluator.d.ts","sourceRoot":"","sources":["../../../src/Evaluator.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAE9C,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAC;AAE5C,mFAAmF;AACnF,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,qEAAqE;IACrE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,KAAK,GAAG;IAClB;;;OAGG;IACH,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxC,4DAA4D;IAC5D,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACxC,kCAAkC;IAClC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,kCAAkC;IAClC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACxC,CAAC;AAEF,gDAAgD;AAChD,eAAO,MAAM,OAAO,iBAAkB,MAAM,SAAS,MAAM,SAAS,aAAa,CAAC,MAAM,CAAC,MAAM,MAAM,KAAG,MACS,CAAC;AAElH;;;;;GAKG;AACH,qBAAa,SAAS;;IAOpB,YAAY,EAAE,QAA8B,EAAE,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAO,EAEzE;IAED,uDAAuD;IACvD,IAAI,aAAa,IAAI,YAAY,EAAE,CAElC;IAED,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAEvB;IAED;;;;OAIG;IACH,GAAG,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAOpC;IAED,0DAA0D;IAC1D,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAE1B;IAED,2EAA2E;IAC3E,IAAI,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,EAAE,KAAU,EAAE,EAAE,WAAW,GAAG,KAAK,EAAE,CAQ7E;IAED,iFAAiF;IACjF,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,EAAE,CAExB;IAED;;;;;OAKG;IACH,OAAO,CAAC,aAAa,EAAE,aAAa,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI,CAUpG;IAED,6FAA6F;IAC7F,SAAS,IAAI,MAAM,GAAG,SAAS,CAK9B;CAwCF;AAUD,4BAA4B;AAC5B,eAAO,MAAM,IAAI,aAAc;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,KAAG,SAAmC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Evaluator.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Evaluator.test.d.ts","sourceRoot":"","sources":["../../../src/Evaluator.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,22 @@ 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;
119
+ /**
120
+ * The earliest time after the last evaluation at which a time built-in can change its answer
121
+ * (`elapsed`, `every`, `due`), so a host schedules its next {@link update} rather than polling;
122
+ * `undefined` when the rules read no clock.
123
+ */
124
+ nextDueAt(): number | undefined;
61
125
  /** Evaluates the `blocks` rules for a proposed action without keeping it. */
62
126
  checkAction(action: Action): ActionCheck;
63
127
  }
64
128
  /** Creates a goal evaluator. */
65
129
  export declare const make: (options: Options) => GoalRules;
130
+ export {};
66
131
  //# sourceMappingURL=GoalRules.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"GoalRules.d.ts","sourceRoot":"","sources":["../../../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