Reintent

Reprogramming the intent

How a host hears every proposal, accepts one with choices it already knows, tells programs apart, and lets System Two reprogram one part.

In Quick start Sam's app asks System Two for the family card and accepts what comes back. Sam's app knows more than the card does. Six of the family are coming to dinner, so the new card needs six lines to sign. Sam may also ask twice, change their mind after accepting, or want only the card reprogrammed, with the line about the dinner kept as it is.

You will learn

  • How a host hears every proposal (intent.onProposal) and accepts one with choices of its own (accept(migrate))
  • What intent.revision and intent.version say, and which proposals can still be accepted
  • How a reprogramming is taken back
  • How System Two reprograms one part of the program (<World id>)

Every proposal

/** @jsxImportSource react */
import { useEffect, useState } from 'react';
import type { ProposalView } from '@reintent/core';
import { ReintentProvider, reintentView, useReintent } from '@reintent/react';
import Card from './Card.intent';
import Family from './Family.intent';
import { recordedModel } from './model';

const REQUEST = 'Make it a card the whole family signs.';
const OCCASIONS = ['She loves a good joke.', 'It is for a formal family dinner.'];
/** Who is coming to dinner: Sam's app knows, the card does not. */
const FAMILY = ['Sam', 'Mum', 'Dad', 'Aunt Rose', 'Leo', 'Mia'];

// The card as a React component: its props are the root's input.
const GrandmaCard = reintentView(Card);
// System Two's reprogram names a program; the one it wrote is recorded in Family.intent.tsx.
const model = recordedModel({ family: Family });

/** Every proposal, whoever asked for it, until Sam accepts or rejects it. */
function Proposals() {
  const { onProposal, review } = useReintent();
  const [proposals, setProposals] = useState<ProposalView[]>([]);
  useEffect(() => onProposal((p) => setProposals((ps) => [...ps, p])), [onProposal]);
  // Accepted only on the program it was written for.
  const version = useReintent((s) => s.version);
  const done = (p: ProposalView) => setProposals((ps) => ps.filter((x) => x !== p));
  return (
    <>
      {proposals.map((p) => (
        <div
          key={p.id}
          style={{ padding: 12, border: '1px solid #c2410c', borderRadius: 8, marginBottom: 8 }}
        >
          <p>
            System Two suggests, for revision {p.baseRevision}: {p.summary}
          </p>
          <button
            disabled={p.base !== version}
            onClick={() => {
              // The new program, and a line for everyone coming to dinner: one step.
              void review(p).accept((tx) => tx.decide({ of: 'card', name: 'signatures' }, FAMILY.length));
              done(p);
            }}
          >
            Accept
          </button>
          <button onClick={() => (void review(p).reject(), done(p))}>Reject</button>
        </div>
      ))}
    </>
  );
}

/** When no tone will do, Sam can ask System Two for another card. */
function Ask() {
  const { reprogram } = useReintent();
  const unresolved = useReintent((s) =>
    s.reads.some((r) => r.key === 'card#tone' && r.status === 'unresolved'),
  );
  if (!unresolved) return null;
  return (
    <p>
      None of the tones seems right for this card.{' '}
      <button onClick={() => void reprogram({ prompt: REQUEST })}>{REQUEST}</button>
    </p>
  );
}

/** Which program the card is now, and a way back. */
function Program() {
  const { history } = useReintent();
  const revision = useReintent((s) => s.revision);
  const version = useReintent((s) => s.version);
  const canUndo = useReintent((s) => s.history.canUndo);
  return (
    <p style={{ fontSize: 13 }}>
      Revision {revision} · version {version}{' '}
      <button disabled={!canUndo} onClick={() => void history.undo()}>
        Undo
      </button>
    </p>
  );
}

/** What Sam tells System One about the occasion: one sentence at a time, and a second click takes it back. */
function Occasion() {
  const { commit } = useReintent();
  const facts = useReintent((s) => s.layers.facts);
  const say = (x: string) =>
    commit(facts.includes(x) ? `“${x}” taken back` : `“${x}”`, (tx) => {
      facts.forEach((y) => tx.untell(y));
      if (!facts.includes(x)) tx.tell(x);
    });
  return (
    <p>
      About the occasion:{' '}
      {OCCASIONS.map((x) => (
        <button key={x} aria-pressed={facts.includes(x)} onClick={() => say(x)}>
          {x}
        </button>
      ))}
    </p>
  );
}

