reactive-goal-ui

Interactive Edge Architecture Lab · Backward-Chaining Reactivity

Goal-Driven Pull & Backward-Chaining Reactivity

Instead of pushing every raw text edit through an entire prompt pipeline, this lab declares a target goal DAG, diffs canonicalized facts against the schema, renders a DOM form strictly for the minimal missing leaf frontier, evaluates conditional predicates, and invalidates only transitive dependents on change.

The problem

Forward push prompt chains re-run unrelated downstream steps whenever wording changes, while static multi-page forms ask users for details already present in intake text.

Hypothesis

Backward-chaining from a target goal schema (solveGoalFrontier) renders smaller missing-input forms and invalidates fewer downstream computations on partial edits than forward-push prompt chains.

Confirm vs. falsify

Confirm: upfront facts omit already-known inputs, paraphrases trigger 0 invalidations, and changing destination keeps dates and budget cached. Falsify: extraction errors cause oscillating forms that overwrite user-filled controls.

3 Things To Try

Each action runs the live constraint solver and appends canonical diffs to the trace inspector below.

1. Extract & Inspect Minimal Frontier

Parse the Tokyo trip sentence into canonical facts and render a 2-field form strictly for missing leaves (pace, international).

2. Prove Zero-Invalidation Early Cutoff

Pull ready nodes, re-extract paraphrased prose ("Departing LHR on 12 November..."), and verify 0 invalidated nodes.

3. Stress Test Transitive Blast Radius

Open Tab 2 (Multi-Goal Workspace), switch to SEV-1 Postmortem [14 constraints], and toggle customerDataExposed.

Extraction / Pull Engine
Checking globalThis.LanguageModel capability...

1. Natural-Language Intake & Canonical Controls

Parser extracts origin, destination, dates, and budget while leaving pace and international unset.

2. Dynamically Generated Missing Frontier Form

3. Known Facts & Selective Invalidation Diff

Selective Invalidation vs. Reused Cache

Unlocked Derived Artifacts

Constraint Diff & HTTP Wire Trace Inspector
Canonical Schema & Salsa Memo Table Snapshot
How This Is Set Up

Constraint Solver Schema & Pull Contract

Both tabs share one pure ESM solver (public/lib/goal-solver.js) across browser UI, Cloudflare Worker endpoints (src/worker.ts), and Node tests. Below is the exact contrast between eager forward-push pipelines and the backward-chaining frontier solver running above.

Forward-push chain (the friction)
// Rigid multi-page wizard or blind downstream prompt push
renderWizardSteps(["origin", "destination", "dates", "budget", "pace", "visa"]);

intakeEl.addEventListener("input", async (e) => {
  // Pushes entire prompt pipeline on every wording edit
  const flights = await runPrompt("flightEstimate", e.target.value);
  const hotels = await runPrompt("hotelEstimate", e.target.value);
  // Runs visa step even for domestic trips or incomplete branches
  const visa = await runPrompt("visaChecklist", flights, hotels);
});
Backward-chaining goal frontier
// Declarative goal schema + backward-chaining minimal frontier
const extraction = extractFactsFromText("book-trip", intakeText, prevFacts);
const frontier = solveGoalFrontier(
  "book-trip",
  extraction.canonicalFacts,
  cache,
  extraction.diff.changedKeys, // [] on paraphrase -> early cutoff
);

// Render DOM inputs strictly for frontier.missingLeaves
renderFrontierForm(formEl, countEl, "book-trip", frontier);
// Pull each ready branch independently via /api/pull-goal-node
for (const nodeId of frontier.readyToPull) {
  await pullSingleDerivedNode("book-trip", nodeId, controller.signal);
}
Complete Page Setup: Goal Schema, Frontier Form & Worker Prerequisite Gate

Exact mount targets in public/index.html, the GOAL_PACKS['book-trip'] schema from public/lib/goal-solver.js, and Worker prerequisite validation in public/app.js and src/worker.ts.

<!-- 1. Page HTML Setup (public/index.html) -->
<script type="module" src="/app.js"></script>
<textarea id="complex-intake"></textarea>
<button type="button" id="complex-extract-btn">Extract Known Facts</button>
<form class="frontier-form" id="complex-frontier-form"></form>
<div class="facts-grid" id="complex-facts-grid"></div>
<div class="dag-scroll" id="complex-dag-container"></div>
<div class="artifacts-grid" id="complex-artifacts-grid"></div>

// 2. GOAL_PACKS['book-trip'] Schema (verbatim from public/lib/goal-solver.js)
export const GOAL_PACKS = {
  'book-trip': {
    id: 'book-trip',
    title: 'Book a Trip',
    nodes: [
      { id: 'origin', label: 'Origin City', kind: 'leaf', column: 0, inputType: 'text', normalizer: 'city' },
      { id: 'destination', label: 'Destination City', kind: 'leaf', column: 0, inputType: 'text', normalizer: 'city' },
      { id: 'dates', label: 'Dates & Duration', kind: 'leaf', column: 0, inputType: 'text', normalizer: 'dates' },
      { id: 'budget', label: 'Total Budget', kind: 'leaf', column: 0, inputType: 'text', normalizer: 'currency' },
      { id: 'pace', label: 'Daily Pace', kind: 'leaf', column: 0, inputType: 'select', normalizer: 'enum', options: ['relaxed', 'balanced', 'packed'] },
      { id: 'international', label: 'International Travel', kind: 'leaf', column: 0, inputType: 'boolean', normalizer: 'boolean' },
      {
        id: 'passportExpiry', label: 'Passport Expiry Date', kind: 'leaf', column: 1, inputType: 'text', normalizer: 'text',
        when: { factKey: 'international', equals: true, description: 'international === true', fn: (facts) => facts.international === true },
      },
      { id: 'flightEstimate', label: 'Flight Estimate', kind: 'derived', column: 1, deps: ['origin', 'destination', 'dates'], artifactTitle: '1. Flight Route & Fare Band', artifactOrder: 1 },
      {
        id: 'visaCheck', label: 'Visa & Entry Check', kind: 'derived', column: 2, deps: ['origin', 'destination', 'international', 'passportExpiry'],
        artifactTitle: '2. Passport & Entry Compliance', artifactOrder: 2,
        when: { factKey: 'international', equals: true, description: 'international === true', fn: (facts) => facts.international === true },
      },
      { id: 'itinerary', label: 'Final Trip Itinerary', kind: 'derived', column: 3, deps: ['flightEstimate', 'budget', 'pace', 'international', 'visaCheck'], artifactTitle: '3. Day-by-Day Trip Itinerary', artifactOrder: 3 },
    ],
  },
};

