@mmon-co/ncept-local 0.1.0 → 0.3.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 +6 -4
- package/dist/directory.d.ts +5 -2
- package/dist/directory.js +60 -26
- package/dist/exchange.js +2 -2
- package/dist/host-tools.js +4 -2
- package/dist/host.d.ts +57 -6
- package/dist/hub.d.ts +11 -1
- package/dist/hub.js +157 -40
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/learning.d.ts +54 -12
- package/dist/learning.js +356 -54
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.js +7 -6
- package/dist/session-policy.d.ts +25 -0
- package/dist/session-policy.js +13 -0
- package/package.json +10 -4
package/dist/learning.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { isMission, isMissionRevision, isRunActiveChange, isRunPastEntry, isRunRetirement, nodeCascadedProperty, readMissionPath, readMissionRun, retire, selectGraph, setActive, tagIndex, } from "@mmon-co/ncept-core";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { lock } from "proper-lockfile";
|
|
2
4
|
import { openProfile } from "./directory.js";
|
|
3
5
|
import { connectHub } from "./hub.js";
|
|
4
6
|
import { checkedTimezone, learnerDayAt } from "./days.js";
|
|
@@ -6,7 +8,103 @@ import { localPayload, localSettings, platform, Runtime, sessionStates, transcri
|
|
|
6
8
|
import { hostTools } from "./host-tools.js";
|
|
7
9
|
import { mechanics } from "./mechanics.js";
|
|
8
10
|
import { isSurface, modeEntry } from "./inputs.js";
|
|
9
|
-
import { parsePiSession } from "./sessions.js";
|
|
11
|
+
import { object, parsePiSession } from "./sessions.js";
|
|
12
|
+
import { reviewStop, sessionLength } from "./session-policy.js";
|
|
13
|
+
function readMissions(view, complete = false) {
|
|
14
|
+
const projection = view.theory.project(view.graph, view.state);
|
|
15
|
+
const sessions = runs(sessionStates(view.profile));
|
|
16
|
+
return missions(view.profile).map((mission) => {
|
|
17
|
+
const run = missionRun(view.profile, mission.id);
|
|
18
|
+
const context = { graph: view.graph, projection, observations: view.observations, activities: [] };
|
|
19
|
+
const path = view.theory.path?.({
|
|
20
|
+
...context,
|
|
21
|
+
targets: mission.targets.map(({ node }) => node),
|
|
22
|
+
past: run.past,
|
|
23
|
+
now: view.now,
|
|
24
|
+
minutes: sessionLength(localSettings(view.profile)),
|
|
25
|
+
...(run.retired ? { retired: run.retired } : {}),
|
|
26
|
+
});
|
|
27
|
+
const itinerary = path ? readMissionPath(path, view.theory, context) : undefined;
|
|
28
|
+
const structured = itinerary?.sections.flatMap(({ lessons }) => lessons) ?? [];
|
|
29
|
+
return {
|
|
30
|
+
mission,
|
|
31
|
+
run: readMissionRun(run, sessions, complete ? run.past.length : 20),
|
|
32
|
+
path: itinerary,
|
|
33
|
+
next: (path?.future ?? [])
|
|
34
|
+
.filter((stop) => {
|
|
35
|
+
if (!stop.checkpoint || stop.checkpoint.required)
|
|
36
|
+
return true;
|
|
37
|
+
const progress = view.theory.progress(view.graph, projection, stop.nodes);
|
|
38
|
+
return stop.nodes.some((node) => !progress[node] || progress[node].status === "open");
|
|
39
|
+
})
|
|
40
|
+
.map((lesson, index) => ({
|
|
41
|
+
...(structured.find((item) => item.kind === lesson.kind &&
|
|
42
|
+
item.tag === lesson.tag &&
|
|
43
|
+
JSON.stringify(item.nodes) === JSON.stringify(lesson.nodes)) ?? { ...lesson, number: index + 1, cleared: false }),
|
|
44
|
+
name: lesson.name ??
|
|
45
|
+
lesson.nodes.map((node) => stringProperty(view.graph, node, "display:label", node)).join(", "),
|
|
46
|
+
})),
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** Read current learning state without day processing, receipts, configuration writes or model calls. */
|
|
51
|
+
export async function openLearningReader(profileDir, theories) {
|
|
52
|
+
const profile = await openProfile(profileDir, theories, { readOnly: true });
|
|
53
|
+
const settings = localSettings(await profile.read());
|
|
54
|
+
const timezone = checkedTimezone(typeof settings.timezone === "string" ? settings.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
55
|
+
const runtime = new Runtime(profile, theories, async () => {
|
|
56
|
+
throw new Error("A learning read cannot request a model");
|
|
57
|
+
}, timezone);
|
|
58
|
+
return {
|
|
59
|
+
async reading() {
|
|
60
|
+
const view = await runtime.snapshot();
|
|
61
|
+
const projection = view.theory.project(view.graph, view.state);
|
|
62
|
+
const progress = view.theory.progress(view.graph, projection, view.graph.nodes.map(({ id }) => id));
|
|
63
|
+
const tagged = tagIndex(projection);
|
|
64
|
+
const dueReview = [...tagged("review:due")];
|
|
65
|
+
const frontier = tagged("frontier");
|
|
66
|
+
const label = (id) => stringProperty(view.graph, id, "display:label", id);
|
|
67
|
+
return {
|
|
68
|
+
missions: readMissions(view, true),
|
|
69
|
+
nodes: view.graph.nodes.map(({ id }) => ({
|
|
70
|
+
id,
|
|
71
|
+
label: label(id),
|
|
72
|
+
status: progress[id]?.status ?? "open",
|
|
73
|
+
frontier: frontier.has(id),
|
|
74
|
+
})),
|
|
75
|
+
edges: view.graph.edges.map(({ from, to }) => ({ from, to })),
|
|
76
|
+
dueReview: dueReview.map((id) => ({ id, label: label(id) })),
|
|
77
|
+
sessions: sessionStates(view.profile).map((session) => ({
|
|
78
|
+
...session,
|
|
79
|
+
title: sessionTitle(session, view.profile, label),
|
|
80
|
+
missionLabel: missions(view.profile).find((mission) => mission.id === session.mission)?.statement,
|
|
81
|
+
nodes: session.about.map((id) => ({ id, label: label(id) })),
|
|
82
|
+
})),
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function sessionTitle(session, profile, label) {
|
|
88
|
+
const entry = session.entry;
|
|
89
|
+
const mode = session.mode.charAt(0).toUpperCase() + session.mode.slice(1);
|
|
90
|
+
let title = mode;
|
|
91
|
+
if (entry?.kind === "review")
|
|
92
|
+
title = "Review · " + entry.nodes.length + " due";
|
|
93
|
+
else {
|
|
94
|
+
const name = entry?.kind === "lesson"
|
|
95
|
+
? entry.lesson.name
|
|
96
|
+
: entry?.kind === "mission"
|
|
97
|
+
? missions(profile).find((mission) => mission.id === entry.id)?.statement
|
|
98
|
+
: entry?.kind === "target"
|
|
99
|
+
? label(entry.node)
|
|
100
|
+
: entry?.kind === "goal"
|
|
101
|
+
? entry.text
|
|
102
|
+
: undefined;
|
|
103
|
+
if (name)
|
|
104
|
+
title += " · " + name;
|
|
105
|
+
}
|
|
106
|
+
return title.slice(0, 200);
|
|
107
|
+
}
|
|
10
108
|
function identity() {
|
|
11
109
|
return crypto.randomUUID();
|
|
12
110
|
}
|
|
@@ -43,7 +141,7 @@ function missions(profile) {
|
|
|
43
141
|
function runs(sessions) {
|
|
44
142
|
return sessions.map((session) => ({
|
|
45
143
|
ref: session.id,
|
|
46
|
-
open: !session.closed,
|
|
144
|
+
open: !session.closed && !session.closing,
|
|
47
145
|
...(session.parent === undefined ? {} : { parent: session.parent }),
|
|
48
146
|
}));
|
|
49
147
|
}
|
|
@@ -85,12 +183,15 @@ function runEntries(before, after, at) {
|
|
|
85
183
|
export class LearningHost {
|
|
86
184
|
runtime;
|
|
87
185
|
confirm;
|
|
186
|
+
onCloseError;
|
|
88
187
|
tail = Promise.resolve();
|
|
89
188
|
pendingSwitch;
|
|
189
|
+
closeJobs = new Map();
|
|
90
190
|
drafts = new Map();
|
|
91
|
-
constructor(runtime, confirm) {
|
|
191
|
+
constructor(runtime, confirm, onCloseError = (error) => console.error("Session close failed:", error)) {
|
|
92
192
|
this.runtime = runtime;
|
|
93
193
|
this.confirm = confirm;
|
|
194
|
+
this.onCloseError = onCloseError;
|
|
94
195
|
}
|
|
95
196
|
serial(operation) {
|
|
96
197
|
const result = this.tail.then(operation);
|
|
@@ -121,31 +222,7 @@ export class LearningHost {
|
|
|
121
222
|
return selected;
|
|
122
223
|
}
|
|
123
224
|
async missionReadings() {
|
|
124
|
-
|
|
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
|
-
});
|
|
225
|
+
return readMissions(await this.runtime.snapshot());
|
|
149
226
|
}
|
|
150
227
|
async lessonEntry(missionId, number) {
|
|
151
228
|
const view = await this.runtime.snapshot();
|
|
@@ -163,7 +240,7 @@ export class LearningHost {
|
|
|
163
240
|
targets: reading.mission.targets.map(({ node }) => node),
|
|
164
241
|
past: reading.run.past,
|
|
165
242
|
now: view.now,
|
|
166
|
-
minutes:
|
|
243
|
+
minutes: sessionLength(localSettings(view.profile)),
|
|
167
244
|
});
|
|
168
245
|
if (!future)
|
|
169
246
|
throw new Error("Theory provides no Mission path");
|
|
@@ -228,10 +305,15 @@ export class LearningHost {
|
|
|
228
305
|
}, session);
|
|
229
306
|
return [
|
|
230
307
|
...event.entries,
|
|
231
|
-
platform({ kind: "local.session", session: { ...session, closed: true } }, session.surface),
|
|
308
|
+
platform({ kind: "local.session", session: { ...session, closing: undefined, closed: true } }, session.surface),
|
|
232
309
|
];
|
|
233
310
|
}
|
|
234
|
-
|
|
311
|
+
markClosing(session) {
|
|
312
|
+
return session.closed || session.closing
|
|
313
|
+
? []
|
|
314
|
+
: [platform({ kind: "local.session", session: { ...session, closing: identity() } }, session.surface)];
|
|
315
|
+
}
|
|
316
|
+
endingRun(current, profile) {
|
|
235
317
|
const known = sessionStates(profile);
|
|
236
318
|
const closing = new Set([current.id]);
|
|
237
319
|
for (const id of closing)
|
|
@@ -251,12 +333,69 @@ export class LearningHost {
|
|
|
251
333
|
}
|
|
252
334
|
for (const session of known)
|
|
253
335
|
if (closing.has(session.id))
|
|
254
|
-
entries.push(...
|
|
336
|
+
entries.push(...this.markClosing(session));
|
|
255
337
|
return entries;
|
|
256
338
|
}
|
|
257
|
-
async
|
|
339
|
+
async end(session) {
|
|
258
340
|
const current = await this.current(session);
|
|
259
|
-
await this.runtime.profile.appendLog(
|
|
341
|
+
await this.runtime.profile.appendLog(this.endingRun(current, await this.runtime.profile.read()));
|
|
342
|
+
}
|
|
343
|
+
async closePending() {
|
|
344
|
+
const pending = sessionStates(await this.runtime.profile.read()).filter((session) => !session.closed && session.closing);
|
|
345
|
+
const failures = [];
|
|
346
|
+
for (const session of pending) {
|
|
347
|
+
const key = session.closing;
|
|
348
|
+
if (!key)
|
|
349
|
+
continue;
|
|
350
|
+
let job = this.closeJobs.get(key);
|
|
351
|
+
if (!job) {
|
|
352
|
+
job = (async () => {
|
|
353
|
+
// The receiving thread's startup sweep may meet the source's background close.
|
|
354
|
+
// Lock only this close, leaving the Profile writable throughout model calls.
|
|
355
|
+
const release = await lock(join(this.runtime.profile.dir, ".close-" + encodeURIComponent(key)), {
|
|
356
|
+
realpath: false,
|
|
357
|
+
retries: { forever: true, minTimeout: 10, maxTimeout: 100, randomize: true },
|
|
358
|
+
});
|
|
359
|
+
try {
|
|
360
|
+
const before = await this.current(session);
|
|
361
|
+
if (before.closed || before.closing !== key)
|
|
362
|
+
return;
|
|
363
|
+
const entries = await this.closing(before);
|
|
364
|
+
// Check under the Profile write lock: another process may have resumed it.
|
|
365
|
+
await this.runtime.profile.appendLog(entries, (profile) => sessionStates(profile).some((current) => current.id === session.id && !current.closed && current.closing === key));
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
await release();
|
|
369
|
+
}
|
|
370
|
+
})();
|
|
371
|
+
this.closeJobs.set(key, job);
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
await job;
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
failures.push(error);
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
this.closeJobs.delete(key);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (failures.length)
|
|
384
|
+
throw new AggregateError(failures, "Session close failed");
|
|
385
|
+
}
|
|
386
|
+
async settle(session) {
|
|
387
|
+
const current = await this.current(session);
|
|
388
|
+
if (current.closed || current.closing || current.mode !== "lesson" || current.entry?.kind !== "lesson")
|
|
389
|
+
return;
|
|
390
|
+
if (!(await this.context(current)).lesson?.complete)
|
|
391
|
+
return;
|
|
392
|
+
await this.end(current);
|
|
393
|
+
return {
|
|
394
|
+
mode: "charting",
|
|
395
|
+
then: "next",
|
|
396
|
+
carry: { kind: "brief" },
|
|
397
|
+
entry: { kind: "mission", id: current.entry.lesson.mission.id },
|
|
398
|
+
};
|
|
260
399
|
}
|
|
261
400
|
async retireMission(id, outcome) {
|
|
262
401
|
const view = await this.runtime.snapshot();
|
|
@@ -265,15 +404,119 @@ export class LearningHost {
|
|
|
265
404
|
const before = missionRun(view.profile, id);
|
|
266
405
|
const cleared = setActive(before, { kind: "none" }, view.now, runs(sessionStates(view.profile)));
|
|
267
406
|
const after = retire(cleared.run, outcome, view.now);
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
407
|
+
// Retirement changes the Mission run. Its conversations may still be mid-turn;
|
|
408
|
+
// their processes own Session closure and can finish recording that turn.
|
|
409
|
+
await this.runtime.profile.appendLog(runEntries(before, after, view.now));
|
|
410
|
+
}
|
|
411
|
+
async begin(intent) {
|
|
412
|
+
if (intent.kind === "new-mission")
|
|
413
|
+
return this.open({ mode: "charting" });
|
|
414
|
+
if (intent.kind === "review") {
|
|
415
|
+
const view = await this.runtime.snapshot();
|
|
416
|
+
const stop = reviewStop(view.theory, {
|
|
417
|
+
graph: view.graph,
|
|
418
|
+
projection: view.theory.project(view.graph, view.state),
|
|
419
|
+
observations: view.observations,
|
|
420
|
+
activities: [],
|
|
421
|
+
past: [],
|
|
422
|
+
now: view.now,
|
|
423
|
+
minutes: sessionLength(localSettings(view.profile)),
|
|
424
|
+
});
|
|
425
|
+
if (!stop?.nodes.length)
|
|
426
|
+
throw new Error("No review due");
|
|
427
|
+
return this.open({ mode: "lesson", entry: { kind: "review", nodes: stop.nodes } });
|
|
273
428
|
}
|
|
274
|
-
|
|
429
|
+
if (!("missionId" in intent))
|
|
430
|
+
throw new Error("Expected a Mission entry");
|
|
431
|
+
const reading = (await this.missionReadings()).find(({ mission }) => mission.id === intent.missionId);
|
|
432
|
+
if (!reading || reading.run.retired?.outcome === "abandoned")
|
|
433
|
+
throw new Error("Mission is not available");
|
|
434
|
+
const { mission, run, next } = reading;
|
|
435
|
+
if (intent.kind === "continue" && run.active)
|
|
436
|
+
return this.open({ mode: "empty", resume: run.active });
|
|
437
|
+
if (run.retired && intent.kind !== "continue")
|
|
438
|
+
throw new Error("A finished Mission can only continue or resume a Session");
|
|
439
|
+
if (intent.kind === "skip-lesson" || intent.kind === "skip-to")
|
|
440
|
+
return this.open({ mode: "lesson", skip: { ...intent, mission: mission.id } });
|
|
441
|
+
if (intent.kind === "tell-tutor" && !intent.request.trim())
|
|
442
|
+
throw new Error("Tell the tutor what you want to change");
|
|
443
|
+
if (intent.kind === "revise-lesson") {
|
|
444
|
+
const view = await this.runtime.snapshot();
|
|
445
|
+
const active = sessionStates(view.profile).find(({ id }) => id === run.active);
|
|
446
|
+
if (active?.entry?.kind !== "lesson")
|
|
447
|
+
throw new Error("There is no active Lesson to revise");
|
|
448
|
+
return this.open({ mode: "lesson", entry: active.entry });
|
|
449
|
+
}
|
|
450
|
+
if (intent.kind === "tell-tutor" || intent.kind === "revise-route" || !mission.targets.length)
|
|
451
|
+
return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
|
|
452
|
+
const stop = next[0];
|
|
453
|
+
if (stop?.kind === "review")
|
|
454
|
+
return this.open({ mode: "lesson", entry: { kind: "review", nodes: stop.nodes }, mission: mission.id });
|
|
455
|
+
if (run.retired)
|
|
456
|
+
throw new Error("No review is due for this finished Mission");
|
|
457
|
+
if (!stop)
|
|
458
|
+
throw new Error("This Mission has no following stop; revise the route or finish it");
|
|
459
|
+
if (stop.checkpoint)
|
|
460
|
+
return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
|
|
461
|
+
return this.open({ mode: "lesson", entry: await this.lessonEntry(mission.id, stop.number) });
|
|
275
462
|
}
|
|
276
463
|
async open(input) {
|
|
464
|
+
const skipMission = input.skip?.mission;
|
|
465
|
+
let skipped = [];
|
|
466
|
+
if (input.skip) {
|
|
467
|
+
if (input.resume || input.entry)
|
|
468
|
+
throw new Error("A skip cannot resume or supply an entry");
|
|
469
|
+
const reading = (await this.missionReadings()).find(({ mission }) => mission.id === input.skip?.mission);
|
|
470
|
+
if (!reading)
|
|
471
|
+
throw new Error("Unknown Mission");
|
|
472
|
+
if (reading.run.retired)
|
|
473
|
+
throw new Error("A finished Mission can only continue or resume a Session");
|
|
474
|
+
const view = await this.runtime.snapshot();
|
|
475
|
+
const context = {
|
|
476
|
+
graph: view.graph,
|
|
477
|
+
projection: view.theory.project(view.graph, view.state),
|
|
478
|
+
observations: view.observations,
|
|
479
|
+
activities: [],
|
|
480
|
+
};
|
|
481
|
+
const future = view.theory.path?.({
|
|
482
|
+
...context,
|
|
483
|
+
targets: reading.mission.targets.map(({ node }) => node),
|
|
484
|
+
past: reading.run.past,
|
|
485
|
+
now: view.now,
|
|
486
|
+
minutes: sessionLength(localSettings(view.profile)),
|
|
487
|
+
});
|
|
488
|
+
if (!future)
|
|
489
|
+
throw new Error("Theory provides no Mission path");
|
|
490
|
+
const stops = readMissionPath(future, view.theory, context).sections.flatMap(({ lessons }) => lessons);
|
|
491
|
+
const frozen = reading.run.past.find((entry) => entry.kind === "session" && entry.session === reading.run.active);
|
|
492
|
+
const frozenStop = frozen?.kind === "session" ? frozen.stop : undefined;
|
|
493
|
+
const activeIndex = frozenStop
|
|
494
|
+
? stops.findIndex((stop) => stop.kind === frozenStop.kind &&
|
|
495
|
+
stop.nodes.length === frozenStop.nodes?.length &&
|
|
496
|
+
stop.nodes.every((node) => frozenStop.nodes?.includes(node)))
|
|
497
|
+
: -1;
|
|
498
|
+
const now = activeIndex >= 0 ? activeIndex : stops.findIndex((stop) => !stop.cleared);
|
|
499
|
+
const skip = input.skip;
|
|
500
|
+
const index = skip.kind === "skip-lesson"
|
|
501
|
+
? now + 1
|
|
502
|
+
: stops.findIndex((stop) => stop.kind === skip.stop.kind &&
|
|
503
|
+
stop.number === skip.stop.number &&
|
|
504
|
+
stop.checkpoint?.milestone === skip.stop.checkpoint?.milestone);
|
|
505
|
+
if (index < 0 || !stops[index])
|
|
506
|
+
throw new Error("This Mission has no following stop; revise the route or finish it");
|
|
507
|
+
if (skip.kind === "skip-to") {
|
|
508
|
+
if (now < 0 || index <= now)
|
|
509
|
+
throw new Error("Choose a stop after the current stop");
|
|
510
|
+
skipped = stops.slice(now, index);
|
|
511
|
+
}
|
|
512
|
+
const stop = stops[index];
|
|
513
|
+
const entry = stop.kind === "review"
|
|
514
|
+
? { kind: "review", nodes: stop.nodes }
|
|
515
|
+
: stop.checkpoint
|
|
516
|
+
? { kind: "mission", id: reading.mission.id }
|
|
517
|
+
: await this.lessonEntry(reading.mission.id, stop.number);
|
|
518
|
+
input = { mode: stop.checkpoint ? "charting" : "lesson", entry };
|
|
519
|
+
}
|
|
277
520
|
const view = await this.runtime.snapshot();
|
|
278
521
|
const known = sessionStates(view.profile);
|
|
279
522
|
let resumed = input.resume ? known.find(({ id }) => id === input.resume) : undefined;
|
|
@@ -320,7 +563,7 @@ export class LearningHost {
|
|
|
320
563
|
? entry.lesson.mission.id
|
|
321
564
|
: entry?.kind === "checkpoint"
|
|
322
565
|
? entry.missionId
|
|
323
|
-
: pending?.from.mission);
|
|
566
|
+
: (input.mission ?? skipMission ?? pending?.from.mission));
|
|
324
567
|
const mission = missionId ? missions(view.profile).find(({ id }) => id === missionId) : undefined;
|
|
325
568
|
if (missionId && !mission)
|
|
326
569
|
throw new Error("Unknown Mission");
|
|
@@ -365,18 +608,49 @@ export class LearningHost {
|
|
|
365
608
|
: pending?.to.then === "aside"
|
|
366
609
|
? { kind: "aside", session: id }
|
|
367
610
|
: { kind: "new", session: id, stop };
|
|
368
|
-
|
|
611
|
+
// A fresh front end adopting an open aside keeps it beside its parent.
|
|
612
|
+
const result = resumed?.parent === before.active && !resumed.closed
|
|
613
|
+
? { run: before, close: [] }
|
|
614
|
+
: setActive(before, target, view.now, runs(known));
|
|
369
615
|
entries.push(...runEntries(before, result.run, view.now));
|
|
370
616
|
for (const ref of result.close) {
|
|
371
617
|
const outgoing = known.find(({ id }) => id === ref);
|
|
372
618
|
if (outgoing)
|
|
373
|
-
entries.push(...
|
|
619
|
+
entries.push(...this.markClosing(outgoing));
|
|
374
620
|
}
|
|
375
621
|
}
|
|
376
622
|
if (pending?.to.then === "next" && (!missionId || pending.from.mission !== missionId))
|
|
377
|
-
entries.push(...
|
|
623
|
+
entries.push(...this.endingRun(pending.from, view.profile));
|
|
378
624
|
const event = await this.runtime.event({ kind: "surface.open", surface: session.surface, format: "local", about }, session);
|
|
379
625
|
entries.push(...event.entries, platform({ kind: "local.session", session }, session.surface));
|
|
626
|
+
if (skipped.length) {
|
|
627
|
+
const nodes = [...new Set(skipped.flatMap((stop) => stop.nodes))];
|
|
628
|
+
const ctx = { ...(await this.runtime.context(session)), about: nodes };
|
|
629
|
+
const selected = view.theory.modes?.lesson;
|
|
630
|
+
const setup = selected ? await this.runtime.execute(selected.setup(ctx), session) : undefined;
|
|
631
|
+
const flatten = (tools) => tools.flatMap((tool) => (tool.members ? flatten(tool.members) : [tool]));
|
|
632
|
+
const tools = flatten(setup?.tools ?? []);
|
|
633
|
+
const record = tools.find((tool) => tool.name === "record_claim");
|
|
634
|
+
const attach = tools.find((tool) => tool.name === "attach_claim");
|
|
635
|
+
if (!record || !attach)
|
|
636
|
+
throw new Error("The theory needs claim recording and attachment");
|
|
637
|
+
const recordClaim = record.run;
|
|
638
|
+
const attachClaim = attach.run;
|
|
639
|
+
function* claims() {
|
|
640
|
+
for (const node of nodes) {
|
|
641
|
+
const result = yield* recordClaim({
|
|
642
|
+
statement: "I already know " + stringProperty(view.graph, node, "display:label", node) + ".",
|
|
643
|
+
prompt: "Skip to a later stop, marking the intervening stops as known",
|
|
644
|
+
stance: "knows",
|
|
645
|
+
}, ctx);
|
|
646
|
+
if (!object(result) || !object(result.observation) || typeof result.observation.id !== "string")
|
|
647
|
+
throw new Error("Claim recording returned no observation identity");
|
|
648
|
+
const id = result.observation.id;
|
|
649
|
+
yield* attachClaim({ record: id, nodes: [node] }, ctx);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
entries.push(...(await this.runtime.prepare(claims(), session)).entries);
|
|
653
|
+
}
|
|
380
654
|
await this.runtime.profile.appendLog(entries);
|
|
381
655
|
if (pending)
|
|
382
656
|
this.pendingSwitch = undefined;
|
|
@@ -427,7 +701,7 @@ export class LearningHost {
|
|
|
427
701
|
for (const id of result.close) {
|
|
428
702
|
const outgoing = sessionStates(view.profile).find((item) => item.id === id);
|
|
429
703
|
if (outgoing)
|
|
430
|
-
entries.push(...
|
|
704
|
+
entries.push(...this.markClosing(outgoing));
|
|
431
705
|
}
|
|
432
706
|
}
|
|
433
707
|
entries.push(platform({ kind: "local.session", session: updated }, session.surface));
|
|
@@ -487,8 +761,8 @@ export class LearningHost {
|
|
|
487
761
|
}
|
|
488
762
|
async turn(input, learnerMessage) {
|
|
489
763
|
const session = await this.current(input);
|
|
490
|
-
if (session.closed)
|
|
491
|
-
throw new Error("Session is
|
|
764
|
+
if (session.closed || session.closing)
|
|
765
|
+
throw new Error("Session is ended; resume it first");
|
|
492
766
|
let view = await this.runtime.snapshot();
|
|
493
767
|
let ctx = await this.context(session);
|
|
494
768
|
if (learnerMessage !== undefined && view.theory.chat?.reply) {
|
|
@@ -496,6 +770,16 @@ export class LearningHost {
|
|
|
496
770
|
view = await this.runtime.snapshot();
|
|
497
771
|
ctx = await this.context(session);
|
|
498
772
|
}
|
|
773
|
+
if (learnerMessage === undefined && transcript(view.profile, session.surface).turns.length === 0) {
|
|
774
|
+
const latest = sessionStates(view.profile)
|
|
775
|
+
.flatMap(({ surface }) => transcript(view.profile, surface).turns)
|
|
776
|
+
.filter(({ speaker, text }) => speaker.kind === "learner" && text.trim() !== "")
|
|
777
|
+
.sort((a, b) => b.at.localeCompare(a.at))[0];
|
|
778
|
+
ctx = {
|
|
779
|
+
...ctx,
|
|
780
|
+
opening: { latestLearnerMessage: latest ? Array.from(latest.text).slice(0, 400).join("") : undefined },
|
|
781
|
+
};
|
|
782
|
+
}
|
|
499
783
|
const selected = this.mode(view.theory, session.mode, session.entry);
|
|
500
784
|
const program = selected ? selected.setup(ctx) : view.theory.chat?.turn(ctx);
|
|
501
785
|
if (!program)
|
|
@@ -509,7 +793,7 @@ export class LearningHost {
|
|
|
509
793
|
schema: tool.schema,
|
|
510
794
|
run: (args) => this.serial(async () => {
|
|
511
795
|
const current = await this.current(session);
|
|
512
|
-
if (current.closed || current.mode !== session.mode)
|
|
796
|
+
if (current.closed || current.closing || current.mode !== session.mode)
|
|
513
797
|
throw new Error("Tool belongs to an inactive Session mode");
|
|
514
798
|
const result = await this.runtime.prepare(tool.run(args, await this.context(current)), current);
|
|
515
799
|
const feature = await this.runtime.event({ kind: "feature.used", operation: tool.name, at: new Date().toISOString(), about: current.about }, current);
|
|
@@ -540,13 +824,19 @@ export class LearningHost {
|
|
|
540
824
|
};
|
|
541
825
|
}
|
|
542
826
|
async config() {
|
|
543
|
-
const
|
|
544
|
-
return {
|
|
827
|
+
const profile = await this.runtime.profile.read();
|
|
828
|
+
return {
|
|
829
|
+
theory: profile.manifest.theory,
|
|
830
|
+
theories: profile.manifest.theories,
|
|
831
|
+
timezone: this.runtime.timezone,
|
|
832
|
+
sessionLength: sessionLength(localSettings(profile)),
|
|
833
|
+
};
|
|
545
834
|
}
|
|
546
835
|
async configure(config) {
|
|
547
836
|
const timezone = checkedTimezone(config.timezone ?? this.runtime.timezone);
|
|
837
|
+
const minutes = sessionLength(config);
|
|
548
838
|
await this.runtime.profile.configure({ theory: config.theory, theories: config.theories });
|
|
549
|
-
await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone })]);
|
|
839
|
+
await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone, sessionLength: minutes })]);
|
|
550
840
|
this.runtime.timezone = timezone;
|
|
551
841
|
}
|
|
552
842
|
async start() {
|
|
@@ -564,21 +854,32 @@ export class LearningHost {
|
|
|
564
854
|
}
|
|
565
855
|
if (typeof localSettings(view.profile).timezone !== "string")
|
|
566
856
|
await this.runtime.profile.appendLog([platform({ kind: "local.config", timezone: this.runtime.timezone })]);
|
|
857
|
+
// Only persisted closing tokens record an interrupted close. An unmarked Session
|
|
858
|
+
// may still be live in another host, including Charting without a Mission run.
|
|
859
|
+
// Recovery must not delay startup of a thread receiving a Session handoff.
|
|
860
|
+
void this.closePending().catch(this.onCloseError);
|
|
567
861
|
}
|
|
568
862
|
}
|
|
569
863
|
export async function openHost(options) {
|
|
570
864
|
const profile = await openProfile(options.profileDir, options.theories);
|
|
571
865
|
const config = localSettings(await profile.read());
|
|
572
866
|
const timezone = checkedTimezone(typeof config.timezone === "string" ? config.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
573
|
-
const learning = new LearningHost(new Runtime(profile, options.theories, options.model, timezone), options.confirm);
|
|
867
|
+
const learning = new LearningHost(new Runtime(profile, options.theories, options.model, timezone), options.confirm, options.onCloseError ?? ((error) => console.error("Session close failed:", error)));
|
|
574
868
|
await learning.start();
|
|
575
|
-
const hub = connectHub(profile, options.theories, options.confirm, options.hub);
|
|
869
|
+
const hub = connectHub(profile, options.theories, options.confirm, (mission) => learning.reviseMission(mission, true), options.hub);
|
|
576
870
|
return {
|
|
577
871
|
profile,
|
|
578
872
|
sessions: {
|
|
579
873
|
open: (input) => learning.serial(() => learning.open(input)),
|
|
874
|
+
begin: (intent) => learning.serial(() => learning.begin(intent)),
|
|
580
875
|
turn: (session, input) => learning.serial(() => learning.turn(session, input.learnerMessage)),
|
|
581
|
-
|
|
876
|
+
settle: (session) => learning.serial(() => learning.settle(session)),
|
|
877
|
+
end: (session) => learning.serial(() => learning.end(session)),
|
|
878
|
+
closePending: () => learning.closePending(),
|
|
879
|
+
close: async (session) => {
|
|
880
|
+
await learning.serial(() => learning.end(session));
|
|
881
|
+
await learning.closePending();
|
|
882
|
+
},
|
|
582
883
|
},
|
|
583
884
|
missions: {
|
|
584
885
|
list: () => learning.missionReadings(),
|
|
@@ -592,6 +893,7 @@ export async function openHost(options) {
|
|
|
592
893
|
pull: (address) => learning.serial(() => hub.pull(address)),
|
|
593
894
|
signIn: () => learning.serial(() => hub.signIn()),
|
|
594
895
|
publish: (input) => learning.serial(() => hub.publish(input)),
|
|
896
|
+
share: (input) => learning.serial(() => hub.share(input)),
|
|
595
897
|
exportTo: (destination) => learning.serial(() => hub.exportTo(destination)),
|
|
596
898
|
importFrom: (source) => learning.serial(async () => {
|
|
597
899
|
const result = await hub.importFrom(source);
|
package/dist/runtime.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export interface LocalSession extends HostSession {
|
|
|
6
6
|
readonly surface: SurfaceId;
|
|
7
7
|
readonly about: readonly NodeId[];
|
|
8
8
|
readonly closed: boolean;
|
|
9
|
+
/** Identifies a pending close; resuming the Session clears it. */
|
|
10
|
+
readonly closing?: string;
|
|
9
11
|
readonly mission?: string;
|
|
10
12
|
readonly parent?: string;
|
|
11
13
|
}
|
package/dist/runtime.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
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";
|
|
@@ -38,6 +38,7 @@ export function sessionStates(profile) {
|
|
|
38
38
|
surface: session.surface,
|
|
39
39
|
mode: session.mode,
|
|
40
40
|
closed: session.closed,
|
|
41
|
+
...(typeof session.closing === "string" ? { closing: session.closing } : {}),
|
|
41
42
|
about: nodeIds(session.about),
|
|
42
43
|
...(session.entry === undefined ? {} : { entry: modeEntry(session.entry) }),
|
|
43
44
|
...(typeof session.mission === "string" ? { mission: session.mission } : {}),
|
|
@@ -122,9 +123,9 @@ export class Runtime {
|
|
|
122
123
|
throw new Error("Invalid revision filename");
|
|
123
124
|
contents.set(digest, JSON.parse(new TextDecoder().decode(bytes)));
|
|
124
125
|
}
|
|
125
|
-
bundle =
|
|
126
|
+
bundle = notebookBundleForRevision(ref, contents);
|
|
126
127
|
}
|
|
127
|
-
const graph = resolvePatchBundle(bundle, new Set(["local"]));
|
|
128
|
+
const graph = resolvePatchBundle(bundle, new Set(["local"]), notebookSelection(bundle));
|
|
128
129
|
const now = new Date().toISOString();
|
|
129
130
|
const observations = this.observations(profile, now);
|
|
130
131
|
return {
|
|
@@ -159,7 +160,7 @@ export class Runtime {
|
|
|
159
160
|
learnerDay: learnerDayAt(observation.at, this.timezone),
|
|
160
161
|
...(object(observation.payload) && object(observation.payload.material)
|
|
161
162
|
? {
|
|
162
|
-
materialPresent: resolvePatchBundle(profile.patches).materials.some((material) => object(observation.payload) &&
|
|
163
|
+
materialPresent: resolvePatchBundle(profile.patches, undefined, notebookSelection(profile.patches)).materials.some((material) => object(observation.payload) &&
|
|
163
164
|
object(observation.payload.material) &&
|
|
164
165
|
material.id === observation.payload.material.id &&
|
|
165
166
|
material.playground === observation.payload.material.playground),
|
|
@@ -311,8 +312,8 @@ export class Runtime {
|
|
|
311
312
|
const revision = candidateRevision(view.graph.terminal.identity, content);
|
|
312
313
|
const contents = new Map(view.bundle.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
|
|
313
314
|
contents.set(revision.ref.digest, content);
|
|
314
|
-
const bundle =
|
|
315
|
-
const graph = resolvePatchBundle(bundle, new Set(["local"]));
|
|
315
|
+
const bundle = notebookBundleForRevision(revision.ref, contents);
|
|
316
|
+
const graph = resolvePatchBundle(bundle, new Set(["local"]), notebookSelection(bundle));
|
|
316
317
|
const profile = {
|
|
317
318
|
...view.profile,
|
|
318
319
|
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
|
+
}
|