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:
+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`);
|
||||
|
||||
Reference in New Issue
Block a user