Shell/core import law: public API barrels + ESLint enforcement (stage 2)
The shell now imports through exactly two barrels, enforced by
import/no-restricted-paths (npm run lint):
components/** -> "@/src/core" (pure core API, browser-safe)
app/** -> "@/src/core" + "@/src/server" (server entries)
Zone violations are lint errors with architecture-pointer messages; the
pure-core modules (contracts, question-core, plan-tree, phases, pending,
math-delims, ui-message) may never import agent/server/store.
Supporting moves (direction: IO layers -> core):
- core/index.ts: the core public API barrel
- core/ui-message.ts: moved from src/agent (it was shell-facing all along)
- quiz/ask input zod schemas moved agent/tools -> core/question-core
(the question contract, alongside the grading logic)
- ChatRecord/ChatSummary moved store/chats -> core/contracts (single schema)
- GraphSnapshot/NodeStateClass moved core/graph -> core/contracts (the
/api/graph payload IS a contract; the pure renderer needs only these)
- src/server/{chats,graph,jobs}.ts + index.ts: thin server entries for the
transport layer; GET /api/graph's fold side-effect now lives behind
graphView() instead of inline in the route
Gates: tsc clean, 190/190 tests, eslint clean (law verified to fire on
store/agent/subpath violations), production build clean.
(Repo repair en route: a git object (app/chat/[id] tree) was missing from
the object store — reconstructed byte-exactly via mktree from its blob;
the broken node_modules that stalled the build was cleanly reinstalled.)
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { handleChatRequest } from "@/src/server/chat-handler";
|
||||
import { handleChatRequest } from "@/src/server";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
return handleChatRequest(req);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getChat } from "@/src/store/chats";
|
||||
import { getChat } from "@/src/server";
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createChat, listChats, titleFromPrompt } from "@/src/store/chats";
|
||||
import { createChat, listChats, titleFromPrompt } from "@/src/server";
|
||||
|
||||
export async function GET() {
|
||||
return Response.json({ chats: listChats() });
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { foldStaleChats, graphSnapshot } from "@/src/core/graph";
|
||||
import { graphView } from "@/src/server";
|
||||
|
||||
/**
|
||||
* The home graph view's data endpoint (W4; vision §1 "Home page"). Folds any
|
||||
* chat whose updatedAt outstrips its emission checkpoint first (partial
|
||||
* sessions deposit value), then returns nodes, edges, derived node states,
|
||||
* and the session titles/provenance for node click-through.
|
||||
* The home graph view's data endpoint (W4; vision §1 "Home page") — thin
|
||||
* transport: the server entry (src/server/graph.ts) folds stale chats and
|
||||
* returns nodes, edges, derived node states, and session provenance.
|
||||
*/
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
foldStaleChats();
|
||||
return Response.json(graphSnapshot());
|
||||
return Response.json(graphView());
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { listJobs } from "@/src/store/jobs";
|
||||
import { listJobs } from "@/src/server";
|
||||
|
||||
/**
|
||||
* Job status polling endpoint (contracts.ts "THE ASYNC PROTOCOL" §4): the
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Chat } from "@/components/chat";
|
||||
import { getChat } from "@/src/store/chats";
|
||||
import type { TeacherUIMessage } from "@/src/agent/ui-message";
|
||||
import type { TeacherUIMessage } from "@/src/core";
|
||||
import { getChat } from "@/src/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
type PluginConfig,
|
||||
} from "streamdown";
|
||||
import { MermaidError } from "@/components/mermaid-error.tsx";
|
||||
import { transformMathDelimiters } from "@/src/core/math-delims.ts";
|
||||
import { transformMathDelimiters } from "@/src/core";
|
||||
|
||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
} from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
import { transformMathDelimiters } from "@/src/core/math-delims";
|
||||
import { transformMathDelimiters } from "@/src/core";
|
||||
import { mermaidOptions, streamdownPlugins } from "./message";
|
||||
import { Shimmer } from "./shimmer";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MessageResponse } from "@/components/ai-elements/message";
|
||||
import type { QuestionAnswerData } from "@/src/core/question-core";
|
||||
import type { QuestionAnswerData } from "@/src/core";
|
||||
|
||||
/**
|
||||
* Static rendering of an answered question (tool part in `output-available`).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ChatActionsContext } from "@/components/chat";
|
||||
import type { ArtifactPartProps, DemoResult, JobRecord } from "@/src/core/contracts";
|
||||
import type { ArtifactPartProps, DemoResult, JobRecord } from "@/src/core";
|
||||
|
||||
/**
|
||||
* Demo artifact card (W6): while the part is input-available, a job activity
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { ArtifactPartProps } from "@/src/core/contracts";
|
||||
import type { ArtifactPartProps } from "@/src/core";
|
||||
import { DemoCard } from "@/components/artifacts/demo-card";
|
||||
import { JobCard } from "@/components/artifacts/job-card";
|
||||
import { PlanDivider } from "@/components/artifacts/plan-divider";
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useContext, useEffect, useRef, useState } from "react";
|
||||
import { MessageResponse } from "@/components/ai-elements/message";
|
||||
import { ChatActionsContext } from "@/components/chat";
|
||||
import type { ArtifactPartProps, JobRecord, ResearchResult } from "@/src/core/contracts";
|
||||
import type { ArtifactPartProps, JobRecord, ResearchResult } from "@/src/core";
|
||||
|
||||
/**
|
||||
* The research job card (contracts.ts "THE ASYNC PROTOCOL" §4).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ArtifactPartProps, PlanToolResult } from "@/src/core/contracts";
|
||||
import type { ArtifactPartProps, PlanToolResult } from "@/src/core";
|
||||
|
||||
/**
|
||||
* The probe→teach divider (vision §2 "Two phases, clearly separated").
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import type { ArtifactPartProps, VisualResult } from "@/src/core/contracts";
|
||||
import type { ArtifactPartProps, VisualResult } from "@/src/core";
|
||||
import { JobActivityCard } from "@/components/artifacts/demo-card";
|
||||
|
||||
/**
|
||||
|
||||
+4
-7
@@ -20,11 +20,8 @@ import { Composer } from "@/components/composer";
|
||||
import { QuestionDock } from "@/components/question-dock";
|
||||
import { SidebarToggle } from "@/components/sidebar";
|
||||
import { TreePanel } from "@/components/tree-panel";
|
||||
import type { TeacherUIMessage } from "@/src/agent/ui-message";
|
||||
import type { ArtifactPartProps } from "@/src/core/contracts";
|
||||
import type { QuestionAnswerData } from "@/src/core/question-core";
|
||||
import { findPendingJobCall, findPendingToolCall } from "@/src/core/pending";
|
||||
import { phaseAt } from "@/src/core/phases";
|
||||
import type { ArtifactPartProps, QuestionAnswerData, TeacherUIMessage } from "@/src/core";
|
||||
import { findPendingJobCall, findPendingToolCall, phaseAt } from "@/src/core";
|
||||
|
||||
/** One width for everything: transcript, cards, and the bottom blob share this column. */
|
||||
const COLUMN = "mx-auto w-full max-w-3xl px-4";
|
||||
@@ -101,7 +98,7 @@ export function Chat({
|
||||
) {
|
||||
void sendMessage();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only by design
|
||||
// mount-only by design
|
||||
}, []);
|
||||
|
||||
const pending = findPendingToolCall(messages);
|
||||
@@ -318,7 +315,7 @@ function DockOverlay({
|
||||
setExpanded(isAtBottom);
|
||||
if (isAtBottom) void scrollToBottom();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- fire only when a NEW question lands
|
||||
// fire only when a NEW question lands
|
||||
}, [pendingId]);
|
||||
|
||||
// ── Collapse state machine with hysteresis ──
|
||||
|
||||
@@ -20,9 +20,7 @@ import Link from "next/link";
|
||||
import { WaypointsIcon } from "lucide-react";
|
||||
import Graph from "graphology";
|
||||
import forceAtlas2 from "graphology-layout-forceatlas2";
|
||||
import type { GraphNode } from "@/src/core/contracts";
|
||||
import type { GraphSnapshot, NodeStateClass } from "@/src/core/graph";
|
||||
import { seededRandom } from "@/src/core/question-core";
|
||||
import { seededRandom, type GraphNode, type GraphSnapshot, type NodeStateClass } from "@/src/core";
|
||||
|
||||
/** Per-state visuals: color token + node size (WebGL wants hex, not oklch). */
|
||||
const STATE_TOKENS: Record<NodeStateClass, { cssVar: string; size: number }> = {
|
||||
|
||||
@@ -5,7 +5,6 @@ import { ArrowDownIcon, ChevronRightIcon, PlayIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { MessageResponse } from "@/components/ai-elements/message";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { AskToolInput, QuizToolInput } from "@/src/agent/tools";
|
||||
import {
|
||||
buildAnswer,
|
||||
coerceCorrectAnswer,
|
||||
@@ -14,10 +13,12 @@ import {
|
||||
seededRandom,
|
||||
shuffleOptions,
|
||||
type AnswerRequest,
|
||||
type AskToolInput,
|
||||
type QuestionAnswerData,
|
||||
type QuestionData,
|
||||
type QuestionMode,
|
||||
} from "@/src/core/question-core";
|
||||
type QuizToolInput,
|
||||
} from "@/src/core";
|
||||
|
||||
/**
|
||||
* The question dock — a pending quiz/ask REPLACES the chat composer: the
|
||||
|
||||
@@ -6,7 +6,7 @@ import { usePathname, useRouter } from "next/navigation";
|
||||
import { PanelLeftCloseIcon, PanelLeftOpenIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ChatSummary } from "@/src/store/chats";
|
||||
import type { ChatSummary } from "@/src/core";
|
||||
|
||||
/**
|
||||
* Toggleable sidebar — NOT a modal drawer: no backdrop, no focus theft. It
|
||||
|
||||
@@ -3,12 +3,7 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { CheckIcon, ChevronsRightIcon, ListTreeIcon } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
planNodeStatus,
|
||||
type PlanNode,
|
||||
type PlanNodeStatus,
|
||||
type PlanTree,
|
||||
} from "@/src/core/contracts";
|
||||
import { planNodeStatus, type PlanNode, type PlanNodeStatus, type PlanTree } from "@/src/core";
|
||||
|
||||
/**
|
||||
* The persistent plan-tree panel (vision §2 "Persistent tree view", W7).
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextPlugin from "@next/eslint-plugin-next";
|
||||
import tsParser from "@typescript-eslint/parser";
|
||||
import importPlugin from "eslint-plugin-import";
|
||||
|
||||
/**
|
||||
* ESLint with one job here: ENFORCE THE IMPORT LAW (the shell/core
|
||||
* architecture, docs/architecture.md). Everything else stays out of the
|
||||
* way — this is not a style linter.
|
||||
*
|
||||
* components/** → "@/src/core" (the pure core barrel) — ONLY
|
||||
* app/** → "@/src/core" + "@/src/server" (the server barrel) — ONLY
|
||||
* pure core → never imports src/agent, src/server, src/store
|
||||
*
|
||||
* tests/ and scripts/ are internal — unrestricted.
|
||||
*/
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([".next/**", "node_modules/**", "data/**", "next-env.d.ts", "scripts/**"]),
|
||||
{
|
||||
files: ["**/*.{js,mjs,ts,tsx}"],
|
||||
languageOptions: {
|
||||
parser: tsParser,
|
||||
parserOptions: { ecmaVersion: "latest", sourceType: "module" },
|
||||
},
|
||||
plugins: { "@next/next": nextPlugin, import: importPlugin },
|
||||
settings: {
|
||||
"import/resolver": { typescript: { alwaysTryTypes: true } },
|
||||
},
|
||||
rules: {
|
||||
...nextPlugin.configs.recommended.rules,
|
||||
"import/no-restricted-paths": [
|
||||
"error",
|
||||
{
|
||||
zones: [
|
||||
{
|
||||
target: "./components",
|
||||
from: "./src",
|
||||
// NOTE: the plugin resolves `except` relative to the zone's `from` path.
|
||||
except: ["./core/index.ts"],
|
||||
message:
|
||||
"Browser shell imports ONLY the pure core barrel: `from \"@/src/core\"` (architecture: docs/architecture.md).",
|
||||
},
|
||||
{
|
||||
target: "./app",
|
||||
from: "./src",
|
||||
except: ["./core/index.ts", "./server/index.ts"],
|
||||
message:
|
||||
"app/ (transport + server components) imports ONLY the barrels: `@/src/core` and `@/src/server` (architecture: docs/architecture.md).",
|
||||
},
|
||||
{
|
||||
target: "./src/core/{index,contracts,question-core,plan-tree,phases,pending,math-delims,ui-message}.ts",
|
||||
from: ["./src/agent", "./src/server", "./src/store"],
|
||||
message:
|
||||
"Pure core modules never import IO layers (agent/server/store). IO-bound core (graph.ts, graph-context.ts) is exempt until the storage-port stage inverts it.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
Vendored
+2
-2
@@ -1,7 +1,7 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/dev/types/routes.d.ts";
|
||||
import "./.next/dev/types/root-params.d.ts";
|
||||
import "./.next/types/routes.d.ts";
|
||||
import "./.next/types/root-params.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
|
||||
Generated
+4200
-9
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"test": "NODE_ENV=test tsx --test tests/*.test.ts tests/*.test.tsx",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -54,11 +55,16 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@next/eslint-plugin-next": "^16.3.3",
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@types/turndown": "^5.0.6",
|
||||
"@typescript-eslint/parser": "^8.68.0",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-import-resolver-typescript": "^4.4.5",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.6.0"
|
||||
|
||||
+4
-59
@@ -1,5 +1,5 @@
|
||||
import { tool, type ToolSet } from "ai";
|
||||
import { z } from "zod";
|
||||
import { askInputSchema, quizInputSchema } from "../core/question-core.ts";
|
||||
import { jobTools } from "./tools/jobs.ts";
|
||||
import { planTools } from "./tools/plan.ts";
|
||||
|
||||
@@ -9,67 +9,15 @@ import { planTools } from "./tools/plan.ts";
|
||||
* - 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.
|
||||
* 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).
|
||||
* - jobTools (src/agent/tools/jobs.ts): CLIENT-SIDE semantics, server-side
|
||||
* fulfillment by background sub-agents (see src/core/contracts.ts).
|
||||
*
|
||||
* Parameter names mirror the prompt docs exactly — keep them in sync.
|
||||
*/
|
||||
|
||||
const optionSchema = z.object({
|
||||
label: z.string().describe("Display label for the answer option"),
|
||||
value: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Optional machine-readable value returned for the option. Defaults to the label."),
|
||||
description: z.string().optional().describe("Optional extra detail shown below the option"),
|
||||
});
|
||||
|
||||
// Raw schemas stay exported: `tool()` wraps them into its internal Schema
|
||||
// type (erasing z.infer), so clients infer input types from these instead.
|
||||
export const quizInputSchema = z.object({
|
||||
question: z.string().describe("The single quiz question to ask"),
|
||||
options: z
|
||||
.array(optionSchema)
|
||||
.min(2)
|
||||
.describe("The answer options (2 or more). Options only — no free-text mode. Never add your own 'I don't know' option."),
|
||||
correctAnswer: z
|
||||
.union([z.string(), z.array(z.string())])
|
||||
.describe(
|
||||
"The correct answer as the option value(s) — the `value` field of the option you intend. " +
|
||||
"Single-select: one string. Multi-select: an array; the learner is only correct if their selection matches this set exactly.",
|
||||
),
|
||||
explanation: z
|
||||
.string()
|
||||
.describe("Explanation revealed AFTER the learner answers. Always say why the correct answer is correct."),
|
||||
multiSelect: z.boolean().optional().describe("Set true only when more than one option is correct"),
|
||||
details: z.string().optional().describe("Optional extra context or instructions shown under the question"),
|
||||
nodeId: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
"Optional plan-tree node id this question assesses. Set whenever the question targets a tree node — " +
|
||||
"the outcome feeds the learner's knowledge graph. Omit for ad-hoc probes.",
|
||||
),
|
||||
});
|
||||
|
||||
export const askInputSchema = z.object({
|
||||
question: z.string().describe("The single question to ask"),
|
||||
mode: z
|
||||
.enum(["single-select", "multi-select", "text"])
|
||||
.optional()
|
||||
.describe("Answer mode. Omit for single-select when options are given, or text when they are not."),
|
||||
options: z
|
||||
.array(optionSchema)
|
||||
.min(2)
|
||||
.optional()
|
||||
.describe("Optional multiple-choice options. Omit for free-form text input. The learner can always choose 'Other' and type a custom answer."),
|
||||
multiSelect: z.boolean().optional().describe("Set true to allow multiple answers to be selected"),
|
||||
details: z.string().optional().describe("Optional extra context or instructions shown under the question"),
|
||||
});
|
||||
|
||||
export const quizTool = tool({
|
||||
description:
|
||||
"Ask the learner a GRADED question with a known correct answer, then instantly grade and give feedback. " +
|
||||
@@ -108,6 +56,3 @@ export function createTeacherTools(ctx: TeacherToolContext): ToolSet {
|
||||
...jobTools(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
export type QuizToolInput = z.infer<typeof quizInputSchema>;
|
||||
export type AskToolInput = z.infer<typeof askInputSchema>;
|
||||
|
||||
@@ -75,7 +75,6 @@ export const visualTool = tool({
|
||||
* everything from the chat record by toolCallId) — the ctx parameter keeps
|
||||
* the createTeacherTools factory shape stable.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function jobTools(ctx: TeacherToolContext): ToolSet {
|
||||
return {
|
||||
research: researchTool,
|
||||
|
||||
+46
-6
@@ -1,12 +1,11 @@
|
||||
/**
|
||||
* Shared contracts — the single source of truth every workstream codes against.
|
||||
* Pure types + protocol docs; no runtime code, no imports (safe everywhere:
|
||||
* server, client, tests). See docs/plan.md (waves) and docs/vision.md (§ refs).
|
||||
*
|
||||
* Owners: orchestrator wrote this file. Workers: do NOT edit it; if a contract
|
||||
* looks wrong or is missing something you need, ask the orchestrator.
|
||||
* Shared contracts — the single source of truth every component codes against.
|
||||
* Pure types + protocol docs; no runtime code, type-only imports (safe
|
||||
* everywhere: server, client, tests). See docs/vision.md (§ refs).
|
||||
*/
|
||||
|
||||
import type { UIMessage } from "ai";
|
||||
|
||||
// ─── Plan tree (vision §2 "formal plan tree") ────────────────────────────────
|
||||
// A session-scoped dependency tree authored by the teacher via plan tools.
|
||||
// One substrate with the global graph: tree nodes fold into graph nodes.
|
||||
@@ -121,6 +120,47 @@ export interface LedgerEvent {
|
||||
* events (+ note); quiz parts without nodeId → events with nodeId null.
|
||||
*/
|
||||
|
||||
/** Per-node state class for the home view (vision §1 "Home page") — derived,
|
||||
* never stored: taught if ANY taught event; else the LATEST quiz event decides
|
||||
* (known / missed / dont-know); a node with no events is a candidate. */
|
||||
export type NodeStateClass = "taught" | "known" | "missed" | "dont-know" | "candidate";
|
||||
|
||||
/** The GET /api/graph payload — everything the home view's PURE renderer needs. */
|
||||
export interface GraphSnapshot {
|
||||
nodes: GraphNode[];
|
||||
edges: GraphEdge[];
|
||||
nodeStates: Record<string, NodeStateClass>;
|
||||
/** chatId → title, for every chat that touched the graph. */
|
||||
sessions: Record<string, string>;
|
||||
/** nodeId → chatIds that touched the node (click-through provenance). */
|
||||
nodeSessions: Record<string, string[]>;
|
||||
}
|
||||
|
||||
// ─── Chat records (the session store's on-disk format) ───────────────────────
|
||||
|
||||
/** One persisted session: data/chats/<id>.json. The stored messages are full
|
||||
* AI SDK UIMessages (parts included) — the canonical session record: a
|
||||
* pending quiz is a tool part in `input-available` state, which is exactly
|
||||
* what makes resume-mid-question free. */
|
||||
export interface ChatRecord {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
messages: UIMessage[];
|
||||
/** The session's plan tree (vision §2) — written by plan tools via saveTree. */
|
||||
tree?: PlanTree;
|
||||
}
|
||||
|
||||
/** The list view's shape (messageCount instead of full messages). */
|
||||
export interface ChatSummary {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
messageCount: number;
|
||||
}
|
||||
|
||||
// ─── Async sub-agent jobs (vision §2.5; plan.md Wave 0 protocol) ────────────
|
||||
|
||||
export type JobKind = "research" | "demo" | "visual";
|
||||
|
||||
@@ -22,7 +22,8 @@
|
||||
*/
|
||||
|
||||
import type { GraphEdge, GraphNode } from "./contracts.ts";
|
||||
import { deriveNodeStates, getGraph, type DerivedGraph, type NodeStateClass } from "./graph.ts";
|
||||
import { deriveNodeStates, getGraph, type DerivedGraph } from "./graph.ts";
|
||||
import type { NodeStateClass } from "./contracts.ts";
|
||||
|
||||
/** The section header the teacher is taught to recognize (50-graph-context.md). */
|
||||
export const GRAPH_CONTEXT_HEADER = "LEARNER KNOWLEDGE GRAPH (auto-generated)";
|
||||
|
||||
+11
-15
@@ -21,7 +21,16 @@
|
||||
*/
|
||||
|
||||
import { isToolUIPart, type UIMessage } from "ai";
|
||||
import type { GraphEdge, GraphNode, LedgerEvent, LedgerEventKind, PlanTree, PlanToolResult } from "./contracts.ts";
|
||||
import type {
|
||||
GraphEdge,
|
||||
GraphNode,
|
||||
GraphSnapshot,
|
||||
LedgerEvent,
|
||||
LedgerEventKind,
|
||||
NodeStateClass,
|
||||
PlanTree,
|
||||
PlanToolResult,
|
||||
} from "./contracts.ts";
|
||||
import type { QuestionAnswerData } from "./question-core.ts";
|
||||
import { getChat, listChats } from "../store/chats.ts";
|
||||
import { graphLedgers, newGraphNodeId } from "../store/graph.ts";
|
||||
@@ -308,9 +317,6 @@ export function getGraph(): DerivedGraph {
|
||||
return { nodes, edges: merged, events: graphLedgers.readEvents() };
|
||||
}
|
||||
|
||||
/** Per-node state classes for the home view (vision §1 "Home page"). */
|
||||
export type NodeStateClass = "taught" | "known" | "missed" | "dont-know" | "candidate";
|
||||
|
||||
const QUIZ_EVENT_KINDS: ReadonlySet<string> = new Set([
|
||||
"probe-correct",
|
||||
"check-correct",
|
||||
@@ -359,17 +365,7 @@ export function deriveNodeStates(nodes: GraphNode[], events: LedgerEvent[]): Rec
|
||||
|
||||
// ─── the /api/graph payload ──────────────────────────────────────────────────
|
||||
|
||||
export interface GraphSnapshot {
|
||||
nodes: GraphNode[];
|
||||
edges: GraphEdge[];
|
||||
nodeStates: Record<string, NodeStateClass>;
|
||||
/** chatId → title, for every chat that touched the graph. */
|
||||
sessions: Record<string, string>;
|
||||
/** nodeId → chatIds that touched the node (click-through provenance). */
|
||||
nodeSessions: Record<string, string[]>;
|
||||
}
|
||||
|
||||
/** Everything the home graph view needs, in one fetch. */
|
||||
/** Everything the home graph view needs, in one fetch (shape: contracts). */
|
||||
export function graphSnapshot(): GraphSnapshot {
|
||||
const { nodes, edges, events } = getGraph();
|
||||
const nodeStates = deriveNodeStates(nodes, events);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* THE CORE PUBLIC API — the only module the shell (app/, components/) may
|
||||
* import. Everything exported here is browser-safe: pure logic + types,
|
||||
* no node builtins, no fs, no network.
|
||||
*
|
||||
* Server-side surfaces (chat streaming, store reads) live behind
|
||||
* src/server's barrel instead — the import law (eslint.config.mjs):
|
||||
*
|
||||
* components/** → "@/src/core" (this barrel, ONLY)
|
||||
* app/** → "@/src/core" + "@/src/server"
|
||||
*
|
||||
* IO-bound modules (core/graph.ts, core/graph-context.ts read the ledgers
|
||||
* via the store) stay internal to the server side until the storage-port
|
||||
* stage inverts their dependency; they are deliberately NOT re-exported
|
||||
* here.
|
||||
*/
|
||||
|
||||
export * from "./contracts.ts";
|
||||
export * from "./question-core.ts";
|
||||
export * from "./plan-tree.ts";
|
||||
export * from "./phases.ts";
|
||||
export * from "./pending.ts";
|
||||
export * from "./math-delims.ts";
|
||||
export * from "./ui-message.ts";
|
||||
@@ -1,14 +1,11 @@
|
||||
/**
|
||||
* question-core — pure logic for quiz/ask questions. No framework imports,
|
||||
* no UI: everything here is deterministic and unit-testable.
|
||||
* question-core — the question contract + pure grading logic. No framework
|
||||
* imports, no UI: everything here is deterministic and unit-testable.
|
||||
*
|
||||
* Used by:
|
||||
* - the TUI quiz extension (extensions/quiz.ts) — blocking terminal UI
|
||||
* - the web app (AI SDK client-side tools) — the browser validates,
|
||||
* shuffles, grades with these functions, then sends the verdict back
|
||||
* as the tool output via addToolOutput
|
||||
*
|
||||
* The web shape (AI SDK):
|
||||
* The zod schemas below are the tool INPUT contracts (agent/tools declares
|
||||
* the tools against them); the browser validates, shuffles, and grades with
|
||||
* these functions, then sends the verdict back as the tool output via
|
||||
* addToolOutput:
|
||||
* 1. The teacher model calls the `quiz` tool (question + options +
|
||||
* correctAnswer + explanation). No server execute → the call lands in
|
||||
* the UI as a typed tool part in `input-available` state.
|
||||
@@ -20,6 +17,8 @@
|
||||
* exited and resumed mid-question for free.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
// ─── shared types ───────────────────────────────────────────────────────────
|
||||
|
||||
export interface QuizOption {
|
||||
@@ -28,6 +27,69 @@ export interface QuizOption {
|
||||
description?: string;
|
||||
}
|
||||
|
||||
// ─── tool input schemas (the question contract) ─────────────────────────────
|
||||
// Parameter names mirror the prompt docs exactly — keep them in sync.
|
||||
|
||||
const optionSchema = z.object({
|
||||
label: z.string().describe("Display label for the answer option"),
|
||||
value: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Optional machine-readable value returned for the option. Defaults to the label."),
|
||||
description: z.string().optional().describe("Optional extra detail shown below the option"),
|
||||
});
|
||||
|
||||
export const quizInputSchema = z.object({
|
||||
question: z.string().describe("The single quiz question to ask"),
|
||||
options: z
|
||||
.array(optionSchema)
|
||||
.min(2)
|
||||
.describe(
|
||||
"The answer options (2 or more). Options only — no free-text mode. Never add your own 'I don't know' option.",
|
||||
),
|
||||
correctAnswer: z
|
||||
.union([z.string(), z.array(z.string())])
|
||||
.describe(
|
||||
"The correct answer as the option value(s) — the `value` field of the option you intend. " +
|
||||
"Single-select: one string. Multi-select: an array; the learner is only correct if their selection matches this set exactly.",
|
||||
),
|
||||
explanation: z
|
||||
.string()
|
||||
.describe("Explanation revealed AFTER the learner answers. Always say why the correct answer is correct."),
|
||||
multiSelect: z.boolean().optional().describe("Set true only when more than one option is correct"),
|
||||
details: z.string().optional().describe("Optional extra context or instructions shown under the question"),
|
||||
nodeId: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
"Optional plan-tree node id this question assesses. Set whenever the question targets a tree node — " +
|
||||
"the outcome feeds the learner's knowledge graph. Omit for ad-hoc probes.",
|
||||
),
|
||||
});
|
||||
|
||||
export const askInputSchema = z.object({
|
||||
question: z.string().describe("The single question to ask"),
|
||||
mode: z
|
||||
.enum(["single-select", "multi-select", "text"])
|
||||
.optional()
|
||||
.describe(
|
||||
"Answer mode. Omit for single-select when options are given, or text when they are not.",
|
||||
),
|
||||
options: z
|
||||
.array(optionSchema)
|
||||
.min(2)
|
||||
.optional()
|
||||
.describe(
|
||||
"Optional multiple-choice options. Omit for free-form text input. The learner can always choose 'Other' and type a custom answer.",
|
||||
),
|
||||
multiSelect: z.boolean().optional().describe("Set true to allow multiple answers to be selected"),
|
||||
details: z.string().optional().describe("Optional extra context or instructions shown under the question"),
|
||||
});
|
||||
|
||||
export type QuizToolInput = z.infer<typeof quizInputSchema>;
|
||||
export type AskToolInput = z.infer<typeof askInputSchema>;
|
||||
|
||||
|
||||
/** A real selected answer, in the order the options were displayed. */
|
||||
export interface OptionAnswer {
|
||||
label: string;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { UIMessage } from "ai";
|
||||
import type { AskToolInput, QuizToolInput } from "./tools.ts";
|
||||
import type { QuestionAnswerData } from "../core/question-core.ts";
|
||||
import type { AskToolInput, QuestionAnswerData, QuizToolInput } from "./question-core.ts";
|
||||
|
||||
/**
|
||||
* The typed UI message for the teacher chat — gives the frontend typed tool
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createChat, getChat, listChats, titleFromPrompt } from "../store/chats.ts";
|
||||
|
||||
/**
|
||||
* Server-side chat entries for the transport layer (app/api/chats*,
|
||||
* app/chat/[id]). Today these delegate straight to the fs store; the
|
||||
* services stage carves the real orchestration behind this same surface.
|
||||
*/
|
||||
|
||||
export { createChat, getChat, listChats, titleFromPrompt };
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { GraphSnapshot } from "../core/contracts.ts";
|
||||
import { foldStaleChats, graphSnapshot } from "../core/graph.ts";
|
||||
|
||||
/**
|
||||
* Server-side graph entry for the home view (GET /api/graph): fold any chat
|
||||
* whose updatedAt outstrips its emission checkpoint first (partial sessions
|
||||
* deposit value), then return the snapshot. Today the fold is the naive-union
|
||||
* emission; the extraction-pipeline stage replaces the writer behind this
|
||||
* same read surface.
|
||||
*/
|
||||
export function graphView(): GraphSnapshot {
|
||||
foldStaleChats();
|
||||
return graphSnapshot();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* THE SERVER-SIDE SURFACE — the only src module (besides the core barrel)
|
||||
* that app/ may import. Route handlers and server components come through
|
||||
* here; nothing under app/ touches src/store or src/agent directly.
|
||||
*/
|
||||
|
||||
export * from "./chat-handler.ts";
|
||||
export * from "./chats.ts";
|
||||
export * from "./graph.ts";
|
||||
export * from "./jobs.ts";
|
||||
@@ -0,0 +1,10 @@
|
||||
import { listJobs } from "../store/jobs.ts";
|
||||
|
||||
/**
|
||||
* Server-side job-status entry (GET /api/jobs?chatId=…, contracts.ts
|
||||
* "THE ASYNC PROTOCOL" §4): the client polls while any job tool part is
|
||||
* pending, finds the job by toolCallId, renders its activity line, and
|
||||
* re-syncs the chat when the job flips to done/error.
|
||||
*/
|
||||
|
||||
export { listJobs };
|
||||
+4
-26
@@ -2,36 +2,14 @@ import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import type { UIMessage } from "ai";
|
||||
import { PATHS } from "../../config.ts";
|
||||
import type { PlanTree } from "../core/contracts.ts";
|
||||
import type { ChatRecord, ChatSummary, PlanTree } from "../core/contracts.ts";
|
||||
|
||||
/**
|
||||
* Chat store — one JSON file per chat in data/chats/.
|
||||
*
|
||||
* The stored messages are full AI SDK UIMessages (parts included). This is
|
||||
* the canonical session record: a pending quiz is a tool part in
|
||||
* `input-available` state, which is exactly what makes resume-mid-question
|
||||
* free. The extraction pipeline (src/extract) will read these later; old pi
|
||||
* sessions (data/sessions) remain bootstrap input only.
|
||||
* Chat store — one JSON file per chat in data/chats/. The record shape lives
|
||||
* in core/contracts (ChatRecord/ChatSummary); this module is the fs adapter's
|
||||
* implementation (the storage port formalizes this in a later stage).
|
||||
*/
|
||||
|
||||
export interface ChatRecord {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
messages: UIMessage[];
|
||||
/** The session's plan tree (vision §2) — written by plan tools via saveTree. */
|
||||
tree?: PlanTree;
|
||||
}
|
||||
|
||||
export interface ChatSummary {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
messageCount: number;
|
||||
}
|
||||
|
||||
function chatFile(id: string): string {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error(`Invalid chat id: ${id}`);
|
||||
return path.join(PATHS.chats, `${id}.json`);
|
||||
|
||||
@@ -22,7 +22,7 @@ import { after, describe, it } from "node:test";
|
||||
import { MockLanguageModelV4, simulateReadableStream } from "ai/test";
|
||||
import type { LanguageModelV4StreamPart } from "@ai-sdk/provider";
|
||||
import type { GraphEdge, GraphNode, LedgerEvent } from "../src/core/contracts.ts";
|
||||
import type { NodeStateClass } from "../src/core/graph.ts";
|
||||
import type { NodeStateClass } from "../src/core/contracts.ts";
|
||||
import { emitChat, type GraphLedgers } from "../src/core/graph.ts";
|
||||
import {
|
||||
buildGraphContext,
|
||||
|
||||
Reference in New Issue
Block a user