Diagnosis (2026-09-11 user testing, minimal-effort GLM): sessions stuck on 'plan' forever. Two causes: (1) the three-phase view read the stored tree's currentNodeId, which nothing ever writes post author-once (2026-09-03) — a structural dead seam; (2) the teacher stochastically left quiz.nodeId untagged, and done-by-quiz-result semantics would have falsely completed nodes anyway. The redesign (docs/probe-teach-split.md) abolishes derived occupancy in favor of explicit events: - Two agents over one transcript: createProberAgent (quiz without a nodeId field, ask, probe_done) and createTeacherAgent (full toolset, plan_init onward). The chat-handler construction branch keys on a probe_done part in the transcript. MODELS.prober added. - probe_done: server-side seam tool — carries the learner assessment (strands + free-form edge read), refuses while a question is open or the probe is already concluded, and queues a handoff steer through the generalized wake pipeline (steers now dedupe by id, not jobId; job finalization only for job steers). The teacher auto-wakes and authors the plan; the learner sees the assessment via the probe-done card. - phases: probe ends at a concluded probe_done, plan ends at a successful plan_init — strictly sequential, no skipping, no legacy compatibility (data wiped at the pivot per doctrine). - Plan map = position, not completion: derivePlanStatuses reads only tagged quiz CALLS (state/outcome feed nothing); current = latest tagged node with consecutive duplicates collapsed, visited = earlier distinct stays (a revisit stays in both — current wins at render). PlanTree is structure-only; currentNodeId/doneNodeIds and the dead mutation helpers are gone. No fallback current. - Prompts split per agent (prompts/prober/, prompts/teacher/ over the trimmed shared base); graph-context injection removed entirely (shelved, docs/probe-teach-split.md §5); knowledge-graph context no longer reaches either agent. - Plan blocks are full-only snapshots at plan_init (neighborhood machinery retired; the persistent DAG window is the future UI wave); usage capture unchanged. Gates: tsc clean, 294/294 tests (phases/plan-tree/plan-blocks/question- tools rewritten to the new semantics; probe-done + handoff-wake tests added), lint, build. Live GLM smoke PASS: prober concluded with an honest assessment, teacher auto-woke, authored a 10-node plan with the block attached, then tagged checks on slope-instinct → secant derived current/ visited exactly as designed; grading honest both ways (driver off-by-one proved a wrong answer grades false).
133 lines
5.3 KiB
TypeScript
133 lines
5.3 KiB
TypeScript
import type { PlanEdge, PlanNode, PlanTree } from "./contracts.ts";
|
|
|
|
/**
|
|
* Pure, validated plan-tree operations (vision §2 "the formal plan tree").
|
|
*
|
|
* Every function takes a tree and returns a NEW tree — never mutates its
|
|
* input. All validation throws PlanTreeError with a message written for the
|
|
* agent (it flows straight back as a tool-result error), stating exactly what
|
|
* is wrong and which id/edge is at fault.
|
|
*
|
|
* Invariants enforced everywhere:
|
|
* - Node ids are unique and non-empty; every edge endpoint references an
|
|
* existing node.
|
|
* - The structure is a DAG: no self-loops, no duplicate edges, no cycles.
|
|
* - `version` increments on every successful STATE-CHANGING op. True no-ops
|
|
* (setCurrent to the already-current node, markDone of an already-done
|
|
* node) return the input tree unchanged — version drives UI re-animation,
|
|
* so a non-change must not tick it. createTree always starts at version 1.
|
|
*/
|
|
|
|
/** Error thrown by every op on invalid input. Message is agent-readable. */
|
|
export class PlanTreeError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = "PlanTreeError";
|
|
}
|
|
}
|
|
|
|
/** An empty, never-stored tree used as the seed before plan_init runs. */
|
|
export function emptyTree(): PlanTree {
|
|
return { nodes: [], edges: [], version: 0 };
|
|
}
|
|
|
|
// ─── validation helpers ──────────────────────────────────────────────────────
|
|
|
|
function assertValidNode(node: PlanNode): void {
|
|
if (!node || typeof node.id !== "string" || node.id.trim() === "") {
|
|
throw new PlanTreeError("Every node needs a non-empty `id` (a stable slug like 'chain-rule-intuition').");
|
|
}
|
|
if (typeof node.title !== "string" || node.title.trim() === "") {
|
|
throw new PlanTreeError(`Node "${node.id}" needs a non-empty \`title\`.`);
|
|
}
|
|
}
|
|
|
|
function nodeMap(nodes: PlanNode[]): Map<string, PlanNode> {
|
|
const map = new Map<string, PlanNode>();
|
|
for (const node of nodes) {
|
|
assertValidNode(node);
|
|
if (map.has(node.id)) {
|
|
throw new PlanTreeError(`Duplicate node id "${node.id}" — node ids must be unique.`);
|
|
}
|
|
map.set(node.id, node);
|
|
}
|
|
return map;
|
|
}
|
|
|
|
function requireNode(map: Map<string, PlanNode>, id: string, what: string): void {
|
|
if (!map.has(id)) {
|
|
throw new PlanTreeError(`${what} references unknown node id "${id}" — it is not in the tree.`);
|
|
}
|
|
}
|
|
|
|
function edgeKey(from: string, to: string): string {
|
|
return `${from}\u0000${to}`;
|
|
}
|
|
|
|
/**
|
|
* Would adding edge from→to create a cycle? Walk forward from `to` along
|
|
* existing edges; if we can reach `from`, the new edge closes a loop.
|
|
*/
|
|
function createsCycle(edges: PlanEdge[], from: string, to: string): boolean {
|
|
const adjacency = new Map<string, string[]>();
|
|
for (const e of edges) {
|
|
const list = adjacency.get(e.from);
|
|
if (list) list.push(e.to);
|
|
else adjacency.set(e.from, [e.to]);
|
|
}
|
|
const stack = [to];
|
|
const seen = new Set<string>();
|
|
while (stack.length > 0) {
|
|
const current = stack.pop()!;
|
|
if (current === from) return true;
|
|
if (seen.has(current)) continue;
|
|
seen.add(current);
|
|
for (const next of adjacency.get(current) ?? []) stack.push(next);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** Full edge validation against existing nodes/edges: endpoints exist, no self-loop, no duplicate, acyclic. */
|
|
function assertValidEdge(from: string, to: string, nodes: PlanNode[], existingEdges: PlanEdge[]): void {
|
|
const map = nodeMap(nodes); // also re-validates nodes on createTree
|
|
requireNode(map, from, "Edge `from`");
|
|
requireNode(map, to, "Edge `to`");
|
|
if (from === to) {
|
|
throw new PlanTreeError(`Edge "${from}" → "${to}" is a self-loop — a node can't require itself.`);
|
|
}
|
|
if (existingEdges.some((e) => e.from === from && e.to === to)) {
|
|
throw new PlanTreeError(`Edge "${from}" → "${to}" already exists — duplicate edges are not allowed.`);
|
|
}
|
|
if (createsCycle(existingEdges, from, to)) {
|
|
throw new PlanTreeError(
|
|
`Edge "${from}" → "${to}" would create a cycle: "${to}" already leads (directly or transitively) back to "${from}". ` +
|
|
`"from" must be understood before "to" — the tree is a DAG.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
// ─── ops ─────────────────────────────────────────────────────────────────────
|
|
|
|
/** Build a fresh tree (version 1) from node and edge lists, validating all invariants. */
|
|
export function createTree(nodes: PlanNode[], edges: PlanEdge[]): PlanTree {
|
|
const map = nodeMap(nodes);
|
|
for (const e of edges) {
|
|
requireNode(map, e.from, "Edge `from`");
|
|
requireNode(map, e.to, "Edge `to`");
|
|
}
|
|
const accepted: PlanEdge[] = [];
|
|
for (const e of edges) {
|
|
// Each edge is checked against the ones already accepted, so any
|
|
// violation names the culprit edge.
|
|
assertValidEdge(e.from, e.to, nodes, accepted);
|
|
accepted.push({ from: e.from, to: e.to });
|
|
}
|
|
return { nodes: nodes.map((n) => ({ ...n })), edges: accepted, version: 1 };
|
|
}
|
|
|
|
// The per-node mutation ops (addNode/updateNode/removeNode/addEdge/removeEdge/
|
|
// setCurrent/markDone) were deleted with the author-once protocol
|
|
// (2026-09-03) and their dead exports removed with the 2026-09-11 pivot: the
|
|
// tree carries structure ONLY — no progress fields exist to mutate
|
|
// (docs/probe-teach-split.md §3). Restructuring is a plan_init rewrite.
|