@mmon-co/ncept-local 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ const tar = await profile.pack();
15
15
  await unpackDirectory(tar, "/path/to/moved-profile", [defaultTheory]);
16
16
  ```
17
17
 
18
- `init` creates an empty personal Patch, empty log and reserved directories in an ordinary project directory. `profile.json` contains `format: 1`, `personal`, `theory` (Core's requirement), `theories` (package names, initially `@mmon-co/ncept-default-theory`) and `sessions` (surface → pi filename). Account credentials live at `credentialsPath()`, outside the Profile, in `~/.config/mmon/credentials.json`.
18
+ `init` creates an empty personal Patch, empty log and reserved directories in an ordinary project directory. `profile.json` contains `format: 1`, `personal`, `theory` (Core's requirement), `theories` (package names, initially `@mmon-co/ncept-default-theory`) and `sessions` (surface → pi filename). Account credentials live at `credentialsPath()`, outside the Profile, in `~/.config/ncept/credentials.json`.
19
19
 
20
20
  `openProfile` and `unpack` migrate a stored minor pin (or an exact web-export release) with the supplied executable Theory’s `migrations` before strict resolution. Broad requirements still use strict resolution without migration. Migration writes new immutable Patch revisions and a content-addressed log snapshot, then atomically switches `profile.json`’s personal head, Theory requirement and optional `log` digest together. Interrupted writes leave the old generation active; reopening retries pure steps from that generation. Old revision/log files remain unread history. Host futures are rebuilt from the migrated Profile; captured Session transcripts are not rewritten as futures.
21
21
 
@@ -38,16 +38,18 @@ const session = await host.sessions.open({ mode: "charting", entry: { kind: "goa
38
38
  const setup = await host.sessions.turn(session, {});
39
39
  const claim = setup.tools.find((tool) => tool.name === "record_claim")!;
40
40
  await claim.run({ statement: "I can add one and one", stance: "knows" });
41
- await host.sessions.close(session);
41
+ const next = await host.sessions.settle(session);
42
42
  ```
43
43
 
44
+ After the whole conversation turn stops and its transcript is saved, call `.settle(session)`. It closes a completed Lesson through the same lifecycle as `.close` and returns a Charting switch for its Mission; an unfinished Lesson stays open. Keep the Session open across all tool batches and the tutor's final reply.
45
+
44
46
  After a switch result, call `.open(result.switch)` for `next`/`aside`; for `here`, keep the same Session handle and request a fresh turn. `.close(session)` records its closing transcript through the Theory. Resume a closed Session with `.open({ mode, resume: session.id })`. Session identities, mode, scope, acceptance provenance and learner-day receipts are platform observations in `log.jsonl`, so they travel with the Profile.
45
47
 
46
48
  The front end writes pi transcripts and registers their filenames against `session.surface` after trust. `turn(session, { learnerMessage })` takes the selected learner **message entry id**, not message text; it runs a declared reply grader before setup. Reads follow the selected pi branch, and locally recorded evidence derives its standing from its acceptance branch. A library caller without a transcript still retains tool-recorded evidence, but has no closing conversation to record.
47
49
 
48
50
  Graph drafts stay unsaved until a confirmed `propose`. Mission and guidance/graph proposals and preference changes use `confirm`; a refusal changes no Profile files. Materials use the `local` playground, immutable blob bytes and working copies under `materials/<node>/<material>/<filename>`. Opening preserves an existing working copy. Read-back returns both the saved body and current working-copy text. Other playgrounds' Materials remain readable as saved data without claiming a runner.
49
51
 
50
- `host.config.update({ ...await host.config.read(), timezone: "America/New_York" })` configures learner-days. The initial zone is the machine's IANA zone; each learner-day ends at 04:00 local, including across DST. At startup, the host raises `day.ended` once per elapsed day and records its receipt alongside the Theory's writes. No account or background daemon is needed.
52
+ `host.config.update({ ...await host.config.read(), timezone: "America/New_York" })` configures learner-days. The initial zone is the machine's IANA zone; each learner-day ends at 04:00 local, including across DST. At startup, the host raises `day.ended` once per elapsed day and records its receipt alongside the Theory's writes. No account or background daemon is needed. Set `sessionLength` through the same config API to choose the Session budget in minutes (default 20). Review opens the Theory’s budgeted maintenance stop, preserving its Node order; the due count still describes all due Nodes.
51
53
 
52
54
  ## Hub and web exchange
53
55
 
@@ -27,6 +27,8 @@ export interface ProfileDirectory {
27
27
  }): Promise<string>;
28
28
  pack(): Promise<Uint8Array>;
29
29
  }
30
- export declare function openProfile(dir: string, theories: readonly ConfiguredTheory[]): Promise<ProfileDirectory>;
30
+ export declare function openProfile(dir: string, theories: readonly ConfiguredTheory[], options?: {
31
+ readOnly?: boolean;
32
+ }): Promise<ProfileDirectory>;
31
33
  /** Unpack into a new Profile, leaving unrelated project files alone and never following links. */
32
34
  export declare function unpackDirectory(archive: Uint8Array, dir: string, theories: readonly ConfiguredTheory[]): Promise<ProfileDirectory>;