export default function App() {
  return (
    <ReintentProvider model={model}>
      {/* Sam's controls are the card's children: they read and change its Intent with useReintent. */}
      <GrandmaCard to="Grandma" age={90} from="Sam">
        <Occasion />
        <Ask />
        <Proposals />
        <Program />
      </GrandmaCard>
    </ReintentProvider>
  );
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

In the app, click “It is for a formal family dinner.”, then “Make it a card the whole family signs.” twice. Two proposals come back, each with Accept and Reject. The app lists them from intent.onProposal, which hears every proposal, whoever asked for it: intent.reprogram({ prompt }) here, a reprogram step, or the intent itself for a choice nothing handled. Each one is a Proposal: a summary and a program, with the prompt or the unresolved choice (why) that asked for it. Nothing changes until a person accepts it. Reject calls intent.review(p).reject(), which writes nothing.

Choices that come with the program

Accept one. The card becomes the family's, with six lines to sign, and nobody is asked how many. The app accepts with

intent.review(p).accept((tx) => tx.decide({ of: 'card', name: 'signatures' }, FAMILY.length));

accept commits the proposal's program and what its function writes, as one step of the history. The function gets the same tx as intent.commit, without program. Here it decides the new program's choice. A reprogramming that renames a choice can carry the old answer over the same way.

Which program: revision and version

Below the proposals, the app shows Revision 1 · version v2. intent.revision is the program's place in the history: how many programs came before it. intent.version names the program itself, and no other program ever gets the same name.

The second proposal's Accept is now disabled. A proposal is written for one program, its base (baseRevision is that program's revision), and accepting it on another program throws, because what it wrote may no longer fit. The app compares p.base with intent.version before offering it.

setProgram replaces the program outside the history

intent.setProgram(element, name) gives the intent a program without a step in the history, the way createIntent({ program }) starts with one. The program gets a new version and its name; no judge is given the name, so System One judges again only the choices whose question or possibilities changed. Use it for the program a host starts with or loads. A reprogramming goes through review(p).accept(), which undo can take back.

A proposal and the root's input

A proposal keeps the input it was written under (p.input), and intent.review(p).inputChanged says whether the input is another one now. Accepted, the new program runs on the input there is. Before it is put in place it is evaluated on that input, in the context of each presentation on a screen now and each context you pass (accept(migrate, { contexts })), or else in the intent's own: a program that throws on it, or gives a tree a host cannot take, throws a ProgramRejected, and the program stays as it was.

Taking a reprogramming back

Click Undo. The card is Sam's again, at revision 0, version v1, and the six lines go with the program, because they were one step. Undo brings back the program's version, so the second proposal's Accept works again.

Reprogramming one part

At the dinner, the line above the card, “For Grandma, at her 90th birthday dinner”, is right as it is. Sam would rather System Two reprogrammed the card and left the rest alone.

/** @jsxImportSource @reintent/core */
import {
  action,
  choices,
  createContext,
  host,
  useChoiceStatus,
  useGenerate,
  type Child,
  type Id,
} from '@reintent/core';

export type Person = { to: string; age: number; from: string };
export const TONES = ['warm', 'funny', 'formal'] as const;
export type Tone = (typeof TONES)[number];

export const GRANDMA: Person = { to: 'Grandma', age: 90, from: 'Sam' };
export const JOKES = ['pun', 'tease'] as const;
export type Joke = (typeof JOKES)[number];

/** What a button does: the intent gives it to every evaluation (index.tsx). */
export const Decide = createContext<(id: Id, value: unknown) => void>('Decide', { key: () => undefined });
/** What “no preference” does: forget the person's decision, so the choice resolves on its own again. */
export const Forget = createContext<(id: Id) => void>('Forget', { key: () => undefined });

export const LOOK: Record<Tone, { background: string; accent: string }> = {
  warm: { background: '#fdebd3', accent: '#b5562b' },
  funny: { background: '#fff2a8', accent: '#7a4fd6' },
  formal: { background: '#f1eee8', accent: '#2b2b2b' },
};

export function title(p: Person, tone: Tone, joke?: Joke) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return joke === 'tease'
    ? `${p.to}, you don’t look a day over ${p.age - 1}!`
    : `${p.age} laps around the sun, ${p.to}!`;
}

/** The card's tone, and which layer it came from: System One weighs it; a person's decision is above its judgment. */
export function useToneStatus() {
  return useChoiceStatus(choices<Tone>(...TONES), {
    of: 'card',
    name: 'tone',
    defaultValue: 'warm',
    question: 'Which tone suits a birthday card for Grandma, turning 90?',
    ask: ['model', 'human'],
  });
}

export function useTone() {
  return useToneStatus().value;
}

/** Which joke: a question only a funny card has. Until someone picks one, it is the pun. */
export function useJokeStatus(tone: Tone) {
  return tone === 'funny'
    ? useChoiceStatus(choices<Joke>(...JOKES), {
        of: 'card',
        name: 'joke',
        defaultValue: 'pun',
        otherwise: 'default',
      })
    : undefined;
}

export function useJoke(tone: Tone) {
  return useJokeStatus(tone)?.value;
}

