CSP: worker-src 'self' · MessageChannel Actors

reactive-agent-machines

Side-by-side experiment comparing cyclic effect() signal loops with out-of-band ##STOP## sentinels against deterministic statechart reducers with read-only UI signals and fixed-point tuple-space blackboards running over supervised Dedicated Web Worker actors.

The problem

Wiring bidirectional Agent <-> Human <-> Verifier workflows through shared mutable signals and effect() callbacks mixes data and control flow. Upstream writebacks cause ping-pong cycles, inner watchers leak subscriptions, and ##STOP## substring checks fail under intermediate updates.

Hypothesis

Moving workflow control out of effect() signals into a pure transition(state, event, ctx) statechart or a revision-deduped tuple-space blackboard backed by Dedicated Web Worker actors eliminates runaway loops while keeping UI projection reactive and one-way.

Confirm vs. falsify

Confirm: cyclic effect() hits the 8-tick guard cap and allows unguarded publishes, while statecharts block illegal/low-confidence transitions and Worker actors recover from crashes. Falsify: multi-step verification becomes too rigid in explicit FSM transitions versus tuple predicates.

3 Things To Try

Gear 1: Simple Tests
Step Stream Transport: Detecting LanguageModel API...

Built-in AI Detection: Checks "LanguageModel" in globalThis. When unavailable or disabled, step generation routes to Worker POST /api/agent-step returning an abortable application/x-ndjson stream.

CSP Enforcement: Root document ships worker-src 'self' and script-src 'self' with zero inline scripts or styles, permitting Dedicated Workers at /worker-actor.js.

Interactive Verification Workbench

3-Turn Interviewer <-> Human <-> Fact-Checker Comparison

Click Run 3-Turn Loop to execute identical workload across all three engines, or click Test Illegal Transition Guard to inject an out-of-phase FINALIZE_DRAFT mid-interview.
Live Execution Counters Across Computational Models
Engine Ticks Spurious Runs Leaked Subs Illegal Transitions Blocked Rule Firings Termination
Cyclic effect() 0 0 0 0 0 idle
Statechart + Signals 0 0 0 0 0 idle
Blackboard Pattern Rules 0 0 0 0 0 idle

Cyclic effect()

idle
Awaiting run...

Statechart + Signals

idle
Awaiting run...

Blackboard Pattern Rules

idle
Awaiting run...
How This Is Set Up

Code Contracts & Runtime Wiring

Both gears execute the same pure ESM module (public/lib/machines.js) shared across the main document, Dedicated Web Workers (public/worker-actor.js), and Node tests. Below is the exact contrast between cyclic effect() writebacks and the guarded statechart / blackboard / actor-pool implementations running above.

Cyclic effect() (the failure mode)
// Cyclic Agent <-> Human effect() ping-pong + ##STOP## sentinel
effect(() => {
  // Format drift or intermediate writes bypass string sentinel checks
  if (agentDraft.value.includes("##STOP##")) return;
  // Inner effect() leaks an uncleaned subscription every turn
  effect(() => {
    const check = verifyClaim(humanAnswer.value);
    // Writeback re-triggers upstream interviewer on the main thread
    agentDraft.value = `${check.note} -> clarify turn`;
  });
});
Guarded reducer / blackboard + Worker actors
// Pure FSM reducer + frozen read-only derived UI projection signals
const { nextState, nextCtx, valid, effects } = transition(state, event, ctx);
const ui = deriveUiSignals(nextState, nextCtx); // Frozen: canSubmitHuman, canPublish

// Or monotonic tuple predicates in a supervised Worker actor pool
const match = matchTuplePattern(tuple, {
  kind: "claim", confidenceLt: 0.6, escalationHandled: false,
});
const supervisor = createActorSupervisor({ poolSize: 2 });
await supervisor.submitTask({ id: "task-1", role: "fact_checker", topic: "verify_claim" });
Complete Page Setup: Guards, Blackboard Rules & Worker Supervision

Exact definitions from public/lib/machines.js, public/worker-actor.js, and src/worker.ts wired to the controls above.

<!-- 1. Page HTML Setup (public/index.html) -->
<input id="sc-human-input" type="text" value="Workers isolate actors over MessageChannel with explicit restart queues." />
<input id="sc-confidence-input" type="number" min="0" max="1" step="0.05" value="0.90" />
<div id="sc-transition-buttons" class="button-row"></div>
<dl class="signal-readout">
  <dd id="sig-active-state">idle</dd><dd id="sig-can-human">false</dd><dd id="sig-can-publish">false</dd>
</dl>
<tbody id="bb-tuples-tbody"></tbody>
<form id="escalation-form"><input id="escalation-note" type="text" required /></form>
<div id="actor-slots" class="actor-slots"></div>
<script type="module" src="/app.js"></script>

// 2. Guard Table & Blackboard Rules (public/lib/machines.js)
const ALLOWED_EVENTS_BY_STATE = Object.freeze({
  idle: ["START_INTERVIEW", "RESET"],
  interviewing: ["ASK_HUMAN", "RESET"],
  awaiting_human: ["SUBMIT_HUMAN_ANSWER", "RESET"],
  fact_checking: ["VERIFICATION_PASSED", "NEEDS_CLARIFICATION", "RESET"],
  revising: ["FINALIZE_DRAFT", "RESET"],
  done: ["RESET"],
});

export const BLACKBOARD_RULES = Object.freeze([
  {
    id: "escalate-low-confidence",
    agent: "EscalationRouter",
    when: { kind: "claim", confidenceLt: 0.6, escalationHandled: false },
  },
  {
    id: "escalate-disputed-claim",
    agent: "EscalationRouter",
    when: { kind: "claim", disputed: true, escalationHandled: false },
  },
  {
    id: "apply-human-escalation",
    agent: "Reconciler",
    when: { kind: "escalation", resolved: true, applied: false },
  },
  {
    id: "fact-check-claim",
    agent: "FactChecker",
    when: { kind: "claim", verified: false, disputed: false, confidenceGte: 0.6 },
  },
  {
    id: "publish-clean-draft",
    agent: "Publisher",
    when: { kind: "draft", unresolvedFlags: 0, published: false },
  },
]);