package/dist/directory.js CHANGED
@@ -2,6 +2,7 @@ import { link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "no
2
2
  import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { lock, lockSync } from "proper-lockfile";
5
6
  import { attachmentDigest, candidateRevision, emptyPatch, isPatchId, mergeProfileLogs, PERSONAL_PATCH_ID, } from "@mmon-co/ncept-core";
6
7
  import { DEFAULT_THEORY_PACKAGES, DEFAULT_THEORY_REQUIREMENT, jsonBytes, logBytes, liveLogPath, migrateProfileFiles, pack, parseManifest, sessionFilename, unpack, utf8, validate, } from "./exchange.js";
7
8
  import { parsePiSession, piSessionFilename, relocatePiSession, serializePiSession, } from "./sessions.js";
@@ -99,34 +100,59 @@ export async function init(dir, options = {}) {
99
100
  await immutable(dir, "patches/" + patch.ref.digest + ".json", jsonBytes(emptyPatch()));
100
101
  await writeFile(join(dir, "log.jsonl"), new Uint8Array(), { flag: "wx" });
101
102
  }
102
- export async function openProfile(dir, theories) {
103
- dir = resolve(dir);
104
- const stored = await filesAt(dir);
105
- const initial = migrateProfileFiles(stored, theories);
106
- // Immutable data first, then a single atomic live-head/log/pin switch. An interruption
107
- // leaves either the old generation or the complete new one; retry never repeats a step.
108
- for (const [path, bytes] of initial) {
109
- if (path !== "profile.json" && !stored.has(path))
110
- await immutable(dir, path, bytes);
111
- }
112
- const manifest = initial.get("profile.json");
113
- if (manifest !== stored.get("profile.json") && manifest)
114
- await atomic(dir, "profile.json", manifest);
115
- const profile = validate(initial, theories);
116
- // A copied or moved Profile must still appear in pi's cwd-filtered /resume list.
117
- for (const filename of Object.values(profile.manifest.sessions)) {
118
- const path = "sessions/" + filename;
119
- const bytes = initial.get(path);
120
- if (bytes) {
121
- const source = new TextDecoder().decode(bytes);
122
- if (parsePiSession(source).header.cwd !== dir)
123
- await atomic(dir, path, utf8.encode(relocatePiSession(source, dir)));
124
- }
103
+ async function locked(dir, operation) {
104
+ let release;
105
+ try {
106
+ // The uncontended path avoids callback round trips for each filesystem step.
107
+ release = lockSync(dir);
125
108
  }
126
- // Serialize this handle's mutations, including read/merge/write of the immutable-identity log.
109
+ catch (error) {
110
+ if (!(error instanceof Error && "code" in error && error.code === "ELOCKED"))
111
+ throw error;
112
+ release = await lock(dir, {
113
+ retries: { forever: true, minTimeout: 10, maxTimeout: 100, randomize: true },
114
+ });
115
+ }
116
+ try {
117
+ return await operation();
118
+ }
119
+ finally {
120
+ await release();
121
+ }
122
+ }
123
+ export async function openProfile(dir, theories, options = {}) {
124
+ dir = resolve(dir);
125
+ if (!options.readOnly)
126
+ await locked(dir, async () => {
127
+ const stored = await filesAt(dir);
128
+ const initial = migrateProfileFiles(stored, theories);
129
+ // Immutable data first, then a single atomic live-head/log/pin switch. An interruption
130
+ // leaves either the old generation or the complete new one; retry never repeats a step.
131
+ for (const [path, bytes] of initial) {
132
+ if (path !== "profile.json" && !stored.has(path))
133
+ await immutable(dir, path, bytes);
134
+ }
135
+ const manifest = initial.get("profile.json");
136
+ if (manifest !== stored.get("profile.json") && manifest)
137
+ await atomic(dir, "profile.json", manifest);
138
+ const profile = validate(initial, theories);
139
+ // A copied or moved Profile must still appear in pi's cwd-filtered /resume list.
140
+ for (const filename of Object.values(profile.manifest.sessions)) {
141
+ const path = "sessions/" + filename;
142
+ const bytes = initial.get(path);
143
+ if (bytes) {
144
+ const source = new TextDecoder().decode(bytes);
145
+ if (parsePiSession(source).header.cwd !== dir)
146
+ await atomic(dir, path, utf8.encode(relocatePiSession(source, dir)));
147
+ }
148
+ }
149
+ });
150
+ // Queue this handle's writes before contending with other handles and processes.
127
151
  let tail = Promise.resolve();
128
152
  function serial(operation) {
129
- const result = tail.then(operation);
153
+ if (options.readOnly)
154
+ return Promise.reject(new Error("Cannot write through a read-only Profile"));
155
+ const result = tail.then(() => locked(dir, operation));
130
156
  tail = result.catch(() => { });
131
157
  return result;
132
158
  }
package/dist/exchange.js CHANGED
@@ -1,4 +1,4 @@
1
- import { attachmentDigest, bundleForRevision, isContentDigest, isPatchId, isProfileLogEntry, mergeProfileLogs, migrateTheoryProfile, resolveTheory, revisionDigest, } from "@mmon-co/ncept-core";
1
+ import { attachmentDigest, notebookBundleForRevision, isContentDigest, isPatchId, isProfileLogEntry, mergeProfileLogs, migrateTheoryProfile, resolveTheory, revisionDigest, } from "@mmon-co/ncept-core";
2
2
  import { object, parsePiSession, relocatePiSession } from "./sessions.js";
3
3
  import { decodeTar, encodeTar } from "./tar.js";
4
4
  export const DEFAULT_THEORY_PACKAGES = ["@mmon-co/ncept-default-theory"];
@@ -139,7 +139,7 @@ function validateStructure(files) {
139
139
  else
140
140
  throw new Error("Unexpected Profile exchange file: " + path);
141
141
  }
142
- const patches = bundleForRevision(manifest.personal, contents);
142
+ const patches = notebookBundleForRevision(manifest.personal, contents);
143
143
  for (const content of contents.values())
144
144
  requireAttachments(content, blobs);
145
145
  const sessions = new Map();
@@ -435,7 +435,9 @@ export function hostTools(host, opened, capabilities, skills, metadataKeys) {
435
435
  });
436
436
  }
437
437
  if (metadataKeys.length) {
438
- mount("edit_metadata", "Edit this mode's authorized metadata keys on existing Nodes: " + metadataKeys.join(", "), schema({ nodes: nodeList, properties: { type: "object" } }, ["nodes", "properties"]), async (raw, session) => {
438
+ mount("edit_metadata", "Edit this mode's authorized metadata keys on existing Nodes: " +
439
+ metadataKeys.join(", ") +
440
+ ". Material completion queries use the created Material's identity; local file-item attempts, including card recalls, have playground local.", schema({ nodes: nodeList, properties: { type: "object" } }, ["nodes", "properties"]), async (raw, session) => {
439
441
  const attached = nodes(raw.nodes);
440
442
  const properties = metadataProperties(raw.properties);
441
443
  if (Object.keys(properties).some((key) => !metadataKeys.includes(key)))
package/dist/host.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ChatSetup, HostCapability, ExactPatchRef, JsonSchema, LessonReading, Mission, MissionRunReading, ModeEntry, ModeSwitchDefault, NodeId, Request, SessionRef, Theory, TheoryRequirement } from "@mmon-co/ncept-core";
1
+ import type { ChatSetup, HostCapability, ExactPatchRef, JsonSchema, LessonReading, MissionPathReading, Mission, MissionRunReading, ModeEntry, ModeSwitchDefault, NodeId, Request, SessionRef, Theory, TheoryRequirement } from "@mmon-co/ncept-core";
2
2
  import type { ProfileDirectory } from "./directory.js";
3
3
  /** The host supplies both judge and assess with the concrete JSON reply schema. */
4
4
  export type ModelRequest = Extract<Request, {
@@ -42,6 +42,7 @@ export interface MissionReading {
42
42
  readonly mission: Mission;
43
43
  readonly run: MissionRunReading;
44
44
  readonly next: readonly LessonReading[];
45
+ readonly path?: MissionPathReading;
45
46
  }
46
47
  export interface HostReading {
47
48
  readonly missions: readonly MissionReading[];
@@ -61,18 +62,52 @@ export interface HostConfig {
61
62
  readonly theories: readonly string[];
62
63
  /** IANA zone for learner-days; defaults to the local machine's configured zone. */
63
64
  readonly timezone?: string;
65
+ /** Positive Session budget in minutes; defaults to 20. */
66
+ readonly sessionLength?: number;
64
67
  }
68
+ export type SessionOpening = Readonly<{
69
+ mode: string;
70
+ entry?: ModeEntry;
71
+ resume?: SessionRef;
72
+ mission?: string;
73
+ }> & Readonly<{
74
+ skip?: {
75
+ mission: string;
76
+ kind: "skip-lesson";
77
+ } | {
78
+ mission: string;
79
+ kind: "skip-to";
80
+ stop: Pick<LessonReading, "kind" | "number" | "checkpoint">;
81
+ };
82
+ }>;
83
+ /** Learner entry controls; resolved against current Profile state by its writing tutor. */
84
+ export type SessionIntent = Readonly<{
85
+ kind: "skip-lesson";
86
+ missionId: string;
87
+ }> | Readonly<{
88
+ kind: "skip-to";
89
+ missionId: string;
90
+ stop: Pick<LessonReading, "kind" | "number" | "checkpoint">;
91
+ }> | Readonly<{
92
+ kind: "continue" | "revise-lesson" | "revise-route";
93
+ missionId: string;
94
+ }> | Readonly<{
95
+ kind: "tell-tutor";
96
+ missionId: string;
97
+ request: string;
98
+ }> | Readonly<{
99
+ kind: "new-mission" | "review";
100
+ }>;
65
101
  export interface Host {
66
102
  readonly profile: ProfileDirectory;
67
103
  readonly sessions: {
68
- open(input: Readonly<{
69
- mode: string;
70
- entry?: ModeEntry;
71
- resume?: SessionRef;
72
- }>): Promise<HostSession>;
104
+ open(input: SessionOpening): Promise<HostSession>;
105
+ begin(intent: SessionIntent): Promise<HostSession>;
73
106
  turn(session: HostSession, input: Readonly<{
74
107
  learnerMessage?: string;
75
108
  }>): Promise<HostChatSetup>;
109
+ /** After the conversation stops, close a completed Lesson and return its next surface. */
110
+ settle(session: HostSession): Promise<ModeSwitch | undefined>;
76
111
  close(session: HostSession): Promise<void>;
77
112
  };
78
113
  readonly missions: {
package/dist/hub.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { mkdtemp, rename, rm } from "node:fs/promises";
2
2
  import { dirname, basename, join } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
4
+ import metadata from "../package.json" with { type: "json" };
5
5
  import { attachmentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isPatchId, migrateTheoryPatchClosure, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
6
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -97,8 +97,7 @@ function theoryRequirement(value) {
97
97
  export function connectHub(profile, theories, confirm, options = {}) {
98
98
  const base = baseUrl(options.url ?? "https://co.mmon.co/ncept");
99
99
  const resource = base + "/mcp";
100
- const { version } = createRequire(import.meta.url)("../package.json");
101
- const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + version };
100
+ const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + metadata.version };
102
101
  async function connected(operation) {
103
102
  const provider = await HubAuth.open(resource, options);
104
103
  if (!provider.tokens())
package/dist/index.d.ts CHANGED
@@ -2,3 +2,4 @@ export * from "./exchange.js";
2
2
  export * from "./sessions.js";
3
3
  export * from "./directory.js";
4
4
  export * from "./host.js";
5
+ export { openLearningReader } from "./learning.js";
package/dist/index.js CHANGED
@@ -2,3 +2,4 @@ export * from "./exchange.js";
2
2
  export * from "./sessions.js";
3
3
  export * from "./directory.js";
4
4
  export * from "./host.js";
5
+ export { openLearningReader } from "./learning.js";
@@ -1,6 +1,37 @@
1
- import { type LessonProgress, type Mission, type ModeEntry, type NodeId, type PatchContent, type SessionMode, type Theory } from "@mmon-co/ncept-core";
2
- import type { Host, HostChatSetup, HostConfig, HostSession, MissionReading, ModeSwitch, OpenHostOptions } from "./host.js";
1
+ import { type LessonProgress, type LessonReading, type Mission, type ModeEntry, type NodeId, type PatchContent, type SessionMode, type Theory } from "@mmon-co/ncept-core";
2
+ import type { Host, HostChatSetup, HostConfig, HostSession, MissionReading, ModeSwitch, OpenHostOptions, SessionOpening, SessionIntent } from "./host.js";
3
3
  import { Runtime, type LocalSession } from "./runtime.js";
4
+ /** Read current learning state without day processing, receipts, configuration writes or model calls. */
5
+ export declare function openLearningReader<S>(profileDir: string, theories: readonly Theory<S>[]): Promise<{
6
+ reading(): Promise<{
7
+ missions: readonly MissionReading[];
8
+ nodes: {
9
+ id: `node-${string}`;
10
+ label: string;
11
+ status: "open" | "done" | "tentative";
12
+ }[];
13
+ dueReview: {
14
+ id: `node-${string}`;
15
+ label: string;
16
+ }[];
17
+ sessions: {
18
+ title: string;
19
+ missionLabel: string | undefined;
20
+ nodes: {
21
+ id: `node-${string}`;
22
+ label: string;
23
+ }[];
24
+ surface: import("@mmon-co/ncept-core").SurfaceId;
25
+ about: readonly NodeId[];
26
+ closed: boolean;
27
+ mission?: string;
28
+ parent?: string;
29
+ id: import("@mmon-co/ncept-core").SessionRef;
30
+ mode: string;
31
+ entry?: ModeEntry;
32
+ }[];
33
+ }>;
34
+ }>;
4
35
  /** Owns execution serialization; the front end owns pi's conversation and transcript writer. */
5
36
  export declare class LearningHost<S> {
6
37
  readonly runtime: Runtime<S>;
@@ -26,12 +57,10 @@ export declare class LearningHost<S> {
26
57
  private closing;
27
58
  private closingRun;
28
59
  close(session: HostSession): Promise<void>;
60
+ settle(session: HostSession): Promise<ModeSwitch | undefined>;
29
61
  retireMission(id: string, outcome: "achieved" | "abandoned"): Promise<void>;
30
- open(input: {
31
- mode: string;
32
- entry?: ModeEntry;
33
- resume?: string;
34
- }): Promise<HostSession>;
62
+ begin(intent: SessionIntent): Promise<HostSession>;
63
+ open(input: SessionOpening): Promise<HostSession>;
35
64
  switchMode(session: LocalSession, to: ModeSwitch): Promise<void>;
36
65
  context(session: LocalSession): Promise<{
37
66
  missions: {
@@ -42,13 +71,13 @@ export declare class LearningHost<S> {
42
71
  targets: `node-${string}`[];
43
72
  priority: number;
44
73
  run: {
45
- next: readonly import("@mmon-co/ncept-core").LessonReading[];
74
+ next: readonly LessonReading[];
46
75
  active: import("@mmon-co/ncept-core").SessionRef | null;
76
+ past: readonly import("@mmon-co/ncept-core").PastEntry[];
47
77
  retired?: Readonly<{
48
78
  outcome: "achieved" | "abandoned";
49
79
  at: string;
50
80
  }>;
51
- past: readonly import("@mmon-co/ncept-core").PastEntry[];
52
81
  asides: readonly import("@mmon-co/ncept-core").SessionRef[];
53
82
  };
54
83
  }[];
@@ -62,6 +91,9 @@ export declare class LearningHost<S> {
62
91
  about: readonly NodeId[];
63
92
  unscopedNodes?: readonly NodeId[];
64
93
  tutorMessages?: readonly string[];
94
+ opening?: Readonly<{
95
+ latestLearnerMessage?: string;
96
+ }>;
65
97
  sessionObservations?: readonly import("@mmon-co/ncept-core").ObservationId[];
66
98
  lessonActivities?: readonly import("@mmon-co/ncept-core").LessonActivity[];
67
99
  sessionMinutes?: number;
package/dist/learning.js CHANGED
@@ -6,7 +6,95 @@ import { localPayload, localSettings, platform, Runtime, sessionStates, transcri
6
6
  import { hostTools } from "./host-tools.js";
7
7
  import { mechanics } from "./mechanics.js";
8
8
  import { isSurface, modeEntry } from "./inputs.js";
9
- import { parsePiSession } from "./sessions.js";
9
+ import { object, parsePiSession } from "./sessions.js";
10
+ import { reviewStop, sessionLength } from "./session-policy.js";
11
+ function readMissions(view, complete = false) {
12
+ const projection = view.theory.project(view.graph, view.state);
13
+ const sessions = runs(sessionStates(view.profile));
14
+ return missions(view.profile).map((mission) => {
15
+ const run = missionRun(view.profile, mission.id);
16
+ const context = { graph: view.graph, projection, observations: view.observations, activities: [] };
17
+ const path = view.theory.path?.({
18
+ ...context,
19
+ targets: mission.targets.map(({ node }) => node),
20
+ past: run.past,
21
+ now: view.now,
22
+ minutes: sessionLength(localSettings(view.profile)),
23
+ ...(run.retired ? { retired: run.retired } : {}),
24
+ });
25
+ const itinerary = path ? readMissionPath(path, view.theory, context) : undefined;
26
+ const structured = itinerary?.sections.flatMap(({ lessons }) => lessons) ?? [];
27
+ return {
28
+ mission,
29
+ run: readMissionRun(run, sessions, complete ? run.past.length : 20),
30
+ path: itinerary,
31
+ next: (path?.future ?? [])
32
+ .filter((stop) => {
33
+ if (!stop.checkpoint || stop.checkpoint.required)
34
+ return true;
35
+ const progress = view.theory.progress(view.graph, projection, stop.nodes);
36
+ return stop.nodes.some((node) => !progress[node] || progress[node].status === "open");
37
+ })
38
+ .map((lesson, index) => ({
39
+ ...(structured.find((item) => item.kind === lesson.kind &&
40
+ item.tag === lesson.tag &&
41
+ JSON.stringify(item.nodes) === JSON.stringify(lesson.nodes)) ?? { ...lesson, number: index + 1, cleared: false }),
42
+ name: lesson.name ??
43
+ lesson.nodes.map((node) => stringProperty(view.graph, node, "display:label", node)).join(", "),
44
+ })),
45
+ };
46
+ });
47
+ }
48
+ /** Read current learning state without day processing, receipts, configuration writes or model calls. */
49
+ export async function openLearningReader(profileDir, theories) {
50
+ const profile = await openProfile(profileDir, theories, { readOnly: true });
51
+ const settings = localSettings(await profile.read());
52
+ const timezone = checkedTimezone(typeof settings.timezone === "string" ? settings.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
53
+ const runtime = new Runtime(profile, theories, async () => {
54
+ throw new Error("A learning read cannot request a model");
55
+ }, timezone);
56
+ return {
57
+ async reading() {
58
+ const view = await runtime.snapshot();
59
+ const projection = view.theory.project(view.graph, view.state);
60
+ const progress = view.theory.progress(view.graph, projection, view.graph.nodes.map(({ id }) => id));
61
+ const dueReview = [...tagIndex(projection)("review:due")];
62
+ const label = (id) => stringProperty(view.graph, id, "display:label", id);
63
+ return {
64
+ missions: readMissions(view, true),
65
+ nodes: view.graph.nodes.map(({ id }) => ({ id, label: label(id), status: progress[id]?.status ?? "open" })),
66
+ dueReview: dueReview.map((id) => ({ id, label: label(id) })),
67
+ sessions: sessionStates(view.profile).map((session) => ({
68
+ ...session,
69
+ title: sessionTitle(session, view.profile, label),
70
+ missionLabel: missions(view.profile).find((mission) => mission.id === session.mission)?.statement,
71
+ nodes: session.about.map((id) => ({ id, label: label(id) })),
72
+ })),
73
+ };
74
+ },
75
+ };
76
+ }
77
+ function sessionTitle(session, profile, label) {
78
+ const entry = session.entry;
79
+ const mode = session.mode.charAt(0).toUpperCase() + session.mode.slice(1);
80
+ let title = mode;
81
+ if (entry?.kind === "review")
82
+ title = "Review · " + entry.nodes.length + " due";
83
+ else {
84
+ const name = entry?.kind === "lesson"
85
+ ? entry.lesson.name
86
+ : entry?.kind === "mission"
87
+ ? missions(profile).find((mission) => mission.id === entry.id)?.statement
88
+ : entry?.kind === "target"
89
+ ? label(entry.node)
90
+ : entry?.kind === "goal"
91
+ ? entry.text
92
+ : undefined;
93
+ if (name)
94
+ title += " · " + name;
95
+ }
96
+ return title.slice(0, 200);
97
+ }
10
98
  function identity() {
11
99
  return crypto.randomUUID();
12
100
  }
@@ -121,31 +209,7 @@ export class LearningHost {
121
209
  return selected;
122
210
  }
123
211
  async missionReadings() {
124
- const view = await this.runtime.snapshot();
125
- const projection = view.theory.project(view.graph, view.state);
126
- const sessions = runs(sessionStates(view.profile));
127
- return missions(view.profile).map((mission) => {
128
- const run = missionRun(view.profile, mission.id);
129
- const context = { graph: view.graph, projection, observations: view.observations, activities: [] };
130
- const path = view.theory.path?.({
131
- ...context,
132
- targets: mission.targets.map(({ node }) => node),
133
- past: run.past,
134
- now: view.now,
135
- minutes: 30,
136
- ...(run.retired ? { retired: run.retired } : {}),
137
- });
138
- const structured = path
139
- ? readMissionPath(path, view.theory, context).sections.flatMap(({ lessons }) => lessons)
140
- : [];
141
- return {
142
- mission,
143
- run: readMissionRun(run, sessions),
144
- next: (path?.future ?? []).map((lesson, index) => structured.find((item) => item.kind === lesson.kind &&
145
- item.tag === lesson.tag &&
146
- JSON.stringify(item.nodes) === JSON.stringify(lesson.nodes)) ?? { ...lesson, number: index + 1, cleared: false }),
147
- };
148
- });
212
+ return readMissions(await this.runtime.snapshot());
149
213
  }
150
214
  async lessonEntry(missionId, number) {
151
215
  const view = await this.runtime.snapshot();
@@ -163,7 +227,7 @@ export class LearningHost {
163
227
  targets: reading.mission.targets.map(({ node }) => node),
164
228
  past: reading.run.past,
165
229
  now: view.now,
166
- minutes: 30,
230
+ minutes: sessionLength(localSettings(view.profile)),
167
231
  });
168
232
  if (!future)
169
233
  throw new Error("Theory provides no Mission path");
@@ -258,6 +322,20 @@ export class LearningHost {
258
322
  const current = await this.current(session);
259
323
  await this.runtime.profile.appendLog(await this.closingRun(current, await this.runtime.profile.read()));
260
324
  }
325
+ async settle(session) {
326
+ const current = await this.current(session);
327
+ if (current.closed || current.mode !== "lesson" || current.entry?.kind !== "lesson")
328
+ return;
329
+ if (!(await this.context(current)).lesson?.complete)
330
+ return;
331
+ await this.close(current);
332
+ return {
333
+ mode: "charting",
334
+ then: "next",
335
+ carry: { kind: "brief" },
336
+ entry: { kind: "mission", id: current.entry.lesson.mission.id },
337
+ };
338
+ }
261
339
  async retireMission(id, outcome) {
262
340
  const view = await this.runtime.snapshot();
263
341
  if (!missions(view.profile).some((mission) => mission.id === id))
@@ -265,15 +343,119 @@ export class LearningHost {
265
343
  const before = missionRun(view.profile, id);
266
344
  const cleared = setActive(before, { kind: "none" }, view.now, runs(sessionStates(view.profile)));
267
345
  const after = retire(cleared.run, outcome, view.now);
268
- const entries = [...runEntries(before, after, view.now)];
269
- for (const ref of cleared.close) {
270
- const session = sessionStates(view.profile).find(({ id }) => id === ref);
271
- if (session)
272
- entries.push(...(await this.closing(session)));
346
+ // Retirement changes the Mission run. Its conversations may still be mid-turn;
347
+ // their processes own Session closure and can finish recording that turn.
348
+ await this.runtime.profile.appendLog(runEntries(before, after, view.now));
349
+ }
350
+ async begin(intent) {
351
+ if (intent.kind === "new-mission")
352
+ return this.open({ mode: "charting" });
353
+ if (intent.kind === "review") {
354
+ const view = await this.runtime.snapshot();
355
+ const stop = reviewStop(view.theory, {
356
+ graph: view.graph,
357
+ projection: view.theory.project(view.graph, view.state),
358
+ observations: view.observations,
359
+ activities: [],
360
+ past: [],
361
+ now: view.now,
362
+ minutes: sessionLength(localSettings(view.profile)),
363
+ });
364
+ if (!stop?.nodes.length)
365
+ throw new Error("No review due");
366
+ return this.open({ mode: "lesson", entry: { kind: "review", nodes: stop.nodes } });
273
367
  }
274
- await this.runtime.profile.appendLog(entries);
368
+ if (!("missionId" in intent))
369
+ throw new Error("Expected a Mission entry");
370
+ const reading = (await this.missionReadings()).find(({ mission }) => mission.id === intent.missionId);
371
+ if (!reading || reading.run.retired?.outcome === "abandoned")
372
+ throw new Error("Mission is not available");
373
+ const { mission, run, next } = reading;
374
+ if (intent.kind === "continue" && run.active)
375
+ return this.open({ mode: "empty", resume: run.active });
376
+ if (run.retired && intent.kind !== "continue")
377
+ throw new Error("A finished Mission can only continue or resume a Session");
378
+ if (intent.kind === "skip-lesson" || intent.kind === "skip-to")
379
+ return this.open({ mode: "lesson", skip: { ...intent, mission: mission.id } });
380
+ if (intent.kind === "tell-tutor" && !intent.request.trim())
381
+ throw new Error("Tell the tutor what you want to change");
382
+ if (intent.kind === "revise-lesson") {
383
+ const view = await this.runtime.snapshot();
384
+ const active = sessionStates(view.profile).find(({ id }) => id === run.active);
385
+ if (active?.entry?.kind !== "lesson")
386
+ throw new Error("There is no active Lesson to revise");
387
+ return this.open({ mode: "lesson", entry: active.entry });
388
+ }
389
+ if (intent.kind === "tell-tutor" || intent.kind === "revise-route" || !mission.targets.length)
390
+ return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
391
+ const stop = next[0];
392
+ if (stop?.kind === "review")
393
+ return this.open({ mode: "lesson", entry: { kind: "review", nodes: stop.nodes }, mission: mission.id });
394
+ if (run.retired)
395
+ throw new Error("No review is due for this finished Mission");
396
+ if (!stop)
397
+ throw new Error("This Mission has no following stop; revise the route or finish it");
398
+ if (stop.checkpoint)
399
+ return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
400
+ return this.open({ mode: "lesson", entry: await this.lessonEntry(mission.id, stop.number) });
275
401
  }
276
402
  async open(input) {
403
+ const skipMission = input.skip?.mission;
404
+ let skipped = [];
405
+ if (input.skip) {
406
+ if (input.resume || input.entry)
407
+ throw new Error("A skip cannot resume or supply an entry");
408
+ const reading = (await this.missionReadings()).find(({ mission }) => mission.id === input.skip?.mission);
409
+ if (!reading)
410
+ throw new Error("Unknown Mission");
411
+ if (reading.run.retired)
412
+ throw new Error("A finished Mission can only continue or resume a Session");
413
+ const view = await this.runtime.snapshot();
414
+ const context = {
415
+ graph: view.graph,
416
+ projection: view.theory.project(view.graph, view.state),
417
+ observations: view.observations,
418
+ activities: [],
419
+ };
420
+ const future = view.theory.path?.({
421
+ ...context,
422
+ targets: reading.mission.targets.map(({ node }) => node),
423
+ past: reading.run.past,
424
+ now: view.now,
425
+ minutes: sessionLength(localSettings(view.profile)),
426
+ });
427
+ if (!future)
428
+ throw new Error("Theory provides no Mission path");
429
+ const stops = readMissionPath(future, view.theory, context).sections.flatMap(({ lessons }) => lessons);
430
+ const frozen = reading.run.past.find((entry) => entry.kind === "session" && entry.session === reading.run.active);
431
+ const frozenStop = frozen?.kind === "session" ? frozen.stop : undefined;
432
+ const activeIndex = frozenStop
433
+ ? stops.findIndex((stop) => stop.kind === frozenStop.kind &&
434
+ stop.nodes.length === frozenStop.nodes?.length &&
435
+ stop.nodes.every((node) => frozenStop.nodes?.includes(node)))
436
+ : -1;
437
+ const now = activeIndex >= 0 ? activeIndex : stops.findIndex((stop) => !stop.cleared);
438
+ const skip = input.skip;
439
+ const index = skip.kind === "skip-lesson"
440
+ ? now + 1
441
+ : stops.findIndex((stop) => stop.kind === skip.stop.kind &&
442
+ stop.number === skip.stop.number &&
443
+ stop.checkpoint?.milestone === skip.stop.checkpoint?.milestone);
444
+ if (index < 0 || !stops[index])
445
+ throw new Error("This Mission has no following stop; revise the route or finish it");
446
+ if (skip.kind === "skip-to") {
447
+ if (now < 0 || index <= now)
448
+ throw new Error("Choose a stop after the current stop");
449
+ skipped = stops.slice(now, index);
450
+ }
451
+ const stop = stops[index];
452
+ const entry = stop.kind === "review"
453
+ ? { kind: "review", nodes: stop.nodes }
454
+ : stop.checkpoint
455
+ ? { kind: "mission", id: reading.mission.id }
456
+ : await this.lessonEntry(reading.mission.id, stop.number);
457
+ input = { mode: stop.checkpoint ? "charting" : "lesson", entry };
458
+ }
277
459
  const view = await this.runtime.snapshot();
278
460
  const known = sessionStates(view.profile);
279
461
  let resumed = input.resume ? known.find(({ id }) => id === input.resume) : undefined;
@@ -320,7 +502,7 @@ export class LearningHost {
320
502
  ? entry.lesson.mission.id
321
503
  : entry?.kind === "checkpoint"
322
504
  ? entry.missionId
323
- : pending?.from.mission);
505
+ : (input.mission ?? skipMission ?? pending?.from.mission));
324
506
  const mission = missionId ? missions(view.profile).find(({ id }) => id === missionId) : undefined;
325
507
  if (missionId && !mission)
326
508
  throw new Error("Unknown Mission");
@@ -365,7 +547,10 @@ export class LearningHost {
365
547
  : pending?.to.then === "aside"
366
548
  ? { kind: "aside", session: id }
367
549
  : { kind: "new", session: id, stop };
368
- const result = setActive(before, target, view.now, runs(known));
550
+ // A fresh front end adopting an open aside keeps it beside its parent.
551
+ const result = resumed?.parent === before.active && !resumed.closed
552
+ ? { run: before, close: [] }
553
+ : setActive(before, target, view.now, runs(known));
369
554
  entries.push(...runEntries(before, result.run, view.now));
370
555
  for (const ref of result.close) {
371
556
  const outgoing = known.find(({ id }) => id === ref);
@@ -377,6 +562,34 @@ export class LearningHost {
377
562
  entries.push(...(await this.closingRun(pending.from, view.profile)));
378
563
  const event = await this.runtime.event({ kind: "surface.open", surface: session.surface, format: "local", about }, session);
379
564
  entries.push(...event.entries, platform({ kind: "local.session", session }, session.surface));
565
+ if (skipped.length) {
566
+ const nodes = [...new Set(skipped.flatMap((stop) => stop.nodes))];
567
+ const ctx = { ...(await this.runtime.context(session)), about: nodes };
568
+ const selected = view.theory.modes?.lesson;
569
+ const setup = selected ? await this.runtime.execute(selected.setup(ctx), session) : undefined;
570
+ const flatten = (tools) => tools.flatMap((tool) => (tool.members ? flatten(tool.members) : [tool]));
571
+ const tools = flatten(setup?.tools ?? []);
572
+ const record = tools.find((tool) => tool.name === "record_claim");
573
+ const attach = tools.find((tool) => tool.name === "attach_claim");
574
+ if (!record || !attach)
575
+ throw new Error("The theory needs claim recording and attachment");
576
+ const recordClaim = record.run;
577
+ const attachClaim = attach.run;
578
+ function* claims() {
579
+ for (const node of nodes) {
580
+ const result = yield* recordClaim({
581
+ statement: "I already know " + stringProperty(view.graph, node, "display:label", node) + ".",
582
+ prompt: "Skip to a later stop, marking the intervening stops as known",
583
+ stance: "knows",
584
+ }, ctx);
585
+ if (!object(result) || !object(result.observation) || typeof result.observation.id !== "string")
586
+ throw new Error("Claim recording returned no observation identity");
587
+ const id = result.observation.id;
588
+ yield* attachClaim({ record: id, nodes: [node] }, ctx);
589
+ }
590
+ }
591
+ entries.push(...(await this.runtime.prepare(claims(), session)).entries);
592
+ }
380
593
  await this.runtime.profile.appendLog(entries);
381
594
  if (pending)
382
595
  this.pendingSwitch = undefined;
@@ -496,6 +709,16 @@ export class LearningHost {
496
709
  view = await this.runtime.snapshot();
497
710
  ctx = await this.context(session);
498
711
  }
712
+ if (learnerMessage === undefined && transcript(view.profile, session.surface).turns.length === 0) {
713
+ const latest = sessionStates(view.profile)
714
+ .flatMap(({ surface }) => transcript(view.profile, surface).turns)
715
+ .filter(({ speaker, text }) => speaker.kind === "learner" && text.trim() !== "")
716
+ .sort((a, b) => b.at.localeCompare(a.at))[0];
717
+ ctx = {
718
+ ...ctx,
719
+ opening: { latestLearnerMessage: latest ? Array.from(latest.text).slice(0, 400).join("") : undefined },
720
+ };
721
+ }
499
722
  const selected = this.mode(view.theory, session.mode, session.entry);
500
723
  const program = selected ? selected.setup(ctx) : view.theory.chat?.turn(ctx);
501
724
  if (!program)
@@ -540,13 +763,19 @@ export class LearningHost {
540
763
  };
541
764
  }
542
765
  async config() {
543
- const { manifest } = await this.runtime.profile.read();
544
- return { theory: manifest.theory, theories: manifest.theories, timezone: this.runtime.timezone };
766
+ const profile = await this.runtime.profile.read();
767
+ return {
768
+ theory: profile.manifest.theory,
769
+ theories: profile.manifest.theories,
770
+ timezone: this.runtime.timezone,
771
+ sessionLength: sessionLength(localSettings(profile)),
772
+ };
545
773
  }
546
774
  async configure(config) {
547
775
  const timezone = checkedTimezone(config.timezone ?? this.runtime.timezone);
776
+ const minutes = sessionLength(config);
548
777
  await this.runtime.profile.configure({ theory: config.theory, theories: config.theories });
549
- await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone })]);
778
+ await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone, sessionLength: minutes })]);
550
779
  this.runtime.timezone = timezone;
551
780
  }
552
781
  async start() {
@@ -577,7 +806,9 @@ export async function openHost(options) {
577
806
  profile,
578
807
  sessions: {
579
808
  open: (input) => learning.serial(() => learning.open(input)),
809
+ begin: (intent) => learning.serial(() => learning.begin(intent)),
580
810
  turn: (session, input) => learning.serial(() => learning.turn(session, input.learnerMessage)),
811
+ settle: (session) => learning.serial(() => learning.settle(session)),
581
812
  close: (session) => learning.serial(() => learning.close(session)),
582
813
  },
583
814
  missions: {
package/dist/runtime.js CHANGED
@@ -1,4 +1,4 @@
1
- import { bundleForRevision, candidateRevision, effectiveObservations, isObservation, isContentDigest, readTheoryState, resolvePatchBundle, resolveTheory, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
1
+ import { notebookBundleForRevision, notebookSelection, candidateRevision, effectiveObservations, isObservation, isContentDigest, readTheoryState, resolvePatchBundle, resolveTheory, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
2
2
  import { object, parsePiSession, piActiveBranch } from "./sessions.js";
3
3
  import { learnerDayAt } from "./days.js";
4
4
  import { isMaterial, isObjectIdentity, isSurface, modeEntry, nodeIds, nonempty } from "./inputs.js";
@@ -122,9 +122,9 @@ export class Runtime {
122
122
  throw new Error("Invalid revision filename");
123
123
  contents.set(digest, JSON.parse(new TextDecoder().decode(bytes)));
124
124
  }
125
- bundle = bundleForRevision(ref, contents);
125
+ bundle = notebookBundleForRevision(ref, contents);
126
126
  }
127
- const graph = resolvePatchBundle(bundle, new Set(["local"]));
127
+ const graph = resolvePatchBundle(bundle, new Set(["local"]), notebookSelection(bundle));
128
128
  const now = new Date().toISOString();
129
129
  const observations = this.observations(profile, now);
130
130
  return {
@@ -159,7 +159,7 @@ export class Runtime {
159
159
  learnerDay: learnerDayAt(observation.at, this.timezone),
160
160
  ...(object(observation.payload) && object(observation.payload.material)
161
161
  ? {
162
- materialPresent: resolvePatchBundle(profile.patches).materials.some((material) => object(observation.payload) &&
162
+ materialPresent: resolvePatchBundle(profile.patches, undefined, notebookSelection(profile.patches)).materials.some((material) => object(observation.payload) &&
163
163
  object(observation.payload.material) &&
164
164
  material.id === observation.payload.material.id &&
165
165
  material.playground === observation.payload.material.playground),
@@ -311,8 +311,8 @@ export class Runtime {
311
311
  const revision = candidateRevision(view.graph.terminal.identity, content);
312
312
  const contents = new Map(view.bundle.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
313
313
  contents.set(revision.ref.digest, content);
314
- const bundle = bundleForRevision(revision.ref, contents);
315
- const graph = resolvePatchBundle(bundle, new Set(["local"]));
314
+ const bundle = notebookBundleForRevision(revision.ref, contents);
315
+ const graph = resolvePatchBundle(bundle, new Set(["local"]), notebookSelection(bundle));
316
316
  const profile = {
317
317
  ...view.profile,
318
318
  patches: bundle,
@@ -0,0 +1,25 @@
1
+ import type { PathContext, Theory } from "@mmon-co/ncept-core";
2
+ /** Profile learning preference; an unchosen Session length matches one unmeasured Lesson Node. */
3
+ export declare function sessionLength(values?: Readonly<{
4
+ sessionLength?: unknown;
5
+ }>): number;
6
+ /** Voluntary Review uses the Theory’s maintenance stop; blocking Reviews stay with their Lesson. */
7
+ export declare function reviewStop(theory: Pick<Theory<unknown>, "path">, context: PathContext): Readonly<{
8
+ kind: string;
9
+ name?: string;
10
+ nodes: readonly import("@mmon-co/ncept-core").NodeId[];
11
+ numbered: boolean;
12
+ numberOffset?: number;
13
+ tag?: string;
14
+ milestone?: import("@mmon-co/ncept-core").NodeId;
15
+ checkpoint?: Readonly<{
16
+ milestone?: import("@mmon-co/ncept-core").NodeId;
17
+ required: boolean;
18
+ final?: true;
19
+ updates?: readonly {
20
+ patch: string;
21
+ title: string;
22
+ version: string;
23
+ }[];
24
+ }>;
25
+ }> | undefined;
@@ -0,0 +1,13 @@
1
+ /** Profile learning preference; an unchosen Session length matches one unmeasured Lesson Node. */
2
+ export function sessionLength(values) {
3
+ const minutes = values?.sessionLength;
4
+ if (minutes === undefined)
5
+ return 20;
6
+ if (typeof minutes !== "number" || !Number.isFinite(minutes) || minutes <= 0)
7
+ throw new Error("Session length must be a positive number of minutes");
8
+ return minutes;
9
+ }
10
+ /** Voluntary Review uses the Theory’s maintenance stop; blocking Reviews stay with their Lesson. */
11
+ export function reviewStop(theory, context) {
12
+ return theory.path?.(context).future.find((stop) => stop.kind === "review" && !stop.numberOffset);
13
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmon-co/ncept-local",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,6 +22,10 @@
22
22
  "types": "./dist/exchange.d.ts",
23
23
  "default": "./dist/exchange.js"
24
24
  },
25
+ "./session-policy": {
26
+ "types": "./dist/session-policy.d.ts",
27
+ "default": "./dist/session-policy.js"
28
+ },
25
29
  "./sessions": {
26
30
  "types": "./dist/sessions.d.ts",
27
31
  "default": "./dist/sessions.js"
@@ -32,11 +36,13 @@
32
36
  "prepack": "bun run build"
33
37
  },
34
38
  "dependencies": {
35
- "@mmon-co/ncept-core": "^0.1.0",
36
- "@modelcontextprotocol/sdk": "1.32.1"
39
+ "@mmon-co/ncept-core": "^0.2.0",
40
+ "@modelcontextprotocol/sdk": "1.32.1",
41
+ "proper-lockfile": "4.1.2"
37
42
  },
38
43
  "devDependencies": {
39
- "@mmon-co/ncept-default-theory": "^1.0.0",
44
+ "@mmon-co/ncept-default-theory": "^1.1.0",
45
+ "@types/proper-lockfile": "^4.1.4",
40
46
  "bun-types": "^1.3.14",
41
47
  "typescript": "5.9.3"
42
48
  },