Reactions using `@hearer` throw at initial performance — compiler strips `"hearer"` from `references`, runtime filter cannot drop them (includes host-side workaround)
Versions
- Compiler: 0.11.1
- Runtime: @siftystudio/viv-runtime 0.10.2
- Schema: 0.10.1
Summary
Any action whose reactions: (or effects:) block uses @hearer throws "Cannot evaluate reference: anchor is not entity" during initial performance. The same reactions also never fire during post-hoc (knowledge-relaying) evaluation. The two halves of the toolchain appear to have quietly divergent assumptions about the references field on wrapped expressions — both symptoms resolve if that field includes "hearer".
Reproducer
A minimal, self-contained reproducer. One action, one reaction using @hearer, plus a ~70-line runner that compiles the source and calls selectAction on a two-character world.
repro.viv
action greet:
gloss: "@greeter greets @other"
roles:
@greeter:
as: initiator
@other:
as: partner
effects:
~mark("greet-effects-ran")
reactions:
if @hearer == @other:
~mark("hearer-reaction-fired")
end
run.ts (TypeScript; runs with npx tsx run.ts)
import { randomUUID } from "node:crypto";
import { execSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import type {
EntityView, HostApplicationAdapter, UID, VivInternalState,
} from "@siftystudio/viv-runtime";
import {
EntityType, initializeVivRuntime, selectAction,
} from "@siftystudio/viv-runtime";
const HERE = dirname(fileURLToPath(import.meta.url));
execSync(`vivc --input "${join(HERE, "repro.viv")}" -o "${join(HERE, "repro.bundle.json")}"`, { stdio: "inherit" });
const CONTENT_BUNDLE = JSON.parse(readFileSync(join(HERE, "repro.bundle.json"), "utf8"));
const MARKS: string[] = [];
const STATE = {
timestamp: 0,
entities: {} as Record<UID, EntityView>,
actions: [] as UID[],
viv: null as VivInternalState | null,
};
STATE.entities["room"] = { entityType: EntityType.Location, id: "room", name: "The Room" };
STATE.entities["alice"] = { entityType: EntityType.Character, id: "alice", name: "Alice", location: "room", memories: {} };
STATE.entities["bob"] = { entityType: EntityType.Character, id: "bob", name: "Bob", location: "room", memories: {} };
const adapter: HostApplicationAdapter = {
provisionActionID: () => randomUUID(),
getEntityView: (id) => structuredClone(STATE.entities[id]),
getEntityLabel: (id) => (STATE.entities[id]?.name as string) ?? id,
saveActionData: (id, d) => { if (!STATE.entities[id]) STATE.actions.push(id); STATE.entities[id] = d; },
saveCharacterMemory: (cid, aid, mem) => { (STATE.entities[cid] as any).memories[aid] = mem; },
saveItemInscriptions: () => {},
getVivInternalState: () => structuredClone(STATE.viv),
saveVivInternalState: (s) => { STATE.viv = structuredClone(s); },
getCurrentTimestamp: () => STATE.timestamp,
getEntityIDs: (type, locID) =>
Object.keys(STATE.entities).filter((id) => {
const e = STATE.entities[id];
return e.entityType === type && (!locID || (e as any).location === locID);
}),
functions: {
mark: (label) => { MARKS.push(String(label)); return null; },
},
};
initializeVivRuntime({ contentBundle: CONTENT_BUNDLE, adapter });
const refs = (CONTENT_BUNDLE as any).actions.greet.reactions[0].references;
console.log(`[A] reaction.references = ${JSON.stringify(refs)}`);
console.log(` includes "hearer"? ${refs.includes("hearer")}\n`);
console.log(`[B] selectAction({ initiatorID: "alice" })`);
try {
const id = await selectAction({ initiatorID: "alice" });
console.log(` completed. action=${id ?? "(none)"} marks=${JSON.stringify(MARKS)}`);
} catch (err) {
const e = err as Error & { expression?: any };
console.log(` THREW: ${e.message}`);
console.log(` at: ${e.expression?.source?.code}`);
console.log(` marks up to throw: ${JSON.stringify(MARKS)}`);
}
Observed
[A] reaction.references = ["other"]
includes "hearer"? false
[B] selectAction({ initiatorID: "alice" })
THREW: Cannot evaluate reference: anchor is not entity
at: @hearer
marks up to throw: ["greet-effects-ran"]
Expected
[A] reaction.references = ["greeter","other","hearer"]
includes "hearer"? true
[B] selectAction({ initiatorID: "alice" })
completed. action=<uuid> marks=["greet-effects-ran"]
Root cause (traced)
Two files that disagree about what references means on a wrapped expression.
Runtime uses references as the sole signal for whether an expression uses @hearer:
runtimes/js/src/action-manager/action-manager.ts(~line 1145): post-hoc dispatch keeps only reactions whosereferencesincludes"hearer".- Same file (~line 1150): initial-performance dispatch drops reactions whose referenced roles aren't bound. If
"hearer"were inreferencesand not bound, this would correctly remove the reaction before evaluation.
Compiler omits special role names from references:
# compiler/src/viv_compiler/utils/utils.py:170
if ast_chunk['value']['anchor'] not in config.SPECIAL_ROLE_NAMES:
roles_referenced_so_far.append(ast_chunk['value']['anchor'])
# compiler/src/viv_compiler/config/config.py:91
SPECIAL_ROLE_NAMES: Final = {"hearer", ACTION_SELF_REFERENCE_ROLE_NAME}
Net: "hearer" never reaches the runtime's references array, so neither filter can act on it.
Design note
It's plausible the compiler deliberately excludes special roles because references primarily drives role-dependency ordering during casting — and hearer/this aren't author-cast, so they don't belong in that dependency graph. The incoherence is that the runtime later layered a second meaning onto the same field ("does this reference @hearer?") without the compiler being aware of that new contract.
Possible fixes:
- Compiler-side (simplest): include special role names in
referenceswhen the body references them. - Runtime-side: compute
@hearerusage via a separate AST scan, or add a newusesHearer: booleanon wrapped expressions.
Impact
The revenge-story walkthrough in docs/introduction/tour.md uses this same pattern (e.g. if @hearer == @subject.initiator && <@hearer> fits trope is-unhinged:). My reproducer suggests that this mechanism doesn't work on the current releases.
Host-side workaround
Users hitting this today can patch the compiled bundle before handing it to initializeVivRuntime. The patch walks each action's effect and reaction bodies, looks for entity references with anchor === "hearer", and adds "hearer" to the enclosing wrapped expression's references list. After patching, the runtime's filters work as they appear to have been designed.
patch-hearer-references.ts (idempotent; safe to keep after an upstream fix)
type AnyObj = Record<string, unknown>;
function collectAnchors(node: unknown, out: Set<string>): void {
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
for (const el of node) collectAnchors(el, out);
return;
}
const obj = node as AnyObj;
if (
(obj.type === "entityReference" || obj.type === "symbolReference") &&
obj.value &&
typeof (obj.value as AnyObj).anchor === "string" &&
!(obj.value as AnyObj).local
) {
out.add((obj.value as AnyObj).anchor as string);
}
for (const key of Object.keys(obj)) collectAnchors(obj[key], out);
}
function patchList(list: unknown): number {
if (!Array.isArray(list)) return 0;
let added = 0;
for (const entry of list) {
if (!entry || typeof entry !== "object") continue;
const e = entry as AnyObj;
const anchors = new Set<string>();
collectAnchors(e.body, anchors);
if (!anchors.has("hearer")) continue;
const refs = Array.isArray(e.references) ? (e.references as string[]) : [];
if (!refs.includes("hearer")) {
refs.push("hearer");
e.references = refs;
added += 1;
}
}
return added;
}
export function patchHearerReferences(bundle: unknown): number {
if (!bundle || typeof bundle !== "object") return 0;
const actions = (bundle as AnyObj).actions;
if (!actions || typeof actions !== "object") return 0;
let total = 0;
for (const name of Object.keys(actions as AnyObj)) {
const a = (actions as AnyObj)[name] as AnyObj;
total += patchList(a.effects);
total += patchList(a.reactions);
}
return total;
}
Usage:
import { patchHearerReferences } from "./patch-hearer-references";
patchHearerReferences(CONTENT_BUNDLE);
initializeVivRuntime({ contentBundle: CONTENT_BUNDLE, adapter });
Verified: in my project, this restored the original @hearer-based revenge trigger across five 6-tick simulations with zero crashes. The reproducer above also passes cleanly (no throw, reaction properly filtered from initial performance) when the patch is applied.
@possibly Good find, and thanks for the thorough report!
This issue is a regression that was caused by treating the special roles @this and @hearer uniformly across the compiler phases. While they allow for the same handling in casting pools and conditions, @hearer needs special treatment for effects and reactions—namely, it can't be excluded from the references wrappers on those fields, as you discovered. This is now fixed, and I've also added compiler and runtime tests to catch any future regressions here.
The fix is shipped in compiler v0.11.2: pip install --upgrade viv-compiler. No need to upgrade the runtime. And confirming your patchHearerReferences workaround is safe to keep around post-upgrade (where it becomes a no-op).