@mmon-co/ncept-local 0.3.11 → 0.3.13

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/dist/hub.js CHANGED
@@ -2,12 +2,13 @@ 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
4
  import metadata from "../package.json" with { type: "json" };
5
- import { attachmentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isMissionRevision, latestMissionRevision, isPatchId, migrateTheoryPatchClosure, notebookSelection, PATCH_MISSIONS_PROPERTY, readReifiedMissions, reifyProfileMissions, relocateGuidance, reifyView, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, selectGraph, withReifiedMissions, } from "@mmon-co/ncept-core";
5
+ import { attachmentDigest, contentAttachments, extractSparseClosure, exactPatchRefKey, isContentDigest, isMissionRevision, latestMissionRevision, isPatchId, migrateTheoryPatchClosure, PATCH_MISSIONS_PROPERTY, readReifiedMissions, reifyProfileMissions, relocateGuidance, reifyView, releasePrecedenceKey, resolveTheory, resolveSparsePatch, resolvedGraphAttachments, revisionContent, theoryPatchNeedsMigration, verifySparseBundle, sameExactPatchRef, selectGraph, withReifiedMissions, } 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";
8
8
  import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
9
9
  import { hubBaseUrl, HubAuth, HubSignInRequired } from "./hub-auth.js";
10
10
  import { unpackDirectory } from "./directory.js";
11
+ import { PackedPatches } from "./packed.js";
11
12
  import { object, parsePiSession } from "./sessions.js";
12
13
  import { validate, unpack } from "./exchange.js";
13
14
  /**
@@ -15,8 +16,7 @@ import { validate, unpack } from "./exchange.js";
15
16
  * the release carries that map alone whatever Patches it was learnt from, and offering the
16
17
  * Mission to whoever opens it.
17
18
  */
18
- export function missionBundle(patches, mission, title, origin) {
19
- const graph = resolvePatchBundle(patches, new Set(["local"]), notebookSelection(patches));
19
+ export async function missionBundle(graph, mission, title, origin) {
20
20
  const cone = selectGraph(graph, { cone: { targets: mission.targets.map(({ node }) => node) } });
21
21
  if (!cone.nodes.length)
22
22
  throw new Error("This Mission has no map yet");
@@ -48,9 +48,9 @@ export function missionBundle(patches, mission, title, origin) {
48
48
  citations: reified.metadata.citations.filter((citation) => citation.kind !== "reified_from"),
49
49
  }, [suggestion]),
50
50
  };
51
- const revision = candidateRevision(`patch-${randomUUID()}`, content);
52
- const bundle = bundleForRevision(revision.ref, new Map([[revision.ref.digest, content]]));
53
- resolvePatchBundle(bundle);
51
+ const store = new PackedPatches();
52
+ const terminal = { identity: `patch-${randomUUID()}`, digest: store.add(content) };
53
+ const bundle = await extractSparseClosure(terminal, store, { completeTerminal: true });
54
54
  return { bundle, skills: cone.nodes.length };
55
55
  }