// 3. Dedicated Worker + MessageChannel + CSP Setup (public/app.js + public/worker-actor.js + src/worker.ts)
const supervisor = createActorSupervisor({ poolSize: 2, onUpdate: renderActorSnapshot });
// Inside createActorSupervisor():
const worker = new Worker("/worker-actor.js", { type: "module", name: actorId });
const channel = new MessageChannel();
worker.postMessage({ type: "INIT_PORT", actorId }, [channel.port2]);
Worker Actor Port Loop & Edge NDJSON Contract
// public/lib/machines.js — Pure guard check
const allowed = ALLOWED_EVENTS_BY_STATE[state] || [];
if (!allowed.includes(eventType)) {
  return { nextState: state, nextCtx: { ...safeCtx, illegalBlocked: safeCtx.illegalBlocked + 1 }, valid: false };
}

// public/worker-actor.js — Dedicated Worker port loop isolating faults off main thread
channelPort.onmessage = async (portEvent) => {
  const msg = portEvent.data || {};
  if (msg.type !== "RUN_TASK" || !msg.task) return;
  try {
    const result = await processActorTask(msg.task, boundActorId);
    channelPort.postMessage({ type: "TASK_RESULT", taskId: msg.task.id, result });
  } catch (err) {
    channelPort.postMessage({ type: "ACTOR_FAULT", taskId: msg.task.id, error: String(err) });
  }
};

// src/worker.ts — Strict CSP permitting same-origin module workers + /api/agent-step NDJSON stream
// Content-Security-Policy: default-src 'self'; script-src 'self'; worker-src 'self'; frame-ancestors 'self' https://aifoc.us https://*.aifoc.us ...
const stream = createNdjsonStream(payload, request.signal);
What disappears

Out-of-band ##STOP## substring sentinels, bidirectional signal writebacks inside effect(), leaked inner subscriptions, and uncaught agent faults crashing the main UI loop.

What becomes explicit

Allowed state-event transition guards, frozen read-only UI signal projections (deriveUiSignals), revision-deduped tuple predicates (ruleId:tupleId:revN), MessageChannel worker pools, and worker-src 'self' CSP boundaries.

Platform gaps remaining

Browsers have no built-in statechart coordinator, tuple-space blackboard, or actor supervisor; applications must build MessageChannel handshakes, crash-restart retry queues, and replayable event logs on top of Dedicated Web Workers.

Runtime Boundary Architecture & Tradeoffs

1. Cyclic effect() Graph

Subscribes effects to shared mutable signals without phase guards. Inner watchers created during callbacks accumulate as leaked subscriptions while downstream writebacks bypass ##STOP## string checks.

2. Statechart + Read-Only Signals

Separates transitions into a pure transition(state, event, ctx) reducer. UI reads a frozen deriveUiSignals() projection and cannot write back into state transitions; every dispatch is logged for deterministic replay.

3. Blackboard + Worker Actors

Evaluates monotonic tuple predicates with (ruleId, tupleId, revision) deduplication to fixed point, while a MessageChannel supervisor isolates task execution and restarts crashed Dedicated Web Workers.

Comparison of Cyclic Effect Ping-Pong, Explicit Statechart Reducer, and Supervised Blackboard Worker Pool Three horizontal runtime pipelines showing cyclic effect overload hitting the 8-tick safety guard, deterministic statechart transitions feeding frozen read-only UI signals, and a tuple-space blackboard dispatching tasks to a MessageChannel Web Worker actor supervisor. 1. Cyclic effect() Graph (@paulkinlan/reactive-agent pattern) Interviewer.effect reads topic, factChecker Human.effect leaks watcher + ##STOP## FactChecker.effect mutates upstream signal Safety Guard Abort ticks == 8 (guard_cap) 2. Explicit Statechart Reducer + Read-Only Derived UI Signals transition(state, event, ctx) idle -> ... -> revising -> done Guard & Event Log blocks illegal; replayable deriveUiSignals() Object.freeze() projection DOM View (1-way) zero signal writeback 3. Tuple-Space Blackboard + Supervised Web Worker Actor Pool Blackboard Tuple Space claim / escalation / draft Pattern Predicates dedupe (rule, id, rev) Actor Supervisor queue + crash restart Web Workers (x2) MessageChannel ports
Figure 1: Data and control flow boundaries across cyclic signal graphs (top), guarded statecharts with one-way UI projections (middle), and fixed-point blackboards backed by supervised Dedicated Web Worker actors (bottom).

Where Each Model Scales vs. Where It Breaks

Cyclic effect()

Where it scales
Acyclic DAGs where derived read-only values propagate forward without feeding back into upstream inputs.
Where it breaks
Bidirectional Agent <-> Human cycles, dynamic inner effects without cleanup disposers, and out-of-band string sentinels like ##STOP##.

Statechart + Signals

Where it scales
Single-coordinator workflows needing strict phase invariants, audit logs, deterministic replay, and one-way UI bindings.
Where it breaks
Combinatorial state explosion when dozens of independent claims or concurrent worker tasks run in parallel without shared serialization.

Blackboard + Worker Actors

Where it scales
Decoupled multi-agent pipelines reacting to declarative tuple predicates with worker-thread crash isolation and queue recovery.
Where it breaks
Non-monotonic rules that toggle tuple fields back and forth without revision dedupe, risking livelock until max-step caps intervene.