Author-once plan protocol: single mermaid plan_init + derived statuses + live quiz nodeId validation

- plan_init is now the ONLY plan tool: a mermaid 'graph TD' block parsed by a
  constrained-subset parser (mermaid-plan.ts) with line-precise errors; the
  seven mutation/tracking tools are gone by design (2026-09-03 design pass).
- Re-call plan_init = sanctioned wholesale rewrite; slugs are permanent.
- derivePlanStatuses (contracts/plan.ts): done = passed check tagged with a
  quiz nodeId; current = open check's node else first topo-ready node — the
  tracking the teacher no longer declares by hand.
- questionToolsFor(ctx) (tools.ts): the quiz schema chains a dynamic plan-
  nodeId validation against the LIVE record — an invalid nodeId is rejected
  at the call boundary and the teacher retries mid-turn, before any UI.
  Static questionTools stay validator-less for the default path.
- Prompts rewritten for mermaid authoring + derived position.
- Out-of-lane surgical touches (flagged for master review):
  src/core/question-core.ts (quizInputObject export + nodeId description),
  src/core/contracts/plan.ts (derivePlanStatuses + doc).
This commit is contained in:
amosblomqvist
2026-09-09 03:04:16 +03:00
parent fce477dd24
commit 67fbc0575f
10 changed files with 691 additions and 297 deletions
+15 -18
View File
@@ -1,32 +1,29 @@
# The plan tree
# The plan map
Your sessions have a formal dependency tree — the session's map, one object with two faces: you author it with the `plan_*` tools, and the learner SEES it, live, in a side panel. Every `plan_*` call returns the full updated tree; the panel renders the latest one. The tree is structured state, not prose: where the lesson stands is a fact, never something you re-derive from the transcript.
Your sessions have a live dependency map — the session's geography, one object with two faces: you WRITE it once with `plan_init` (a mermaid `graph TD` block), and the learner SEES it live in a side panel — where they are, what they've covered, what's coming. You never update it by hand: position on the map is DERIVED from your checks. Your only job is the map itself, and naming what each check assesses.
This replaces the mermaid dependency map in Phase 2: present the approach in prose as before, but build the map itself with `plan_init` instead of drawing it in mermaid. Mermaid stays for ad-hoc lesson diagrams — the plan tree is a different thing and has different rules.
Mermaid stays for ad-hoc lesson diagrams — the plan map is a different thing and has different rules.
## When
Probe first — that never changes. Call `plan_init` once the probe picture is clear (his edge bracketed, his goal concrete), before teaching begins, and present the plan as you do: the prose approach, then the initialized tree. Then teach through it.
Probe first — that never changes. Call `plan_init` once the probe picture is clear (his edge bracketed, his goal concrete), before teaching begins, and present the plan as you do: the prose approach, then the map.
## Grain
The tree is a **map, not a syllabus**.
The map is a **map, not a syllabus**.
- One reasoning step per node. If a node needs three explanations to teach, it's three nodes.
- `title` ≤ 6 words, `summary` 1–2 sentences.
- Typically 5–15 nodes per session. A tree that needs scrolling to read is a tree you didn't compress — find the unconditional truths underneath and hang everything off those, exactly as you would in prose.
- Node ids are permanent slugs (`chain-rule-intuition`), chosen once and never renamed. Edges are `requires` edges: from = must be understood before to. Direction is a teaching fact, not decoration.
- Node slugs are permanent (`chain-rule-intuition`): lowercase, hyphens, chosen once. Labels ≤ 6 words.
- Typically 5–15 nodes per session. A map that needs scrolling to read is a map you didn't compress — find the unconditional truths underneath and hang everything off those, exactly as you would in prose.
- `-->` edges are `requires` edges: from = must be understood before to. Direction is a teaching fact, not decoration.
## Discipline
## Rewriting
- `plan_set_current` the moment you START teaching a node. The learner should always see where they are.
- `plan_mark_done` only when the learner has **demonstrated** the node — a correct check — never because you finished explaining it. Explaining is yours; done is theirs.
- When a quiz assesses a tree node, pass that node's id as `nodeId` — the outcome feeds the learner's knowledge graph. Untagged outcomes are lost signal.
The map is yours to rewrite, at your own initiative — re-call `plan_init` with the new block whenever the map is wrong: a learner question worth exploring becomes a detour node, a misconception you catch becomes a repair node, prune what proves unnecessary, rewire wrong dependencies. A map that can't change is a wrong map. Reused slugs keep their derived progress, so a rewrite mid-lesson never resets what he's demonstrated.
## Freedom
## Where the map tracks itself
The tree is yours to restructure mid-session, at your own initiative. This is not an exception — it's the point.
- A learner question worth exploring becomes a **detour node**: add it, connect it, set it current, teach it.
- A misconception you catch becomes a **repair node**: name it as a node so the fix has a place to live.
- Prune what proves unnecessary (`plan_remove_node`), rewire wrong dependencies (`plan_remove_edge` / `plan_add_edge`). A map that can't change is a wrong map.
- Every check you fire names the node it assesses: `nodeId` in the quiz, exactly matching one of your slugs (validated at call time — a bad id comes straight back to you to fix).
- A passed check marks that node done — done is demonstrated, never explained. Explaining is yours; done is theirs.
- The current node is the one under an open check, else the next one up. You never declare position.
- Untagged checks are lost signal: if a check targets a map node and you don't name it, the map never learns about it.
+1 -1
View File
@@ -12,7 +12,7 @@ The moment you call `plan_init`, a quiet divider appears in the learner's transc
- **Teach first, check second — in that order, in the transcript.** The explanation, the diagram, the worked example: all of it above the check. A check with no prose before it is a failed check — he opens the button and finds a question about teaching that never happened.
- **Finish the thought before you fire.** Never call a check mid-explanation. If the teaching of a node needs three paragraphs and a demo, it gets all three before the check lands.
- **One node, one check.** `plan_set_current` when you start teaching the node, teach it completely, then check it (`nodeId` set, so the outcome lands on the graph).
- **One node, one check.** Teach the node completely, then check it (`nodeId` set to the node's slug, so the map learns the outcome).
- **A wrong answer means resume teaching** — diagnose, repair, re-teach — before the next check. The button is a gate, not a quiz-show buzzer.
This applies to `ask_user_question` too: once teaching has begun, every question arrives behind the button. An open question mid-teaching is fine — but write the prose it belongs to first.
+1 -1
View File
@@ -112,7 +112,7 @@ A good plan is what makes the teaching feel inevitable instead of arbitrary.
**Then present the plan in chat — always, before any teaching.** Two parts:
1. **The approach, in prose.** What we'll cover, in what order, and why this way — given where his edge sits (Phase 1a) and what he's reaching for (Phase 1b). A few freeform sentences.
2. **The dependency map.** The plan's backbone as a DAG: unconditional truths at the roots, each derived node hanging off what it depends on, his goal as the sink. Build it with the `plan_init` tool (see the plan-tree section below) — the learner SEES this tree live in a side panel, and Phase 3 walks it node by node with `plan_set_current` / `plan_mark_done`. Keep it small: few nodes, short labels — a map, not the territory.
2. **The dependency map.** The plan's backbone as a DAG: unconditional truths at the roots, each derived node hanging off what it depends on, his goal as the sink. Write it once with the `plan_init` tool (see the plan-map section below) — the learner SEES it live in a side panel, and where the lesson stands derives from your checks (`nodeId`), not from your bookkeeping. Keep it small: few nodes, short labels — a map, not the territory.
**Stress-test the roots before presenting.** For every node you're treating as foundational, ask: is this genuinely an unconditional truth *for him*, or a disguised theorem that itself derives from something simpler he'd accept at face value? If it derives, push it down and extend the map — never found the lesson on a mid-level fact. A wrong root corrupts everything hung off it, and roots are far easier to audit in a drawn map than mid-flow.
+62 -13
View File
@@ -1,5 +1,5 @@
import { tool, type ToolSet } from "ai";
import { askInputSchema, quizInputSchema } from "../core/question-core.ts";
import { askInputSchema, quizInputObject, quizInputProblems, quizInputSchema } from "../core/question-core.ts";
import type { JobRecord } from "../core/contracts.ts";
import type { JobStore } from "../core/ports.ts";
import { jobTools, type DemoInput, type ResearchInput, type VisualInput } from "./tools/jobs.ts";
@@ -10,14 +10,20 @@ export { jobTools };
/**
* The teacher's tools, composed per request by createTeacherTools.
*
* - questionTools (quiz / ask_user_question): CLIENT-SIDE tools (no `execute`).
* The tool call streams to the browser in `input-available` state; the
* learner answers in the dock; the client grades via question-core and
* sends the verdict with addToolOutput. The input schemas live in
* core/question-core (the question contract) — parameter names mirror
* the prompt docs exactly; keep them in sync.
* - planTools (src/agent/tools/plan.ts): SERVER-SIDE, mutate the chat's plan
* tree (needs the chatId closure — hence the per-request factory).
* - questionTools / questionToolsFor (quiz / ask_user_question): CLIENT-SIDE
* tools (no `execute`). The tool call streams to the browser in
* `input-available` state; the learner answers in the dock; the client
* grades via question-core and sends the verdict with addToolOutput. The
* input schemas live in core/question-core (the question contract) —
* parameter names mirror the prompt docs exactly; keep them in sync.
* questionToolsFor adds the per-session plan-nodeId validation: an invalid
* nodeId NEVER reaches the learner — the SDK returns the validation error
* to the teacher as a tool result and it retries (same loop as the
* grading rules). It reads the LIVE record at validation time, so a
* plan_init earlier in the same turn already counts.
* - planTools (src/agent/tools/plan.ts): SERVER-SIDE — the single author-once
* plan_init (mermaid → structured tree; re-callable rewrite). Needs the
* chatId closure — hence the per-request factory.
* - jobTools (src/agent/tools/jobs.ts): SERVER-EXECUTED dispatch — the call
* resolves immediately with a fire-and-forget ack, the background runner
* does the work, and the result arrives later as a steer message
@@ -54,6 +60,49 @@ export const questionTools = {
ask_user_question: askUserQuestionTool,
};
/**
* Per-session question tools: the quiz schema gains the dynamic plan-nodeId
* validation on top of question-core's shared authoring rules (chained
* superRefines — the grading contract is untouched). The check reads the
* LIVE chat record, so rewrites mid-turn are honored, and with no tree yet
* (probe phase) every nodeId is rejected — ad-hoc checks must omit it.
* ask_user_question is untouched: it never carries nodeId (not a check).
*/
export function questionToolsFor(ctx: Pick<PlanToolContext, "chatId" | "chatStore">): ToolSet {
const quizInputWithNodeValidation = quizInputObject
.superRefine((input, add) => {
for (const problem of quizInputProblems(input)) {
add.addIssue({ code: "custom", message: problem });
}
})
.superRefine((input, add) => {
if (typeof input.nodeId !== "string" || input.nodeId.length === 0) return;
const record = ctx.chatStore.getChat(ctx.chatId);
const tree = record?.tree;
const known = tree?.nodes.map((n) => n.id) ?? [];
if (!known.includes(input.nodeId)) {
add.addIssue({
code: "custom",
message:
`nodeId "${input.nodeId}" matches no node in this session's plan map. ` +
(known.length > 0
? `Copy one of your plan_init slugs exactly (${known.slice(0, 5).join(", ")}${known.length > 5 ? ", …" : ""}), or omit nodeId for an ad-hoc check.`
: "No plan map exists yet — omit nodeId (ad-hoc checks only until you call plan_init)."),
});
}
});
const quizWithNodeValidation = tool({
description: quizTool.description,
inputSchema: quizInputWithNodeValidation,
});
return {
quiz: quizWithNodeValidation,
ask_user_question: askUserQuestionTool,
};
}
export interface TeacherToolContext extends PlanToolContext {
/** Job-tool wiring (sub-agent dispatch): the job store + the runner's
* spawn seam. The composition root injects both. */
@@ -65,13 +114,13 @@ export interface TeacherToolContext extends PlanToolContext {
}
/**
* Per-request tool registry. Plan tools close over the ctx (chatId + the
* injected ChatStore) for persistence; question tools are context-free;
* job tools close over the job store + spawn seam.
* Per-request tool registry. Plan tools and question tools close over the
* ctx (chatId + the injected ChatStore — the latter also powers the quiz
* nodeId validation); job tools close over the job store + spawn seam.
*/
export function createTeacherTools(ctx: TeacherToolContext): ToolSet {
return {
...questionTools,
...questionToolsFor(ctx),
...planTools(ctx),
...jobTools({ chatId: ctx.chatId, jobStore: ctx.jobStore, spawn: ctx.spawn }),
};
+132
View File
@@ -0,0 +1,132 @@
/**
* Mermaid → PlanTree authoring format (the author-once protocol, 2026-09-03).
*
* The teacher writes the session map as a mermaid `graph TD` block — the
* format models are most fluent in — and plan_init canonicalizes it into the
* structured PlanTree. A CONSTRAINED SUBSET, parsed by hand: deterministic,
* dependency-free, precise line-numbered errors the teacher can act on (the
* same validate-and-retry loop as the question schemas). Not the mermaid
* runtime — the server never renders, it only needs the graph.
*
* Accepted syntax (anything else → an error naming the line):
* graph TD | graph TB | flowchart TD | flowchart TB (case-insensitive)
* %% comment lines
* node — bare id (title falls back to the id)
* id[title] — square-bracket label
* id("title") — paren label
* a --> b — requires edge (from = prerequisite); bare endpoints
* register as nodes; forward references are fine
* a[title] --> b[title]
*
* Node ids are permanent slugs: ^[a-z0-9]+(-[a-z0-9]+)*$ (checks reference
* them via the quiz nodeId). Labels are single-line titles.
*/
import type { PlanEdge, PlanNode } from "@/src/core";
export interface ParsedPlan {
nodes: PlanNode[];
edges: PlanEdge[];
}
export interface PlanParseResult {
ok: boolean;
/** All problems, each prefixed with its 1-based line number. */
problems: string[];
plan?: ParsedPlan;
}
const HEADER_RE = /^(graph|flowchart)\s+(td|tb)\s*$/i;
const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
/** One edge endpoint: `id`, `id[title]`, or `id("title")`. */
// Case-tolerant on the id: register() then enforces the lowercase slug convention
// with a SPECIFIC message (an "UPPER" id reaches the slug check, not a generic
// parse error — the most common authoring mistake).
const ENDPOINT_RE = /^([A-Za-z0-9][A-Za-z0-9-]*?)\s*(?:\[([^\[\]]*)\]|\(\s*"([^"]*)"\s*\)|\(([^()]*)\))?$/;
interface Endpoint {
id: string;
label?: string;
}
function parseEndpoint(text: string): Endpoint | null {
const m = text.trim().match(ENDPOINT_RE);
if (!m || !m[1]) return null;
return { id: m[1], label: (m[2] ?? m[3] ?? m[4] ?? "").trim() };
}
/** Parse the mermaid subset. Collects ALL problems (never just the first). */
export function parseMermaidPlan(mermaid: string): PlanParseResult {
const problems: string[] = [];
const lines = mermaid.split(/\r?\n/);
// Header: required, first non-empty non-comment line.
const first = lines.findIndex((l) => l.trim().length > 0 && !l.trim().startsWith("%%"));
if (first === -1) {
return { ok: false, problems: ["The plan is empty — expected a `graph TD` block with nodes and `-->` requires-edges."] };
}
const header = lines[first]?.trim() ?? "";
if (!HEADER_RE.test(header)) {
problems.push(`line ${first + 1}: expected the header \`graph TD\` (or flowchart TD/TB) first, got \`${header}\`.`);
}
const nodes = new Map<string, string>(); // id → title (first label wins)
const edges: PlanEdge[] = [];
const seenEdges = new Set<string>();
const register = ({ id, label }: Endpoint, lineNo: number): void => {
if (!SLUG_RE.test(id)) {
problems.push(
`line ${lineNo}: node id \`${id}\` must be a lowercase slug (a-z, 0-9, hyphens — e.g. \`chain-rule-intuition\`); ids are permanent and checks reference them.`,
);
return;
}
if (!nodes.has(id)) nodes.set(id, label && label.length > 0 ? label : id);
else if (label && label.length > 0 && nodes.get(id) === id) nodes.set(id, label);
};
for (let i = first + 1; i < lines.length; i++) {
const line = lines[i]?.trim() ?? "";
const no = i + 1;
if (line.length === 0 || line.startsWith("%%")) continue;
const arrows = line.split("-->");
if (arrows.length === 2) {
const from = parseEndpoint(arrows[0] ?? "");
const to = parseEndpoint(arrows[1] ?? "");
if (!from || !to) {
problems.push(`line ${no}: can't read the edge \`${line}\` — expected \`a[title] --> b[title]\`.`);
continue;
}
register(from, no);
register(to, no);
if (from.id === to.id) {
problems.push(`line ${no}: self-loop \`${from.id} --> ${to.id}\` — a node can't require itself.`);
continue;
}
const key = `${from.id}->${to.id}`;
if (!seenEdges.has(key)) {
seenEdges.add(key);
edges.push({ from: from.id, to: to.id });
}
} else if (arrows.length > 2) {
problems.push(`line ${no}: chained edges \`${line}\` — write one edge per line (the plan is a map, not a sentence).`);
} else {
const node = parseEndpoint(line);
if (!node) {
problems.push(
`line ${no}: can't parse \`${line}\` — the plan accepts node lines (\`slug[title]\` — ids are lowercase slugs: a-z, 0-9, hyphens) and requires-edges (\`a --> b\`) only; subgraphs, styles, classes, and other mermaid features are not part of the subset.`,
);
continue;
}
register(node, no);
}
}
const plan: ParsedPlan = {
nodes: [...nodes.entries()].map(([id, title]) => ({ id, title })),
edges,
};
if (problems.length > 0) return { ok: false, problems };
if (plan.nodes.length === 0) return { ok: false, problems: ["No nodes found — the plan needs at least one."] };
return { ok: true, problems: [], plan };
}
+53 -158
View File
@@ -2,18 +2,8 @@ import { tool, type ToolSet } from "ai";
import { z } from "zod";
import type { PlanToolResult, PlanTree } from "../../core/contracts.ts";
import type { ChatStore } from "../../core/ports.ts";
import {
addEdge,
addNode,
createTree,
emptyTree,
markDone,
PlanTreeError,
removeEdge,
removeNode,
setCurrent,
updateNode,
} from "../../core/plan-tree.ts";
import { createTree, emptyTree, PlanTreeError } from "../../core/plan-tree.ts";
import { parseMermaidPlan } from "./mermaid-plan.ts";
/** What the plan tools close over (the plan-tree half of the tool context). */
export interface PlanToolContext {
@@ -23,161 +13,66 @@ export interface PlanToolContext {
}
/**
* Plan-tree tools — W1 workstream (docs/plan.md Wave 1; src/core/contracts.ts
* "Plan tree"). SERVER-SIDE tools WITH execute: read the chat record, apply a
* pure validated op from src/core/plan-tree.ts, persist via saveTree, and
* return PlanToolResult — the FULL updated tree every time, so the UI tree
* panel renders the latest state straight from the transcript's tool outputs.
* The plan tool — AUTHOR-ONCE protocol (2026-09-03 design pass): the teacher
* WRITES the map and never tracks progress. One tool, plan_init, takes the
* whole dependency map as a mermaid `graph TD` block:
*
* Edges are `requires` edges: from = prerequisite, to = dependent
* ("from must be understood before to").
* - call it ONCE at the probe→teach seam (the call fires the phase divider)
* - statuses (done / current / upcoming) are DERIVED from check outcomes
* (contracts.ts derivePlanStatuses) — the teacher never declares them
* - re-call it any time the map is wrong: the new block replaces the tree
* wholesale. Node slugs are permanent — reused ids keep their derived
* done status, so a mid-lesson rewrite never resets honest progress
* - checks name the node they assess (quiz nodeId, validated against the
* live tree at the call boundary) — that tag is the only thing statuses
* derive from
*
* The former mutation tools (add/update/remove node/edge, set_current,
* mark_done) are gone by design: restructuring is a rewrite, tracking is
* derived. SERVER-SIDE with execute: parse → validate → persist → return
* the FULL canonicalized tree (PlanToolResult), so the tree panel renders the
* latest state straight from the transcript's tool outputs.
*/
const nodeId = z
.string()
.min(1)
.describe("Stable node slug, e.g. 'chain-rule-intuition'. Ids are permanent — never reuse or rename one mid-session.");
const nodeSchema = z.object({
id: nodeId.describe("Stable node slug, e.g. 'chain-rule-intuition'. Ids are permanent — never reuse or rename one mid-session."),
title: z.string().min(1).describe("Short label for the tree panel — at most ~6 words."),
summary: z.string().optional().describe("1-2 sentences: what this node covers."),
});
const edgeSchema = z.object({
from: nodeId.describe("Prerequisite node id (must be understood before `to`)."),
to: nodeId.describe("Node id that depends on `from`."),
});
/**
* Shared execute wrapper: load record → apply pure op → persist → PlanToolResult.
* PlanTreeError and missing chats become {ok:false} with the current (or
* empty) tree, so the model can see what it's working with and fix the call.
*/
async function runPlanOp(
ctx: PlanToolContext,
op: (tree: PlanTree) => PlanTree,
): Promise<PlanToolResult> {
const { chatId, chatStore } = ctx;
const record = chatStore.getChat(chatId);
if (!record) return { ok: false, error: `Chat not found: ${chatId}`, tree: emptyTree() };
const current = record.tree ?? emptyTree();
try {
const next = op(current);
chatStore.saveTree(chatId, next);
return { ok: true, tree: next };
} catch (err) {
if (err instanceof PlanTreeError) return { ok: false, error: err.message, tree: current };
throw err;
}
}
export function planTools(ctx: PlanToolContext): ToolSet {
return {
plan_init: tool({
description:
"Initialize this session's plan tree — the dependency map of the lesson, which the learner sees live in a side panel. " +
"Call ONCE, after probing, before teaching begins: pass the full initial node set and the `requires` edges between them " +
"(edge direction: from = prerequisite, to = dependent — from must be understood before to). The tree must be a DAG (no cycles). " +
"Refuses to run if a tree already exists — after that, use the other plan_* tools to evolve it.",
"Write or REWRITE this session's plan map — the dependency graph the learner sees live in a side panel. " +
"Call once after probing, before teaching begins; re-call whenever the map is wrong (the new block replaces the old tree). " +
"A mermaid `graph TD` block: one node per line (`slug[Short Title]` — slugs are permanent lowercase ids), `-->` edges meaning " +
"'from must be understood before to'. 5–15 nodes: a map, not a syllabus — one reasoning step per node, compress. " +
"Every check you fire names the node it assesses via `nodeId`; where the lesson stands derives from those outcomes.",
inputSchema: z.object({
nodes: z.array(nodeSchema).min(1).describe("The initial nodes. A map, not a syllabus: one reasoning step per node."),
edges: z
.array(edgeSchema)
.optional()
.describe("Initial `requires` edges between the nodes. Edge direction: from = prerequisite, to = dependent."),
mermaid: z
.string()
.min(1)
.describe(
"A mermaid `graph TD` block, e.g.:\ngraph TD\n primitives[Number primitives] --> operators[Arithmetic operators]\n operators --> expressions[Evaluating expressions]\n" +
"Node lines: `slug[Title]`. Edge lines: `slug --> slug` (from = prerequisite). No subgraphs, styles, classes, or other mermaid features.",
),
}),
execute: async ({ nodes, edges }): Promise<PlanToolResult> => {
const record = ctx.chatStore.getChat(ctx.chatId);
if (!record) return { ok: false, error: `Chat not found: ${ctx.chatId}`, tree: emptyTree() };
const existing = record.tree;
if (existing && existing.nodes.length > 0) {
return {
ok: false,
error: "Tree already initialized — use the mutation tools",
tree: existing,
};
execute: async ({ mermaid }): Promise<PlanToolResult> => {
const { chatId, chatStore } = ctx;
const record = chatStore.getChat(chatId);
if (!record) return { ok: false, error: `Chat not found: ${chatId}`, tree: emptyTree() };
const current = record.tree ?? emptyTree();
const parsed = parseMermaidPlan(mermaid);
if (!parsed.ok || !parsed.plan) {
// The parser collects every problem; the teacher fixes and retries.
return { ok: false, error: parsed.problems.join("\n"), tree: current };
}
try {
// createTree validates the structure (duplicate ids, missing
// edge endpoints, self-loops, cycles → PlanTreeError).
const next = createTree(parsed.plan.nodes, parsed.plan.edges);
chatStore.saveTree(chatId, next);
return { ok: true, tree: next };
} catch (err) {
if (err instanceof PlanTreeError) return { ok: false, error: err.message, tree: current };
throw err;
}
return runPlanOp(ctx, () => createTree(nodes, edges ?? []));
},
}),
plan_add_node: tool({
description:
"Add one node to the plan tree. Optionally pass `parents`: node ids this new node depends on (a `requires` edge parent → this node is " +
"created for each; a parent must be understood before this node). Parents must already exist; the result must stay a DAG.",
inputSchema: z.object({
id: nodeId,
title: z.string().min(1).describe("Short label for the tree panel — at most ~6 words."),
summary: z.string().optional().describe("1-2 sentences: what this node covers."),
parents: z
.array(nodeId)
.optional()
.describe("Ids of prerequisite nodes — each gets a `requires` edge pointing to this node. All must already exist."),
}),
execute: async ({ id, title, summary, parents }): Promise<PlanToolResult> =>
runPlanOp(ctx, (tree) => addNode(tree, { id, title, ...(summary !== undefined ? { summary } : {}) }, parents)),
}),
plan_update_node: tool({
description:
"Update a node's `title` and/or `summary`. The node must exist; the id never changes. Use this to sharpen a vague node, not to change its meaning.",
inputSchema: z
.object({
id: nodeId,
title: z.string().min(1).optional().describe("New short label (at most ~6 words)."),
summary: z.string().optional().describe("New 1-2 sentence summary."),
})
.refine((v) => v.title !== undefined || v.summary !== undefined, {
message: "Pass at least one of `title` or `summary` — an update with neither changes nothing.",
}),
execute: async ({ id, title, summary }): Promise<PlanToolResult> =>
runPlanOp(ctx, (tree) => updateNode(tree, id, { ...(title !== undefined ? { title } : {}), ...(summary !== undefined ? { summary } : {}) })),
}),
plan_remove_node: tool({
description:
"Remove a node from the plan tree — prune what proves unnecessary. Cascades: every edge touching the node (both directions), its current " +
"status, and its done status are removed with it.",
inputSchema: z.object({ id: nodeId }),
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => removeNode(tree, id)),
}),
plan_add_edge: tool({
description:
"Add a `requires` edge to the plan tree. Direction: from = prerequisite, to = dependent — `from` must be understood before `to`. " +
"Both nodes must exist; self-loops, duplicate edges, and anything that would create a cycle are rejected.",
inputSchema: z.object({
from: nodeId.describe("Prerequisite node id (must be understood before `to`)."),
to: nodeId.describe("Dependent node id (requires `from`)."),
}),
execute: async ({ from, to }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => addEdge(tree, from, to)),
}),
plan_remove_edge: tool({
description:
"Remove an existing `requires` edge from the plan tree (the nodes stay). Use when a dependency turns out to be wrong or unnecessary.",
inputSchema: z.object({
from: nodeId.describe("Prerequisite end of the edge to remove."),
to: nodeId.describe("Dependent end of the edge to remove."),
}),
execute: async ({ from, to }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => removeEdge(tree, from, to)),
}),
plan_set_current: tool({
description:
"Set the CURRENT node — where the lesson is right now. Call it the moment you START teaching a node, so the learner sees their position " +
"on the map. The node must exist. This marks position only; it does not mark anything done.",
inputSchema: z.object({ id: nodeId.describe("The node you are starting to teach now.") }),
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => setCurrent(tree, id)),
}),
plan_mark_done: tool({
description:
"Mark a node DONE — and only when the learner has DEMONSTRATED it (a correct check), not when you finished explaining it. " +
"The node must exist. Idempotent.",
inputSchema: z.object({ id: nodeId.describe("The node the learner just demonstrated.") }),
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => markDone(tree, id)),
}),
};
}
}