56
56
  function releaseAddress(value, base) {
@@ -74,49 +74,67 @@ async function fetched(url, init) {
74
74
  throw new Error("Hub request failed (" + response.status + "): " + (await response.text()));
75
75
  return response;
76
76
  }
77
- function attachments(bundle) {
78
- const found = new Map();
79
- const add = (values) => {
80
- for (const value of values)
81
- if (isAttachment(value))
82
- found.set(value.hash, value);
83
- };
84
- for (const revision of bundle.revisions) {
85
- add(Object.values(revision.metadata.properties));
86
- for (const operation of revision.delta.operations) {
87
- if (operation.kind === "add-metadata-set")
88
- add(Object.values(operation.metadataSet.properties));
89
- if (operation.kind === "add-material" || operation.kind === "edit-material") {
90
- add([operation.material.content, ...Object.values(operation.material.meta)]);
77
+ async function fetchReleaseBlobs(endpoint, headers, graph) {
78
+ const hashes = [...new Set(Array.from(resolvedGraphAttachments(graph), (item) => item.hash))];
79
+ const blobs = new Map();
80
+ function retain(hash, bytes) {
81
+ if (attachmentDigest(bytes) !== hash)
82
+ throw new Error("Hub attachment digest mismatch: " + hash);
83
+ blobs.set(hash, bytes);
84
+ }
85
+ let legacy = false;
86
+ async function batch(group) {
87
+ if (!legacy) {
88
+ const response = await fetch(endpoint + "/attachments", {
89
+ method: "POST",
90
+ headers: { ...headers, "Content-Type": "application/json" },
91
+ body: JSON.stringify({ hashes: group }),
92
+ signal: AbortSignal.timeout(120_000),
93
+ });
94
+ const batchRoute = response.headers.has("X-Hub-Attachment-Batch");
95
+ if (response.ok && batchRoute) {
96
+ const bytes = await response.arrayBuffer();
97
+ const frame = new DataView(bytes);
98
+ let offset = 0;
99
+ for (const hash of group) {
100
+ const length = frame.getUint32(offset);
101
+ retain(hash, new Uint8Array(bytes, offset + 4, length));
102
+ offset += 4 + length;
103
+ }
104
+ if (offset !== bytes.byteLength)
105
+ throw new Error("Unexpected Hub attachment frame");
106
+ return;
107
+ }
108
+ if (response.status === 413) {
109
+ if (group.length > 1) {
110
+ const mid = Math.ceil(group.length / 2);
111
+ await batch(group.slice(0, mid));
112
+ await batch(group.slice(mid));
113
+ return;
114
+ }
91
115
  }
116
+ else if (!batchRoute && (response.ok || response.status === 404 || response.status === 405)) {
117
+ await response.body?.cancel();
118
+ legacy = true;
119
+ }
120
+ else
121
+ throw new Error("Hub request failed (" + response.status + "): " + (await response.text()));
92
122
  }
123
+ for (const hash of group)
124
+ retain(hash, new Uint8Array(await (await fetched(endpoint + "/attachments/" + hash, { headers })).arrayBuffer()));
93
125
  }
94
- return [...found.values()];
126
+ for (let i = 0; i < hashes.length; i += 256)
127
+ await batch(hashes.slice(i, i + 256));
128
+ return blobs;
95
129
  }
96
- /** Reject malformed wire data before handing its typed operations to Core's bundle verifier. */
97
- function verifiedBundle(value) {
98
- if (!object(value) || !object(value.terminal) || !Array.isArray(value.revisions))
99
- throw new Error("Invalid Hub bundle");
100
- const exact = (ref) => object(ref) && isPatchId(ref.identity) && isContentDigest(ref.digest);
101
- if (!exact(value.terminal))
102
- throw new Error("Invalid Hub terminal");
103
- const isRevision = (revision) => object(revision) &&
104
- exact(revision.ref) &&
105
- Array.isArray(revision.bases) &&
106
- revision.bases.every(exact) &&
107
- object(revision.delta) &&
108
- Array.isArray(revision.delta.operations) &&
109
- object(revision.metadata) &&
110
- object(revision.metadata.properties) &&
111
- Array.isArray(revision.metadata.citations);
112
- const revisions = value.revisions.map((revision) => {
113
- if (!isRevision(revision))
114
- throw new Error("Invalid Hub revision");
115
- return revision;
116
- });
117
- const bundle = { terminal: value.terminal, revisions };
118
- resolvePatchBundle(bundle);
119
- return bundleForRevision(bundle.terminal, new Map(revisions.map((revision) => [revision.ref.digest, revisionContent(revision)])));
130
+ const captureReading = { completeTerminal: true, includeCompleteBases: true };
131
+ function bundleStore(bundle) {
132
+ const store = new PackedPatches();
133
+ for (const [d, manifest] of bundle.manifests)
134
+ store.manifests.set(d, manifest);
135
+ for (const [d, chunk] of bundle.chunks)
136
+ store.chunks.set(d, chunk);
137
+ return store;
120
138
  }
121
139
  function theoryRequirement(value) {
122
140
  if (!object(value) ||
@@ -175,14 +193,17 @@ export function connectHub(profile, theories, confirm, createMission, options =
175
193
  });
176
194
  return hash;
177
195
  }
178
- /** Upload a closed bundle's attachments, capture it as a new Hub Patch and release it. */
196
+ /** Upload supplied content, capture it as a new Hub Patch and release it. */
179
197
  async function release(bundle, blobs, version, visibility) {
198
+ const { completeContents } = await verifySparseBundle(bundle, captureReading);
199
+ const uploads = new Map([...completeContents.values()].flatMap(contentAttachments).map((attachment) => [attachment.hash, attachment]));
180
200
  return connected(async (call) => {
181
- for (const attachment of attachments(bundle)) {
182
- const bytes = blobs.get(attachment.hash);
183
- if (!bytes)
184
- throw new Error("Missing Profile blob: " + attachment.hash);
185
- await upload(call, bytes, attachment.mediaType);
201
+ for (const [hash, attachment] of uploads) {
202
+ // A complete revision can still come from a sparse reading that omitted some blobs.
203
+ // Capture decides if the Hub can reuse those bytes or requires an upload.
204
+ const bytes = blobs.get(hash);
205
+ if (bytes)
206
+ await upload(call, bytes, attachment.mediaType);
186
207
  }
187
208
  const captured = await call("capture", { bundle });
188
209
  await call("name", { patchId: captured.ref.identity, digest: captured.ref.digest, version });
@@ -202,10 +223,10 @@ export function connectHub(profile, theories, confirm, createMission, options =
202
223
  if (!object(response) || response.patchId !== selected.patchId || response.version !== selected.version)
203
224
  throw new Error("Hub release address mismatch");
204
225
  const requirement = theoryRequirement(response.theoryRequirement);
205
- const bundle = verifiedBundle(response.bundle);
226
+ const { bundle, graph } = await verifySparseBundle(response.bundle);
206
227
  if (bundle.terminal.identity !== selected.patchId)
207
228
  throw new Error("Hub release identity mismatch");
208
- const revisions = new Map(bundle.revisions.map((revision) => [exactPatchRefKey(revision.ref), revision]));
229
+ const refs = new Set(graph.patchOrder.map(exactPatchRefKey));
209
230
  if (!Array.isArray(response.baseTheoryRequirements))
210
231
  throw new Error("Invalid Hub base Theory requirements");
211
232
  const baseRequirements = new Map();
@@ -216,49 +237,45 @@ export function connectHub(profile, theories, confirm, createMission, options =
216
237
  !isContentDigest(declaration.ref.digest))
217
238
  throw new Error("Invalid Hub base Theory requirement");
218
239
  const key = exactPatchRefKey({ identity: declaration.ref.identity, digest: declaration.ref.digest });
219
- if (!revisions.has(key) || baseRequirements.has(key) || key === exactPatchRefKey(bundle.terminal))
240
+ if (!refs.has(key) || baseRequirements.has(key) || key === exactPatchRefKey(bundle.terminal))
220
241
  throw new Error("Invalid Hub base Theory requirement");
221
242
  baseRequirements.set(key, theoryRequirement(declaration.requirement));
222
243
  }
223
- const blobs = new Map();
224
- for (const { hash } of attachments(bundle)) {
225
- const bytes = new Uint8Array(await (await fetched(endpoint + "/attachments/" + hash, { headers })).arrayBuffer());
226
- if (attachmentDigest(bytes) !== hash)
227
- throw new Error("Hub attachment digest mismatch: " + hash);
228
- blobs.set(hash, bytes);
229
- }
230
244
  const current = await profile.read();
231
245
  const theory = resolveTheory(current.manifest.theory, theories);
232
- let migrated;
233
- let adopted;
246
+ let reading = { bundle, graph };
234
247
  try {
235
- ({ terminal: adopted, revisions: migrated } = migrateTheoryPatchClosure(theory, bundle, requirement, baseRequirements));
248
+ const rewrites = [requirement, ...baseRequirements.values()].map((pin) => theoryPatchNeedsMigration(theory, pin));
249
+ if (rewrites.some(Boolean)) {
250
+ const { terminal, revisions } = migrateTheoryPatchClosure(theory, bundleStore(bundle).dense(bundle.terminal), requirement, baseRequirements);
251
+ if (!sameExactPatchRef(terminal.ref, bundle.terminal)) {
252
+ const store = new PackedPatches();
253
+ for (const revision of revisions)
254
+ store.add(revisionContent(revision));
255
+ reading = await verifySparseBundle(await extractSparseClosure(terminal.ref, store));
256
+ }
257
+ }
236
258
  }
237
259
  catch (error) {
238
260
  throw new Error("Cannot adopt Hub release; its publisher must republish for the installed Theory: " + String(error));
239
261
  }
240
- const contents = new Map(current.patches.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
241
- for (const revision of bundle.revisions)
242
- contents.set(revision.ref.digest, revisionContent(revision));
243
- for (const revision of migrated)
244
- contents.set(revision.ref.digest, revisionContent(revision));
245
- const personal = current.patches.revisions.find(({ ref }) => sameExactPatchRef(ref, current.manifest.personal));
246
- if (!personal)
247
- throw new Error("Missing personal Patch");
262
+ const blobs = await fetchReleaseBlobs(endpoint, headers, graph);
263
+ const adopted = reading.bundle.terminal;
264
+ const manifest = new Map(reading.bundle.manifests).get(adopted.digest);
265
+ if (!manifest)
266
+ throw new Error("Missing Hub terminal manifest");
267
+ const personal = current.personal;
248
268
  const content = {
249
- ...revisionContent(personal),
250
- bases: [...personal.bases.filter((ref) => ref.identity !== adopted.ref.identity), adopted.ref],
269
+ ...personal,
270
+ bases: [...personal.bases.filter((ref) => ref.identity !== adopted.identity), adopted],
251
271
  };
252
- const next = candidateRevision(personal.ref.identity, content);
253
- contents.set(next.ref.digest, content);
254
- resolvePatchBundle(bundleForRevision(next.ref, contents));
255
- const suggestions = readReifiedMissions(revisionContent(adopted), resolvePatchBundle(bundleForRevision(adopted.ref, contents)));
272
+ const suggestions = readReifiedMissions(manifest, reading.graph);
256
273
  const existing = new Set();
257
274
  for (const entry of current.log) {
258
275
  if (!isMissionRevision(entry))
259
276
  continue;
260
277
  const source = entry.mission.source;
261
- if (source?.patch.identity === adopted.ref.identity)
278
+ if (source?.patch.identity === adopted.identity)
262
279
  existing.add(source.suggestionId);
263
280
  }
264
281
  const selectedMissions = [];
@@ -276,7 +293,7 @@ export function connectHub(profile, theories, confirm, createMission, options =
276
293
  id: `mission-${randomUUID()}`,
277
294
  statement: item.statement,
278
295
  priority: 1,
279
- targets: item.targetNodes.map((node) => ({ node, provenance: adopted.ref })),
296
+ targets: item.targetNodes.map((node) => ({ node, provenance: adopted })),
280
297
  ...(item.guidance === undefined ? {} : { guidance: item.guidance }),
281
298
  ...(item.assessment === undefined ? {} : { assessment: item.assessment }),
282
299
  source: {
@@ -287,18 +304,16 @@ export function connectHub(profile, theories, confirm, createMission, options =
287
304
  },
288
305
  });
289
306
  }
290
- // Nothing touches the live head until every downloaded revision and blob verifies.
307
+ // Nothing touches the live head until every downloaded manifest, chunk and blob verifies.
291
308
  for (const bytes of blobs.values())
292
309
  await profile.addBlob(bytes);
293
- for (const revision of bundle.revisions)
294
- await profile.addRevision(revision.ref.identity, revisionContent(revision));
295
- for (const revision of migrated)
296
- if (!revisions.has(exactPatchRefKey(revision.ref)))
297
- await profile.addRevision(revision.ref.identity, revisionContent(revision));
298
- await profile.setPersonal(await profile.addRevision(personal.ref.identity, content));
310
+ await profile.addSparseClosure(bundle);
311
+ if (reading.bundle !== bundle)
312
+ await profile.addSparseClosure(reading.bundle);
313
+ await profile.setPersonal(await profile.addRevision(current.manifest.personal.identity, content));
299
314
  for (const mission of selectedMissions)
300
315
  await createMission(mission);
301
- return adopted.ref;
316
+ return adopted;
302
317
  },
303
318
  async signIn() {
304
319
  await (await HubAuth.open(resource, options)).signIn();
@@ -306,18 +321,21 @@ export function connectHub(profile, theories, confirm, createMission, options =
306
321
  async publish(input) {
307
322
  releasePrecedenceKey(input.version);
308
323
  const current = await profile.read();
309
- const contents = new Map(current.patches.revisions.map((revision) => [revision.ref.digest, revisionContent(revision)]));
310
- const original = bundleForRevision(input.patch, contents);
311
- const terminal = original.revisions.find(({ ref }) => sameExactPatchRef(ref, input.patch));
312
- if (!terminal)
324
+ if (!current.graph.patchOrder.some((ref) => sameExactPatchRef(ref, input.patch)))
313
325
  throw new Error("Patch is not in this Profile");
314
- if (original.revisions.some((revision) => revision !== terminal && PATCH_MISSIONS_PROPERTY in revision.metadata.properties))
315
- throw new Error("Cannot publish a Patch with private Mission pointers in a pinned base");
316
- const { metadata } = reifyProfileMissions(revisionContent(terminal), current.log, resolvePatchBundle(original), {
317
- missionIds: input.missions ?? [],
318
- });
326
+ const store = PackedPatches.fromFiles(await profile.files());
327
+ const terminal = store.content(input.patch);
328
+ const { graph } = await resolveSparsePatch(input.patch, store);
329
+ for (const base of graph.patchOrder) {
330
+ const manifest = store.manifests.get(base.digest);
331
+ if (!sameExactPatchRef(base, input.patch) &&
332
+ manifest &&
333
+ PATCH_MISSIONS_PROPERTY in manifest.metadata.properties)
334
+ throw new Error("Cannot publish a Patch with private Mission pointers in a pinned base");
335
+ }
336
+ const { metadata } = reifyProfileMissions(terminal, current.log, graph, { missionIds: input.missions ?? [] });
319
337
  const packaged = {
320
- ...revisionContent(terminal),
338
+ ...terminal,
321
339
  metadata: {
322
340
  ...metadata,
323
341
  properties: {
@@ -327,10 +345,8 @@ export function connectHub(profile, theories, confirm, createMission, options =
327
345
  },
328
346
  },
329
347
  };
330
- const ref = candidateRevision(input.patch.identity, packaged).ref;
331
- contents.set(ref.digest, packaged);
332
- const bundle = bundleForRevision(ref, contents);
333
- resolvePatchBundle(bundle);
348
+ const ref = { identity: input.patch.identity, digest: store.add(packaged) };
349
+ const bundle = await extractSparseClosure(ref, store, captureReading);
334
350
  if (!(await confirm({
335
351
  kind: "hub.publish",
336
352
  title: "Publish " + input.title + " " + input.version,
@@ -351,7 +367,7 @@ export function connectHub(profile, theories, confirm, createMission, options =
351
367
  throw new Error("Unknown Mission");
352
368
  const { entry, position } = revision;
353
369
  const { mission } = entry;
354
- const { bundle, skills } = missionBundle(current.patches, mission, title, {
370
+ const { bundle, skills } = await missionBundle(current.graph, mission, title, {
355
371
  missionId: mission.id,
356
372
  logEntryId: entry.id,
357
373
  logPosition: position,
@@ -400,7 +416,7 @@ export function connectHub(profile, theories, confirm, createMission, options =
400
416
  const download = await call("export_profile", {});
401
417
  return new Uint8Array(await (await fetched(download.url)).arrayBuffer());
402
418
  });
403
- const imported = validate(unpack(archive, theories), theories);
419
+ const imported = await validate(await unpack(archive, theories), theories);
404
420
  const backup = profile.dir + ".backup-" + randomUUID();
405
421
  if (!(await confirm({
406
422
  kind: "hub.import",
@@ -33,6 +33,7 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
33
33
  surface: import("@mmon-co/ncept-core").SurfaceId;
34
34
  about: readonly NodeId[];
35
35
  closed: boolean;
36
+ closedAt?: string;
36
37
  closing?: string;
37
38
  mission?: string;
38
39
  parent?: string;
@@ -79,6 +80,7 @@ export declare class LearningHost<S> {
79
80
  retireMission(id: string, outcome: "achieved" | "abandoned"): Promise<void>;
80
81
  begin(intent: SessionIntent): Promise<HostSession>;
81
82
  open(input: SessionOpening): Promise<HostSession>;
83
+ private requireRefinedSection;
82
84
  switchMode(session: LocalSession, to: ModeSwitch): Promise<void>;
83
85
  context(session: LocalSession, view?: LearningView<S>): Promise<{
84
86
  missions: {
package/dist/learning.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { isMission, isMissionRevision, isRunActiveChange, isRunPastEntry, isRunRetirement, lessonHere, nodeCascadedProperty, readMissionPath, readMissionRun, retire, selectGraph, setActive, tagIndex, } from "@mmon-co/ncept-core";
2
+ import { CHECKED_IN_PROPERTY, checkInRequired, pathProperty, sectionCoarseNodes, } from "@mmon-co/ncept-default-theory/path";
3
+ import { DEFAULT_THEORY_ID, homeDefaultRecords } from "@mmon-co/ncept-default-theory/state";
2
4
  import { join } from "node:path";
3
5
  import { lock } from "proper-lockfile";
4
6
  import { openProfile } from "./directory.js";
@@ -10,9 +12,59 @@ import { mechanics } from "./mechanics.js";
10
12
  import { ENTRY_KINDS, isSurface, modeEntry } from "./inputs.js";
11
13
  import { object, parsePiSession } from "./sessions.js";
12
14
  import { sessionLength } from "./session-policy.js";
13
- function readMissions(view, complete = false) {
15
+ function dueCheckIn(view, run, path, reading, closed, touches) {
16
+ if (run.retired || view.theory.id !== DEFAULT_THEORY_ID)
17
+ return;
18
+ const here = lessonHere(reading);
19
+ const section = here ? reading.sections.indexOf(here.section) : reading.sections.length;
20
+ const milestone = path.sections[section - 1]?.milestone;
21
+ const final = !here && milestone !== undefined ? true : undefined;
22
+ const required = checkInRequired(view.graph, path, milestone);
23
+ const stamp = milestone && pathProperty(view.graph, milestone, CHECKED_IN_PROPERTY);
24
+ let source;
25
+ if (milestone) {
26
+ for (const past of run.past) {
27
+ const session = past.kind === "session" ? closed.get(past.session) : undefined;
28
+ if (!session?.closedAt || (source && session.closedAt <= source.closedAt))
29
+ continue;
30
+ if (!final && typeof stamp === "string" && session.closedAt <= stamp)
31
+ continue;
32
+ if (touches(session.surface, milestone))
33
+ source = { sessionId: session.id, closedAt: session.closedAt };
34
+ }
35
+ }
36
+ if (!source && !required)
37
+ return;
38
+ const context = { ...(milestone === undefined ? {} : { milestone }), ...(final ? { final } : {}) };
39
+ return {
40
+ checkIn: { ...context, required },
41
+ entry: { kind: "checkpoint", missionId: run.mission, ...context, ...source, outcome: { kind: "cleared" } },
42
+ };
43
+ }
44
+ function readMissionStates(view, complete = false) {
14
45
  const projection = view.theory.project(view.graph, view.state);
15
- const sessions = runs(sessionStates(view.profile));
46
+ const states = sessionStates(view.profile);
47
+ const sessions = runs(states);
48
+ const closed = new Map(states.filter(({ closed }) => closed).map((session) => [session.id, session]));
49
+ let recordNodes;
50
+ const touches = (surface, node) => {
51
+ if (!recordNodes) {
52
+ recordNodes = new Map();
53
+ const { records, current } = homeDefaultRecords(view.graph, view.observations, view.now);
54
+ for (const record of records) {
55
+ if (!record.surface)
56
+ continue;
57
+ const homes = current.get(record.id);
58
+ if (!homes?.size)
59
+ continue;
60
+ const nodes = recordNodes.get(record.surface) ?? new Set();
61
+ for (const home of homes)
62
+ nodes.add(home);
63
+ recordNodes.set(record.surface, nodes);
64
+ }
65
+ }
66
+ return recordNodes.get(surface)?.has(node) ?? false;
67
+ };
16
68
  return missions(view.profile).map((mission) => {
17
69
  const run = missionRun(view.profile, mission.id);
18
70
  const context = { graph: view.graph, projection, observations: view.observations, activities: [] };
@@ -24,29 +76,27 @@ function readMissions(view, complete = false) {
24
76
  minutes: sessionLength(localSettings(view.profile)),
25
77
  ...(run.retired ? { retired: run.retired } : {}),
26
78
  });
27
- const itinerary = path ? readMissionPath(path, view.theory, context) : undefined;
79
+ const itinerary = path && readMissionPath(path, view.theory, context);
80
+ const due = path && itinerary && dueCheckIn(view, run, path, itinerary, closed, touches);
28
81
  const structured = itinerary?.sections.flatMap(({ lessons }) => lessons) ?? [];
29
- return {
82
+ const reading = {
30
83
  mission,
31
84
  run: readMissionRun(run, sessions, complete ? run.past.length : 20),
32
85
  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) => ({
86
+ ...(due ? { checkIn: due.checkIn } : {}),
87
+ next: (path?.future ?? []).map((lesson, index) => ({
41
88
  ...(structured.find((item) => item.kind === lesson.kind &&
42
89
  item.tag === lesson.tag &&
43
90
  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(", "),
91
+ name: lesson.name ?? lesson.nodes.map((node) => stringProperty(view.graph, node, "display:label", node)).join(", "),
46
92
  })),
47
93
  };
94
+ return { reading, entry: due?.entry };
48
95
  });
49
96
  }
97
+ function readMissions(view, complete = false) {
98
+ return readMissionStates(view, complete).map(({ reading }) => reading);
99
+ }
50
100
  /** Read current learning state without day processing, receipts or model calls. */
51
101
  export async function openLearningReader(profileDir, theories) {
52
102
  const profile = await openProfile(profileDir, theories, { readOnly: true });
@@ -122,14 +172,23 @@ function lessonAtEntry(session, graph, readings) {
122
172
  function sessionTitle(session, profile, label) {
123
173
  const entry = session.entry;
124
174
  const mode = session.mode.charAt(0).toUpperCase() + session.mode.slice(1);
125
- const name = entry?.kind === "mission"
126
- ? missions(profile).find((mission) => mission.id === entry.id)?.statement
127
- : entry?.kind === "target"
128
- ? label(entry.node)
129
- : entry?.kind === "goal"
130
- ? entry.text
131
- : undefined;
132
- return (name ? mode + " · " + name : mode).slice(0, 200);
175
+ let title = mode;
176
+ if (entry?.kind === "checkpoint") {
177
+ const name = missions(profile).find((mission) => mission.id === entry.missionId)?.statement;
178
+ title = "Check-in" + (name ? " · " + name : "");
179
+ }
180
+ else {
181
+ const name = entry?.kind === "mission"
182
+ ? missions(profile).find((mission) => mission.id === entry.id)?.statement
183
+ : entry?.kind === "target"
184
+ ? label(entry.node)
185
+ : entry?.kind === "goal"
186
+ ? entry.text
187
+ : undefined;
188
+ if (name)
189
+ title += " · " + name;
190
+ }
191
+ return title.slice(0, 200);
133
192
  }
134
193
  function identity() {
135
194
  return crypto.randomUUID();
@@ -270,7 +329,7 @@ export class LearningHost {
270
329
  for (const target of mission.targets) {
271
330
  if (!view.graph.nodes.some(({ id }) => id === target.node))
272
331
  throw new Error("Mission target is not in the graph");
273
- const source = await this.runtime.snapshot(target.provenance);
332
+ const source = await this.runtime.readPatch(target.provenance, view.profile);
274
333
  if (!source.graph.nodes.some(({ id }) => id === target.node))
275
334
  throw new Error("Invalid Mission target provenance");
276
335
  }
@@ -385,15 +444,15 @@ export class LearningHost {
385
444
  async begin(intent) {
386
445
  if (intent.kind === "new-mission")
387
446
  return this.open({ mode: "charting" });
388
- const reading = (await this.missionReadings()).find(({ mission }) => mission.id === intent.missionId);
389
- if (!reading || reading.run.retired?.outcome === "abandoned")
447
+ const state = readMissionStates(await this.runtime.snapshot()).find(({ reading }) => reading.mission.id === intent.missionId);
448
+ if (!state || state.reading.run.retired?.outcome === "abandoned")
390
449
  throw new Error("Mission is not available");
391
- const { mission, run, next, path } = reading;
450
+ const { mission, run, next, path } = state.reading;
392
451
  const entry = { kind: "mission", id: mission.id };
393
452
  if (intent.kind === "continue" && run.active)
394
453
  return this.open({ mode: "empty", resume: run.active });
395
- if (run.retired && intent.kind !== "continue")
396
- throw new Error("A finished Mission can only continue or resume a Session");
454
+ if (run.retired)
455
+ throw new Error("This Mission is finished");
397
456
  if (intent.kind === "skip-lesson" || intent.kind === "skip-to")
398
457
  return this.open({ mode: "lesson", skip: { ...intent, mission: mission.id } });
399
458
  if (intent.kind === "tell-tutor" && !intent.request.trim())
@@ -407,18 +466,17 @@ export class LearningHost {
407
466
  }
408
467
  if (intent.kind === "tell-tutor" || intent.kind === "revise-route" || !mission.targets.length)
409
468
  return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
410
- if (run.retired)
411
- throw new Error("This Mission is finished");
469
+ if (state.entry)
470
+ return this.open({ mode: "charting", entry: state.entry });
412
471
  const stop = next[0];
413
472
  if (!stop)
414
473
  throw new Error("This Mission has no following stop; revise the route or finish it");
415
- if (stop.checkpoint)
416
- return this.open({ mode: "charting", entry: { kind: "mission", id: mission.id } });
417
474
  return this.open({ mode: "lesson", entry });
418
475
  }
419
476
  async open(input) {
420
477
  const skipMission = input.skip?.mission;
421
478
  let skipped = [];
479
+ let skipSection;
422
480
  if (input.skip) {
423
481
  if (input.resume || input.entry)
424
482
  throw new Error("A skip cannot resume or supply an entry");
@@ -436,19 +494,15 @@ export class LearningHost {
436
494
  const skip = input.skip;
437
495
  const index = skip.kind === "skip-lesson"
438
496
  ? stops.findIndex((stop, position) => position > now && !stop.cleared)
439
- : stops.findIndex((stop) => stop.kind === skip.stop.kind &&
440
- stop.number === skip.stop.number &&
441
- stop.checkpoint?.milestone === skip.stop.checkpoint?.milestone);
497
+ : stops.findIndex((stop) => stop.kind === skip.stop.kind && stop.number === skip.stop.number);
442
498
  if (index < 0 || !stops[index])
443
499
  throw new Error("This Mission has no following stop; revise the route or finish it");
444
500
  if (now < 0 || index <= now || stops[index].cleared)
445
501
  throw new Error("Choose an uncleared stop after the current Lesson");
446
- skipped = stops.slice(now, index).filter((stop) => stop.numbered && !stop.cleared && !stop.checkpoint);
502
+ skipped = stops.slice(now, index).filter((stop) => stop.numbered && !stop.cleared);
447
503
  const stop = stops[index];
448
- input = {
449
- mode: stop.checkpoint ? "charting" : "lesson",
450
- entry: { kind: "mission", id: reading.mission.id },
451
- };
504
+ skipSection = path.sections.find(({ lessons }) => lessons.includes(stop));
505
+ input = { mode: "lesson", entry: { kind: "mission", id: reading.mission.id } };
452
506
  }
453
507
  const view = await this.runtime.snapshot();
454
508
  const known = sessionStates(view.profile);
@@ -494,6 +548,9 @@ export class LearningHost {
494
548
  const mission = missionId ? missions(view.profile).find(({ id }) => id === missionId) : undefined;
495
549
  if (missionId && !mission)
496
550
  throw new Error("Unknown Mission");
551
+ // Resuming an open Lesson stays possible, so Continue never strands an active run.
552
+ if (mode === "lesson" && mission && !resumed && (entry?.kind === "mission" || skipSection))
553
+ this.requireRefinedSection(view, mission.id, skipSection);
497
554
  const about = (mode === "lesson" && entry?.kind === "mission" ? undefined : resumed?.about) ??
498
555
  (entry?.kind === "target"
499
556
  ? [entry.node]
@@ -574,12 +631,22 @@ export class LearningHost {
574
631
  this.pendingSwitch = undefined;
575
632
  return session;
576
633
  }
634
+ requireRefinedSection(view, missionId, destination) {
635
+ if (view.theory.id !== DEFAULT_THEORY_ID)
636
+ return;
637
+ const path = readMissions(view).find(({ mission }) => mission.id === missionId)?.path;
638
+ const here = path && lessonHere(path)?.section;
639
+ if ([here, destination].some((section) => section && sectionCoarseNodes(view.graph, section).length > 0))
640
+ throw new Error("Complete the check-in before starting the next Lesson");
641
+ }
577
642
  async switchMode(session, to) {
578
643
  const view = await this.runtime.snapshot();
579
644
  const selected = this.mode(view.theory, session.mode, session.entry);
580
645
  if (!selected?.switches.some((allowed) => allowed.mode === to.mode && allowed.then === to.then))
581
646
  throw new Error("This mode does not allow that switch");
582
647
  this.mode(view.theory, to.mode, to.entry);
648
+ if (to.mode === "lesson" && to.entry?.kind === "mission")
649
+ this.requireRefinedSection(view, to.entry.id);
583
650
  if (to.then === "here") {
584
651
  const missionId = to.entry?.kind === "mission"
585
652
  ? to.entry.id
@@ -0,0 +1,21 @@
1
+ import { type ContentDigest, type ExactPatchRef, type PatchChunk, type PatchContent, type PatchManifest, type SparsePatchBundle } from "@mmon-co/ncept-core";
2
+ import type { ProfileFiles } from "./tar.js";
3
+ export declare class PackedPatches {
4
+ readonly manifests: Map<`sha256:${string}`, PatchManifest>;
5
+ readonly chunks: Map<`sha256:${string}`, PatchChunk>;
6
+ static fromFiles(files: ProfileFiles): PackedPatches;
7
+ getManifest: (d: ContentDigest) => Promise<PatchManifest | undefined>;
8
+ getChunk: (d: ContentDigest) => Promise<PatchChunk | undefined>;
9
+ add(content: PatchContent): `sha256:${string}`;
10
+ content(ref: ExactPatchRef): PatchContent;
11
+ reading(terminal: ExactPatchRef): Promise<{
12
+ patches: SparsePatchBundle;
13
+ graph: import("@mmon-co/ncept-core").ResolvedGraph;
14
+ personal: PatchContent;
15
+ }>;
16
+ dense(ref: ExactPatchRef): import("@mmon-co/ncept-core").ClosedPatchBundle;
17
+ }
18
+ export declare function packedFiles(parts: {
19
+ manifests: Iterable<SparsePatchBundle["manifests"][number]>;
20
+ chunks: Iterable<SparsePatchBundle["chunks"][number]>;
21
+ }): Map<string, Uint8Array<ArrayBufferLike>>;