export function Card(p: Person) {
  const tone = useTone();
  const joke = useJoke(tone);
  // The words nobody listed: System Two writes them, once for each set of inputs.
  const message = useGenerate<string>({
    of: 'card',
    name: 'message',
    instruction:
      'Write the message inside a birthday card: two short sentences in this tone, no greeting and no signature.',
    uses: { to: p.to, age: p.age, tone, joke },
  });
  return host('div', {
    style: {
      maxWidth: 380,
      padding: '1.5em',
      borderRadius: 12,
      background: LOOK[tone].background,
      color: '#3a2a1c',
    },
    children: [
      host('h1', { style: { color: LOOK[tone].accent }, children: title(p, tone, joke) }),
      host('p', { children: message.value ?? '…' }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  const joke = useJokeStatus(tone.value);
  const row = <T extends string>(name: string, values: readonly T[], now: { value: T; source: string }) =>
    host('p', {
      children: [
        ...values.map((v) =>
          // A person's decision is pressed; a value the card took on its own is only marked.
          host('button', {
            disabled: now.source === 'decision' && v === now.value,
            ...(now.source !== 'decision' &&
              v === now.value && { style: { textDecoration: 'underline dotted' } }),
            onClick: action.decide({ of: 'card', name }, v),
            children: v,
          }),
        ),
        // The person's way of not deciding: forget the decision, and the card picks again.
        host('button', {
          disabled: now.source !== 'decision',
          onClick: action.forget({ of: 'card', name }),
          style: {
            marginLeft: 12,
            borderStyle: 'dashed',
            fontStyle: 'italic',
            ...(now.source === 'decision' && { background: 'transparent' }),
          },
          children: 'no preference',
        }),
      ],
    });
  // Unresolved: the card shows its question. Whether a person is asked is the intent's (questions()).
  const asking = tone.status === 'unresolved';
  return host('div', {
    children: [
      asking &&
        host('p', {
          style: { fontWeight: 600 },
          children: 'Not sure which tone suits her. Which would you like?',
        }),
      row('tone', TONES, tone),
      joke && row('joke', JOKES, joke),
    ],
  });
}

/** Sam's page around the card: a line about the dinner, then whatever it holds. */
export function Page(p: { children?: Child }) {
  return host('div', {
    children: [
      host('p', {
        style: { fontSize: 13, color: '#6b5b4b' },
        children: 'For Grandma, at her 90th birthday dinner',
      }),
      p.children,
    ],
  });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

In index.intent.tsx, the card sits in <World id="card">, a part of the program named card. Its onUnresolved is a function of an UnresolvedChoice, one of the forms of OnUnresolved: the tone gets reprogram({ goal }), and the joke falls back. A World that reprograms needs an id, and throws without one.

Say “It is for a formal family dinner.” The tone cannot settle, the World takes its one step, and System Two is asked to reprogram the part. model.reprogram gets a ReprogramRequest: the unresolved choice in why, the version and revision it is asked about, and a scope with the part's name (scope.boundary) and what the part holds now (scope.program). It answers with a ProposalDraft: the program the part holds instead, a summary and a name. Here a function in index.intent.tsx stands in for System Two. It logs the request and answers with the family card that System Two wrote in Quick start.

The World moves on while the proposal waits. With its one step taken, the tone asks Sam (intent.questions() lists it). Accept the proposal above the panel. The card becomes the family's, and the line above it stays as it was. The proposal's scope names the part, and accepting it replaces only what that <World id> holds. Undo takes it back like any reprogram. The tone then cannot settle again, and System Two is asked again.

Before a draft becomes a proposal, the intent tries it in its part, where it would be shown, and sends nothing. A draft that fails there, or whose λ the catalog does not take, is refused, and System Two is asked again with the problems in refused, up to attempts drafts. reprogram({ goal, attempts, catalog }) sets them for the World (ReprogramOptions, the catalog a CatalogContract), and createIntent({ catalog, reprogram: { attempts } }) for the whole intent. Unset, it is one draft and no catalog. Letting System Two write a part has a model write the drafts.

A part is found in the program's tree

<World id> names a part only where the program given to the intent holds it, as in this index.intent.tsx. Inside a component's own code, the World holds code. There the step can't be taken, and the choice goes on out with the World's steps in tried (['reprogram'] here). Write the parts System Two may reprogram in the tree.

Recap

  • intent.onProposal hears every proposal: from intent.reprogram, from a reprogram step, and from the intent.
  • intent.review(p).accept(migrate) commits the program and what migrate writes as one step. reject() writes nothing.
  • intent.revision is the program's place in the history, and intent.version names the program. A proposal is accepted only on its base.
  • Undo takes a reprogramming back with the choices that came with it.
  • <World id onUnresolved={reprogram({ goal })}> names a part. System Two gets it as scope, and accepting replaces that part and keeps the rest.

Last updated on

Edit on GitHub