// 3. Page Bootstrap & Worker Prerequisite Gate (public/app.js + src/worker.ts)
const res = await fetch('/api/extract-facts', {
  method: 'POST', headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ packId, text, prevFacts, cache: state.cache }),
});
const solved = solveGoalFrontier(packId, state.facts, state.cache, changedKeys);
renderFrontierForm(dom.complexFrontierForm, dom.complexFrontierCount, packId, solved);
// Derived nodes stream only after all activeDeps resolve:
const pullRes = await fetch('/api/pull-goal-node', {
  method: 'POST', headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ packId, nodeId, facts: state.facts, cache: state.cache }),
});
// src/worker.ts rejects incomplete branches with HTTP 422 before opening NDJSON stream:
if (nodeState.blockedBy.length > 0) {
  return jsonResponse({ error: `Derived node "${nodeId}" is blocked by unsatisfied prerequisites.`, blockedBy: nodeState.blockedBy }, 422);
}
Canonical Fact Diff & Salsa Early Cutoff Contract
// public/lib/goal-solver.js — Canonical diff & conditional predicate pruning
export function canonicalFactDiff(packId, prevFacts = {}, nextFacts = {}) {
  // Compares canonicalPrev[node.id] !== canonicalNext[node.id] per leaf
  return { canonicalPrev, canonicalNext, changedKeys, unchangedKeys, earlyCutoff: changedKeys.length === 0 };
}
const isActive = !node.when || node.when.fn(canonicalFacts);
if (entry && entry.inputSignature !== signatures.get(node.id)) dirtySeeds.add(node.id);

// src/worker.ts — /api/extract-facts & /api/pull-goal-node prerequisite gate
if (url.pathname === '/api/extract-facts') {
  const extraction = extractFactsFromText(packId, text, prevFacts);
  const frontier = solveGoalFrontier(packId, extraction.canonicalFacts, cache, extraction.diff.changedKeys);
  return jsonResponse({ canonicalFacts: extraction.canonicalFacts, diff: extraction.diff, frontierSummary });
}
What disappears

Fixed-order wizard pages asking redundant questions, imperative form show/hide conditionals, and full-pipeline invalidation when prose phrasing changes.

What becomes explicit

Typed leaf normalizers, canonicalFactDiff() equality checks, node.when conditional predicates, transitive inputSignature dirtying, and independent readyToPull branch unlocking.

Platform gaps remaining

HTML forms and Constraint Validation do not express goal dependency graphs, backward-chaining missing-leaf frontiers, or schema-normalized memo tables; client and Worker code must maintain the DAG solver and extraction validator.

Runtime Architecture: Pull Frontier & Early Cutoff

Flow from declarative goal schema through canonical diff, conditional sub-goal pruning, and NDJSON node synthesis.

1. Canonical Normalization

Extracts and normalizes leaf facts (cities, ISO dates, currency totals, booleans) into stable canonical values before diffing against cached revisions.

2. Minimal Frontier Form

Walks backward from the target goal DAG, prunes inactive conditional sub-goals, and emits HTML inputs strictly for active unsatisfied leaves.

3. Selective Invalidation

Recomputes input signatures only along transitive downstream edges, preserving sibling memo caches and streaming ready branches independently over NDJSON.

Backward-chaining goal resolution flow diagram 1. Goal Schema Leaf inputs, predicates, derived prerequisite DAG 2. Known Facts Diff Canonical normalization & Salsa equality check 3. Missing Frontier DOM form generated only for unsatisfied active leaves 4. Conditional Rules Predicates attach or prune sub-goals dynamically 5. Pull & Unlock Transitive invalidation & NDJSON branch streams Early Cutoff: changedKeys === [] skips invalidation & reuses cached derived nodes

Where This Model Scales

  • Multi-deliverable workflows with disjoint prerequisite subtrees where one finished branch can stream and render before unrelated user inputs arrive.
  • High-latency derived synthesis calls guarded by canonical input normalization so paraphrased re-extractions hit Salsa early cutoff with zero recomputation.
  • Conditional compliance or jurisdiction sub-goals that add or prune form inputs deterministically from explicit boolean/enum predicates.

Where This Model Breaks

  • Cyclic goal dependencies where computing node A requires an output from node B while node B requires user confirmation derived from A.
  • Dense coupling where every output section depends on every leaf input, collapsing selective invalidation back into full-graph recomputation.
  • Silent extraction misclassifications where noisy natural-language parsing marks a wrong canonical fact as satisfied and suppresses the clarifying form field.