Reintent

Saving and restoring

What an intent keeps, how new code takes it over, how to save it, and what it has done.

Sam closes the laptop after an evening with the card: a sentence said to System One, its answers in, the tone decided. Tomorrow the app opens again, and the card should be exactly as Sam left it, without asking System One again. Everything it needs is in the intent's layers.

You will learn

  • What intent.layers holds
  • How new code takes over an intent with setProgram
  • How to save the layers and open them again
  • What intent.inspect() and intent.stats report

The layers

The evening, in code, then the layers read back:

/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, 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' };

/** What a button does: the intent gives it to every evaluation (index.intent.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) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return `${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'],
  });
}

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

export function Card(p: Person) {
  const tone = useTone();
  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) }),
      host('p', { children: 'Wishing you a wonderful day.' }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  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',
        }),
      ],
    });
  return host('div', { children: [row('tone', TONES, tone)] });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

intent.layers is one immutable value, a Layers, with a layer for each writer:

  • choices: each choice by its key ('card#tone', keyOf(id): a name cannot be empty or have # in it, so the key splits back at its last #), with a person's decision, constraints and preferences, and System One's beliefs, one for each set of inputs. Here there are two, after the sentence and before it, newest first;
  • named: what a person said of every choice with a name;
  • facts: what a person said of the whole card (What a person says);
  • generated: what System Two wrote, for each set of inputs;
  • unloaded: what the host marked as held elsewhere;
  • program: the program's name, given by programName or by an accepted reprogramming. It names the program in the history; no judgment is given it.

The program itself is code, so the app gives it again each time it starts.

New code, the same intent

Sam's app loads new code while the card is open. The intent takes the new program:

/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, 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' };

/** What a button does: the intent gives it to every evaluation (index.intent.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) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return `${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'],
  });
}

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

export function Card(p: Person) {
  const tone = useTone();
  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) }),
      host('p', { children: 'Wishing you a wonderful day.' }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  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',
        }),
      ],
    });
  return host('div', { children: [row('tone', TONES, tone)] });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

intent.setProgram(program) gives the intent a new program and keeps everything else: the layers and their history. The card reads Sam's formal as decided, and undo takes it back, because the history is still there. After the undo, System One's warm is back from the beliefs the layers kept. intent.inspect().requests still holds only the judgment from before the new code, so nobody was asked again.

Saving and opening again

The layers are plain data, so JSON.stringify(intent.layers) saves them, and createIntent({ layers }) opens them again:

import { createIntent, recorded } from '@reintent/core';
import { Card, GRANDMA } from './App.intent';

const model = recorded([{ effect: 'judge', id: 'card#tone', answer: { warm: 0.7, funny: 0.2, formal: 0.1 } }]);

// In the evening: System One judged, Sam decided formal, and the app saved the layers.
const evening = createIntent({ program: <Card {...GRANDMA} />, model });
const connection = evening.connect({ commit() {} });
evening.decide({ of: 'card', name: 'tone' }, 'formal');
const saved = JSON.stringify(evening.layers);
connection.disconnect();

// The next morning: the app opens again on what it saved.
const intent = createIntent({
  program: <Card {...GRANDMA} />,
  model,
  layers: JSON.parse(saved),
});
const tone = () => intent.realize().reads[0];
console.log(tone().value, tone().source); // → 'formal' 'decision'
console.log(intent.history.canUndo); // → false

intent.forget({ of: 'card', name: 'tone' });
console.log(tone().value, tone().source); // → 'warm' 'belief'
console.log(intent.inspect().requests.length); // → 0

layers starts the intent on the saved layers. The morning's card reads the evening's formal. When Sam forgets the decision, System One's warm comes back from the saved beliefs, and nothing is asked. The history stays with the evening's intent, so the morning starts with nothing to undo.

Give programName again when restoring

createIntent({ program }) sets layers.program to its programName, and to nothing when there is none. Pass the same programName to the restored intent, so its history names the program as the evening's did. The judgments do not depend on it: their stamps hold what they are given, and the program's name is not.

What the intent has done

/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, 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' };

/** What a button does: the intent gives it to every evaluation (index.intent.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) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return `${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'],
  });
}

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

export function Card(p: Person) {
  const tone = useTone();
  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) }),
      host('p', { children: 'Wishing you a wonderful day.' }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  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',
        }),
      ],
    });
  return host('div', { children: [row('tone', TONES, tone)] });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

intent.inspect() returns everything the intent holds now:

  • history: the note of each commit, in order;
  • requests: every request sent to the model, with its status ('running', 'completed' or 'failed'). intent.pending() is the ones still running or failed (Connecting your own model);
  • layers: the same value as intent.layers;
  • revision and version: the program's place in the history and its version id, here 'v1' (Reprogramming the intent).

Here the history has Sam's sentence and decision, and the two judgments are both completed, one before the sentence and one after it.

What an evaluation costs

/** @jsxImportSource @reintent/core */
import { action, choices, createContext, host, useChoiceStatus, 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' };

/** What a button does: the intent gives it to every evaluation (index.intent.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) {
  if (tone === 'formal') return `Many happy returns, ${p.to}.`;
  if (tone === 'warm') return `Happy ${p.age}th birthday, ${p.to}!`;
  return `${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'],
  });
}

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

export function Card(p: Person) {
  const tone = useTone();
  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) }),
      host('p', { children: 'Wishing you a wonderful day.' }),
      host('p', { style: { textAlign: 'right', fontStyle: 'italic' }, children: `— ${p.from}` }),
    ],
  });
}

export function Buttons() {
  const tone = useToneStatus();
  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',
        }),
      ],
    });
  return host('div', { children: [row('tone', TONES, tone)] });
}

export default function App() {
  return host('div', { children: [<Card {...GRANDMA} />, <Buttons />] });
}
ChoicesC

Starting…

Realizationλ

Starting…

What happened

Nothing logged.

intent.stats counts renders, the evaluations that ran the components, and skipped, the ones handed back as they were because nothing the components read had changed. Connecting renders twice, before and after System One's answer. Subsequent realize calls reuse the cached result. Sam's decision makes the connection render again, and reading afterwards reuses that result. Skipping only saves time, and λ comes out the same.

Recap

  • intent.layers holds every writer's layer: decisions, constraints, preferences, beliefs, what was said, what was generated, what is unloaded.
  • intent.setProgram(program) takes new code, and keeps the layers and their history.
  • JSON.stringify(intent.layers) saves them; createIntent({ layers }) opens them again, beliefs included, with an empty history.
  • intent.inspect() reports the history, every request and the program's version; intent.stats counts evaluations run and skipped.

Last updated on

Edit on GitHub