@mmon-co/ncept-local 0.2.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 CHANGED
@@ -68,7 +68,7 @@ Pull verifies the closed bundle and all attachment digests before adopting its r
68
68
 
69
69
  `openHost({ ..., hub: { url, clientMetadataUrl, credentialsFile, openUrl } })` optionally overrides the Application base URL (default `https://co.mmon.co/ncept`), credential file (default `credentialsPath()`) and browser opening. For issuers using CIMD rather than dynamic registration, supply the front end's public native-client metadata document as `clientMetadataUrl` (the pi package uses pi's published identity). Front ends running remotely can present the authorization URL themselves through `openUrl`; the browser must be able to reach the host machine’s loopback callback. HTTP is allowed only for loopback development URLs.
70
70
 
71
- Confirmation proposals distinguish `hub.publish`, `hub.export`, `hub.import` and `hub.choose-mission`. When the web allowance is insufficient, the host asks which Missions to keep, up to the remaining allowance, and includes the upgrade address in each proposal’s detail. Declining the final replacement leaves the live Profile unchanged. Import from web validates the archive before confirmation and stages it before replacement, retains the entire previous project directory as `<profileDir>.backup-<uuid>`, and relocates transcripts to the final directory. Reopen any active Session after replacing the Profile; unrelated old project files and Material working copies remain in the backup, not in the replacement.
71
+ Confirmation proposals distinguish `hub.publish`, `hub.export` and `hub.import`. Declining the final replacement leaves the live Profile unchanged. Import from web validates the archive before confirmation and stages it before replacement, retains the entire previous project directory as `<profileDir>.backup-<uuid>`, and relocates transcripts to the final directory. Reopen any active Session after replacing the Profile; unrelated old project files and Material working copies remain in the backup, not in the replacement.
72
72
 
73
73
  ## First use from this repository
74
74
 
@@ -13,7 +13,8 @@ export interface ProfileDirectory {
13
13
  readonly dir: string;
14
14
  read(): Promise<ValidatedProfile>;
15
15
  files(): Promise<ProfileFiles>;
16
- appendLog(entries: readonly ProfileLogEntry[]): Promise<void>;
16
+ /** A conditional append checks the current Profile while holding its write lock. */
17
+ appendLog(entries: readonly ProfileLogEntry[], accept?: (current: ValidatedProfile) => boolean): Promise<void>;
17
18
  addRevision(identity: PatchId, content: PatchContent): Promise<ExactPatchRef>;
18
19
  setPersonal(ref: ExactPatchRef): Promise<void>;
19
20
  configure(options: InitOptions): Promise<void>;
package/dist/directory.js CHANGED
@@ -163,6 +163,12 @@ export async function openProfile(dir, theories, options = {}) {
163
163
  const files = await filesAt(dir);
164
164
  const manifest = { ...parseManifest(files.get("profile.json")), ...change };
165
165
  files.set("profile.json", jsonBytes(manifest));
166
+ // A surface re-registered to another file (bb's edit-message rewinds onto a fresh pi session)
167
+ // leaves its previous transcript on disk, outside the exchange.
168
+ const kept = new Set(Object.values(manifest.sessions).map((filename) => "sessions/" + filename));
169
+ for (const path of files.keys())
170
+ if (path.startsWith("sessions/") && !kept.has(path))
171
+ files.delete(path);
166
172
  for (const filename of Object.values(manifest.sessions)) {
167
173
  const path = "sessions/" + filename;
168
174
  if (!files.has(path))
@@ -188,8 +194,10 @@ export async function openProfile(dir, theories, options = {}) {
188
194
  dir,
189
195
  read,
190
196
  files: () => filesAt(dir),
191
- appendLog: (entries) => serial(async () => {
197
+ appendLog: (entries, accept) => serial(async () => {
192
198
  const current = await read();
199
+ if (accept && !accept(current))
200
+ return;
193
201
  const bytes = logBytes(mergeProfileLogs(current.log, entries));
194
202
  const manifest = { ...current.manifest, log: attachmentDigest(bytes) };
195
203
  await immutable(dir, liveLogPath(manifest), bytes);
@@ -89,7 +89,7 @@ export function hostTools(host, opened, capabilities, skills, metadataKeys) {
89
89
  schema: definition,
90
90
  run: (raw) => host.serial(async () => {
91
91
  const session = await host.current(opened);
92
- if (session.closed || session.mode !== opened.mode)
92
+ if (session.closed || session.closing || session.mode !== opened.mode)
93
93
  throw new Error("Tool belongs to an inactive Session mode");
94
94
  const result = await run(args(raw), session);
95
95
  if (!object(result.content) || result.content.status !== "refused") {
package/dist/host.d.ts CHANGED
@@ -12,6 +12,7 @@ export interface Proposal {
12
12
  readonly title: string;
13
13
  readonly description: string;
14
14
  readonly detail: unknown;
15
+ readonly defaultAccepted?: boolean;
15
16
  }
16
17
  export type Confirm = (proposal: Proposal) => Promise<boolean>;
17
18
  export type ModeSwitch = ModeSwitchDefault & Readonly<{
@@ -106,8 +107,12 @@ export interface Host {
106
107
  turn(session: HostSession, input: Readonly<{
107
108
  learnerMessage?: string;
108
109
  }>): Promise<HostChatSetup>;
109
- /** After the conversation stops, close a completed Lesson and return its next surface. */
110
+ /** After the conversation stops, end a completed Lesson and return its next surface. */
110
111
  settle(session: HostSession): Promise<ModeSwitch | undefined>;
112
+ /** End admission immediately, leaving Theory judgments pending. */
113
+ end(session: HostSession): Promise<void>;
114
+ /** Finish pending Theory closes without holding up other Session operations. */
115
+ closePending(): Promise<void>;
111
116
  close(session: HostSession): Promise<void>;
112
117
  };
113
118
  readonly missions: {
@@ -126,6 +131,15 @@ export interface Host {
126
131
  title: string;
127
132
  description?: string;
128
133
  }>): Promise<HubRelease>;
134
+ /**
135
+ * Publish one Mission's map (its targets and their prerequisites) as a new Hub release and
136
+ * return its link. Unlisted unless asked otherwise; signs in first when needed.
137
+ */
138
+ share(input: Readonly<{
139
+ mission: string;
140
+ title: string;
141
+ visibility?: "public" | "unlisted";
142
+ }>): Promise<HubRelease>;
129
143
  exportTo(destination: "web"): Promise<void>;
130
144
  importFrom(source: "web"): Promise<ImportResult>;
131
145
  };
@@ -153,5 +167,7 @@ export interface OpenHostOptions<S> {
153
167
  readonly theories: readonly Theory<S>[];
154
168
  readonly model: Model;
155
169
  readonly confirm: Confirm;
170
+ /** Receives failures from the background recovery sweep. */
171
+ readonly onCloseError?: (error: unknown) => void;
156
172
  }
157
173
  export { openHost } from "./learning.js";
package/dist/hub.d.ts CHANGED
@@ -1,4 +1,14 @@
1
+ import { type ClosedPatchBundle, type Mission } from "@mmon-co/ncept-core";
1
2
  import { type ProfileDirectory } from "./directory.js";
2
3
  import { type ConfiguredTheory } from "./exchange.js";
3
4
  import type { Confirm, Host, HubOptions } from "./host.js";
4
- export declare function connectHub(profile: ProfileDirectory, theories: readonly ConfiguredTheory[], confirm: Confirm, options?: HubOptions): Host["hub"];
5
+ /**
6
+ * One Mission's map as a standalone Patch: its targets and their prerequisites, flattened so
7
+ * the release carries that map alone whatever Patches it was learnt from, and offering the
8
+ * Mission to whoever opens it.
9
+ */
10
+ export declare function missionBundle(patches: ClosedPatchBundle, mission: Mission, title: string): {
11
+ bundle: ClosedPatchBundle;
12
+ skills: number;
13
+ };
14
+ export declare function connectHub(profile: ProfileDirectory, theories: readonly ConfiguredTheory[], confirm: Confirm, createMission: Host["missions"]["create"], options?: HubOptions): Host["hub"];
package/dist/hub.js CHANGED
@@ -2,13 +2,98 @@ 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, isPatchId, migrateTheoryPatchClosure, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
5
+ import { attachmentDigest, canonicalJson, contentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isMission, isMissionRevision, isPatchId, migrateTheoryPatchClosure, notebookSelection, reifyView, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, selectGraph, } 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 { HubAuth } from "./hub-auth.js";
9
9
  import { unpackDirectory } from "./directory.js";
10
10
  import { object, parsePiSession } from "./sessions.js";
11
11
  import { validate, unpack } from "./exchange.js";
12
+ /**
13
+ * One Mission's map as a standalone Patch: its targets and their prerequisites, flattened so
14
+ * the release carries that map alone whatever Patches it was learnt from, and offering the
15
+ * Mission to whoever opens it.
16
+ */
17
+ export function missionBundle(patches, mission, title) {
18
+ const graph = resolvePatchBundle(patches, new Set(["local"]), notebookSelection(patches));
19
+ const cone = selectGraph(graph, { cone: { targets: mission.targets.map(({ node }) => node) } });
20
+ if (!cone.nodes.length)
21
+ throw new Error("This Mission has no map yet");
22
+ // Flattened: the link carries the Mission's map alone, whatever Patches it was learnt from.
23
+ const reified = reifyView(cone, {
24
+ metadata: { properties: { "patch:title": title, "patch:description": mission.statement }, citations: [] },
25
+ });
26
+ const provenance = reified.metadata.citations.find((citation) => citation.kind === "reified_from");
27
+ const mapped = new Map(provenance?.kind === "reified_from" ? provenance.entities.nodes.map(({ source, target }) => [source, target]) : []);
28
+ const node = (id) => mapped.get(id) ?? id;
29
+ const entries = (list) => list?.map((entry) => ({
30
+ ...entry,
31
+ ...(entry.nodes ? { nodes: entry.nodes.map(node) } : {}),
32
+ ...(entry.mode === "append"
33
+ ? {}
34
+ : "replace" in entry.mode
35
+ ? { mode: { replace: entry.mode.replace.map((ref) => ("name" in ref ? ref : { node: node(ref.node) })) } }
36
+ : { mode: { keep: entry.mode.keep.map((ref) => ("name" in ref ? ref : { node: node(ref.node) })) } }),
37
+ }));
38
+ const guidance = entries(mission.guidance);
39
+ const assessment = entries(mission.assessment);
40
+ // The Hub offers this to whoever opens the link as a Mission they can start.
41
+ const suggestion = {
42
+ id: randomUUID(),
43
+ preselected: true,
44
+ statement: mission.statement,
45
+ shortName: title,
46
+ targetNodes: mission.targets.map((target) => node(target.node)),
47
+ ...(guidance?.length ? { guidance } : {}),
48
+ ...(assessment?.length ? { assessment } : {}),
49
+ };
50
+ const content = {
51
+ ...reified,
52
+ metadata: {
53
+ // The Hub records provenance itself and refuses it from a client.
54
+ citations: reified.metadata.citations.filter((citation) => citation.kind !== "reified_from"),
55
+ properties: { ...reified.metadata.properties, [MISSION_SUGGESTIONS]: canonicalJson([suggestion]) },
56
+ },
57
+ };
58
+ const revision = candidateRevision(`patch-${randomUUID()}`, content);
59
+ const bundle = bundleForRevision(revision.ref, new Map([[revision.ref.digest, content]]));
60
+ resolvePatchBundle(bundle);
61
+ return { bundle, skills: cone.nodes.length };
62
+ }
63
+ /** The Application's metadata property for Missions a release offers its readers. */
64
+ const MISSION_SUGGESTIONS = "application:mission-suggestions";
65
+ function suggestedMissions(revision, contents) {
66
+ const encoded = revision.metadata.properties[MISSION_SUGGESTIONS];
67
+ if (encoded === undefined)
68
+ return [];
69
+ if (typeof encoded !== "string")
70
+ throw new Error("Invalid Mission suggestions metadata");
71
+ const suggestions = JSON.parse(encoded);
72
+ if (!Array.isArray(suggestions))
73
+ throw new Error("Invalid Mission suggestions metadata");
74
+ const nodes = new Set(resolvePatchBundle(bundleForRevision(revision.ref, contents)).nodes.map(({ id }) => id));
75
+ const ids = new Set();
76
+ return suggestions.map((item) => {
77
+ if (!object(item) || typeof item.id !== "string" || !item.id || !Array.isArray(item.targetNodes))
78
+ throw new Error("Invalid Mission suggestion");
79
+ const { statement, targetNodes, guidance, assessment, preselected } = item;
80
+ const mission = {
81
+ id: "hub-" + contentDigest([revision.ref.identity, item.id]),
82
+ statement,
83
+ priority: 1,
84
+ targets: targetNodes.map((node) => ({ node, provenance: revision.ref })),
85
+ ...(guidance === undefined ? {} : { guidance }),
86
+ ...(assessment === undefined ? {} : { assessment }),
87
+ };
88
+ if (!isMission(mission) ||
89
+ ids.has(mission.id) ||
90
+ new Set(targetNodes).size !== targetNodes.length ||
91
+ mission.targets.some(({ node }) => !nodes.has(node)))
92
+ throw new Error("Invalid Mission suggestion");
93
+ ids.add(mission.id);
94
+ return { mission, preselected: preselected === true };
95
+ });
96
+ }
12
97
  function baseUrl(value) {
13
98
  const url = new URL(value);
14
99
  if ((url.protocol !== "https:" &&
@@ -94,7 +179,7 @@ function theoryRequirement(value) {
94
179
  throw new Error("Invalid Hub release Theory requirement");
95
180
  return { theory: value.theory, range: value.range };
96
181
  }
97
- export function connectHub(profile, theories, confirm, options = {}) {
182
+ export function connectHub(profile, theories, confirm, createMission, options = {}) {
98
183
  const base = baseUrl(options.url ?? "https://co.mmon.co/ncept");
99
184
  const resource = base + "/mcp";
100
185
  const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + metadata.version };
@@ -102,7 +187,7 @@ export function connectHub(profile, theories, confirm, options = {}) {
102
187
  const provider = await HubAuth.open(resource, options);
103
188
  if (!provider.tokens())
104
189
  throw new Error("Sign in first with host.hub.signIn()");
105
- const client = new Client({ name: "@mmon-co/ncept-local", version: "0.1.0" });
190
+ const client = new Client({ name: metadata.name, version: metadata.version });
106
191
  try {
107
192
  await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider }));
108
193
  return await operation(async (name, args) => {
@@ -135,6 +220,25 @@ export function connectHub(profile, theories, confirm, options = {}) {
135
220
  });
136
221
  return hash;
137
222
  }
223
+ /** Upload a closed bundle's attachments, capture it as a new Hub Patch and release it. */
224
+ async function release(bundle, blobs, version, visibility) {
225
+ return connected(async (call) => {
226
+ for (const attachment of attachments(bundle)) {
227
+ const bytes = blobs.get(attachment.hash);
228
+ if (!bytes)
229
+ throw new Error("Missing Profile blob: " + attachment.hash);
230
+ await upload(call, bytes, attachment.mediaType);
231
+ }
232
+ const captured = await call("capture", { bundle });
233
+ await call("name", { patchId: captured.ref.identity, digest: captured.ref.digest, version });
234
+ await call("publish", { patchId: captured.ref.identity, version, visibility });
235
+ return {
236
+ ref: captured.ref,
237
+ version,
238
+ url: base + "/hub/" + captured.ref.identity + "/releases/" + encodeURIComponent(version),
239
+ };
240
+ });
241
+ }
138
242
  return {
139
243
  async pull(address) {
140
244
  const selected = releaseAddress(address, base);
@@ -193,6 +297,21 @@ export function connectHub(profile, theories, confirm, options = {}) {
193
297
  const next = candidateRevision(personal.ref.identity, content);
194
298
  contents.set(next.ref.digest, content);
195
299
  resolvePatchBundle(bundleForRevision(next.ref, contents));
300
+ const suggestions = suggestedMissions(adopted, contents);
301
+ const existing = new Set(current.log.filter(isMissionRevision).map(({ mission }) => mission.id));
302
+ const selectedMissions = [];
303
+ for (const { mission, preselected } of suggestions) {
304
+ if (existing.has(mission.id))
305
+ continue;
306
+ if (await confirm({
307
+ kind: "hub.pull.mission",
308
+ title: "Add the suggested Mission?",
309
+ description: mission.statement,
310
+ detail: { statement: mission.statement },
311
+ defaultAccepted: preselected,
312
+ }))
313
+ selectedMissions.push(mission);
314
+ }
196
315
  // Nothing touches the live head until every downloaded revision and blob verifies.
197
316
  for (const bytes of blobs.values())
198
317
  await profile.addBlob(bytes);
@@ -202,6 +321,8 @@ export function connectHub(profile, theories, confirm, options = {}) {
202
321
  if (!revisions.has(exactPatchRefKey(revision.ref)))
203
322
  await profile.addRevision(revision.ref.identity, revisionContent(revision));
204
323
  await profile.setPersonal(await profile.addRevision(personal.ref.identity, content));
324
+ for (const mission of selectedMissions)
325
+ await createMission(mission);
205
326
  return adopted.ref;
206
327
  },
207
328
  async signIn() {
@@ -237,54 +358,51 @@ export function connectHub(profile, theories, confirm, options = {}) {
237
358
  detail: { ...input, bundle },
238
359
  })))
239
360
  throw new Error("Publication declined");
240
- return connected(async (call) => {
241
- for (const attachment of attachments(bundle)) {
242
- const bytes = current.blobs.get(attachment.hash);
243
- if (!bytes)
244
- throw new Error("Missing Profile blob: " + attachment.hash);
245
- await upload(call, bytes, attachment.mediaType);
246
- }
247
- const captured = await call("capture", { bundle });
248
- await call("name", { patchId: captured.ref.identity, digest: captured.ref.digest, version: input.version });
249
- await call("publish", { patchId: captured.ref.identity, version: input.version });
250
- return {
251
- ref: captured.ref,
252
- version: input.version,
253
- url: base + "/hub/" + captured.ref.identity + "/releases/" + encodeURIComponent(input.version),
254
- };
255
- });
361
+ return release(bundle, current.blobs, input.version, "public");
362
+ },
363
+ async share(input) {
364
+ const title = input.title.trim();
365
+ if (!title)
366
+ throw new Error("A shared Mission needs a title");
367
+ const visibility = input.visibility ?? "unlisted";
368
+ const current = await profile.read();
369
+ const mission = current.log
370
+ .filter(isMissionRevision)
371
+ .findLast((entry) => entry.mission.id === input.mission)?.mission;
372
+ if (!mission)
373
+ throw new Error("Unknown Mission");
374
+ const { bundle, skills } = missionBundle(current.patches, mission, title);
375
+ if (!(await confirm({
376
+ kind: "hub.share",
377
+ title: "Share " + title,
378
+ description: visibility === "public"
379
+ ? "List this Mission's map (" + skills + " skills) and its Materials publicly on the Hub."
380
+ : "Publish this Mission's map (" +
381
+ skills +
382
+ " skills) and its Materials at a link. Anyone with the link can read and learn from it; it isn't listed on the Hub.",
383
+ detail: { mission: mission.id, statement: mission.statement, title, visibility, skills: skills },
384
+ })))
385
+ throw new Error("Share declined");
386
+ const provider = await HubAuth.open(resource, options);
387
+ if (!provider.tokens())
388
+ await provider.signIn();
389
+ return release(bundle, current.blobs, "0.1.0", visibility);
256
390
  },
257
391
  async exportTo() {
258
392
  const archive = await profile.pack();
259
393
  await connected(async (call) => {
260
394
  const hash = await upload(call, archive, "application/x-tar");
261
395
  const preview = await call("import_profile", { hash });
262
- let missions;
263
- if (preview.status === "choose-missions") {
264
- missions = [];
265
- for (const mission of preview.missions) {
266
- if (preview.available !== null && missions.length >= preview.available)
267
- break;
268
- if (await confirm({
269
- kind: "hub.choose-mission",
270
- title: "Keep Mission: " + mission.statement,
271
- description: "Choose Missions to move to the web within your allowance, or upgrade on the web first.",
272
- detail: { mission, available: preview.available, upgrade: preview.upgrade },
273
- }))
274
- missions.push(mission.id);
275
- }
276
- }
277
396
  if (!(await confirm({
278
397
  kind: "hub.export",
279
398
  title: "Replace web Main with this local Profile",
280
- description: "The old web Main is retained as history. Unchosen Missions remain here locally.",
281
- detail: { ...preview, chosenMissions: missions },
399
+ description: "The old web Main is retained as history.",
400
+ detail: preview,
282
401
  })))
283
402
  return;
284
403
  const result = await call("import_profile", {
285
404
  hash,
286
405
  expectedMainProfileId: preview.mainProfileId,
287
- ...(missions === undefined ? {} : { missions }),
288
406
  });
289
407
  if (result.status !== "imported")
290
408
  throw new Error("Web import needs a new preview: " + JSON.stringify(result));
@@ -9,6 +9,11 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
9
9
  id: `node-${string}`;
10
10
  label: string;
11
11
  status: "open" | "done" | "tentative";
12
+ frontier: boolean;
13
+ }[];
14
+ edges: {
15
+ from: `node-${string}`;
16
+ to: `node-${string}`;
12
17
  }[];
13
18
  dueReview: {
14
19
  id: `node-${string}`;
@@ -24,6 +29,7 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
24
29
  surface: import("@mmon-co/ncept-core").SurfaceId;
25
30
  about: readonly NodeId[];
26
31
  closed: boolean;
32
+ closing?: string;
27
33
  mission?: string;
28
34
  parent?: string;
29
35
  id: import("@mmon-co/ncept-core").SessionRef;
@@ -36,13 +42,15 @@ export declare function openLearningReader<S>(profileDir: string, theories: read
36
42
  export declare class LearningHost<S> {
37
43
  readonly runtime: Runtime<S>;
38
44
  readonly confirm: OpenHostOptions<S>["confirm"];
45
+ readonly onCloseError: (error: unknown) => void;
39
46
  private tail;
40
47
  private pendingSwitch?;
48
+ private readonly closeJobs;
41
49
  readonly drafts: Map<string, {
42
50
  base: string;
43
51
  content: PatchContent;
44
52
  }>;
45
- constructor(runtime: Runtime<S>, confirm: OpenHostOptions<S>["confirm"]);
53
+ constructor(runtime: Runtime<S>, confirm: OpenHostOptions<S>["confirm"], onCloseError?: (error: unknown) => void);
46
54
  serial<T>(operation: () => Promise<T>): Promise<T>;
47
55
  reload(): Promise<void>;
48
56
  current(session: HostSession): Promise<LocalSession>;
@@ -55,8 +63,10 @@ export declare class LearningHost<S> {
55
63
  }>;
56
64
  reviseMission(mission: Mission, create: boolean): Promise<void>;
57
65
  private closing;
58
- private closingRun;
59
- close(session: HostSession): Promise<void>;
66
+ private markClosing;
67
+ private endingRun;
68
+ end(session: HostSession): Promise<void>;
69
+ closePending(): Promise<void>;
60
70
  settle(session: HostSession): Promise<ModeSwitch | undefined>;
61
71
  retireMission(id: string, outcome: "achieved" | "abandoned"): Promise<void>;
62
72
  begin(intent: SessionIntent): Promise<HostSession>;
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";
@@ -58,11 +60,19 @@ export async function openLearningReader(profileDir, theories) {
58
60
  const view = await runtime.snapshot();
59
61
  const projection = view.theory.project(view.graph, view.state);
60
62
  const progress = view.theory.progress(view.graph, projection, view.graph.nodes.map(({ id }) => id));
61
- const dueReview = [...tagIndex(projection)("review:due")];
63
+ const tagged = tagIndex(projection);
64
+ const dueReview = [...tagged("review:due")];
65
+ const frontier = tagged("frontier");
62
66
  const label = (id) => stringProperty(view.graph, id, "display:label", id);
63
67
  return {
64
68
  missions: readMissions(view, true),
65
- nodes: view.graph.nodes.map(({ id }) => ({ id, label: label(id), status: progress[id]?.status ?? "open" })),
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 })),
66
76
  dueReview: dueReview.map((id) => ({ id, label: label(id) })),
67
77
  sessions: sessionStates(view.profile).map((session) => ({
68
78
  ...session,
@@ -131,7 +141,7 @@ function missions(profile) {
131
141
  function runs(sessions) {
132
142
  return sessions.map((session) => ({
133
143
  ref: session.id,
134
- open: !session.closed,
144
+ open: !session.closed && !session.closing,
135
145
  ...(session.parent === undefined ? {} : { parent: session.parent }),
136
146
  }));
137
147
  }
@@ -173,12 +183,15 @@ function runEntries(before, after, at) {
173
183
  export class LearningHost {
174
184
  runtime;
175
185
  confirm;
186
+ onCloseError;
176
187
  tail = Promise.resolve();
177
188
  pendingSwitch;
189
+ closeJobs = new Map();
178
190
  drafts = new Map();
179
- constructor(runtime, confirm) {
191
+ constructor(runtime, confirm, onCloseError = (error) => console.error("Session close failed:", error)) {
180
192
  this.runtime = runtime;
181
193
  this.confirm = confirm;
194
+ this.onCloseError = onCloseError;
182
195
  }
183
196
  serial(operation) {
184
197
  const result = this.tail.then(operation);
@@ -292,10 +305,15 @@ export class LearningHost {
292
305
  }, session);
293
306
  return [
294
307
  ...event.entries,
295
- platform({ kind: "local.session", session: { ...session, closed: true } }, session.surface),
308
+ platform({ kind: "local.session", session: { ...session, closing: undefined, closed: true } }, session.surface),
296
309
  ];
297
310
  }
298
- async closingRun(current, profile) {
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) {
299
317
  const known = sessionStates(profile);
300
318
  const closing = new Set([current.id]);
301
319
  for (const id of closing)
@@ -315,20 +333,63 @@ export class LearningHost {
315
333
  }
316
334
  for (const session of known)
317
335
  if (closing.has(session.id))
318
- entries.push(...(await this.closing(session)));
336
+ entries.push(...this.markClosing(session));
319
337
  return entries;
320
338
  }
321
- async close(session) {
339
+ async end(session) {
322
340
  const current = await this.current(session);
323
- await this.runtime.profile.appendLog(await this.closingRun(current, await this.runtime.profile.read()));
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");
324
385
  }
325
386
  async settle(session) {
326
387
  const current = await this.current(session);
327
- if (current.closed || current.mode !== "lesson" || current.entry?.kind !== "lesson")
388
+ if (current.closed || current.closing || current.mode !== "lesson" || current.entry?.kind !== "lesson")
328
389
  return;
329
390
  if (!(await this.context(current)).lesson?.complete)
330
391
  return;
331
- await this.close(current);
392
+ await this.end(current);
332
393
  return {
333
394
  mode: "charting",
334
395
  then: "next",
@@ -555,11 +616,11 @@ export class LearningHost {
555
616
  for (const ref of result.close) {
556
617
  const outgoing = known.find(({ id }) => id === ref);
557
618
  if (outgoing)
558
- entries.push(...(await this.closing(outgoing)));
619
+ entries.push(...this.markClosing(outgoing));
559
620
  }
560
621
  }
561
622
  if (pending?.to.then === "next" && (!missionId || pending.from.mission !== missionId))
562
- entries.push(...(await this.closingRun(pending.from, view.profile)));
623
+ entries.push(...this.endingRun(pending.from, view.profile));
563
624
  const event = await this.runtime.event({ kind: "surface.open", surface: session.surface, format: "local", about }, session);
564
625
  entries.push(...event.entries, platform({ kind: "local.session", session }, session.surface));
565
626
  if (skipped.length) {
@@ -640,7 +701,7 @@ export class LearningHost {
640
701
  for (const id of result.close) {
641
702
  const outgoing = sessionStates(view.profile).find((item) => item.id === id);
642
703
  if (outgoing)
643
- entries.push(...(await this.closing(outgoing)));
704
+ entries.push(...this.markClosing(outgoing));
644
705
  }
645
706
  }
646
707
  entries.push(platform({ kind: "local.session", session: updated }, session.surface));
@@ -700,8 +761,8 @@ export class LearningHost {
700
761
  }
701
762
  async turn(input, learnerMessage) {
702
763
  const session = await this.current(input);
703
- if (session.closed)
704
- throw new Error("Session is closed; resume it first");
764
+ if (session.closed || session.closing)
765
+ throw new Error("Session is ended; resume it first");
705
766
  let view = await this.runtime.snapshot();
706
767
  let ctx = await this.context(session);
707
768
  if (learnerMessage !== undefined && view.theory.chat?.reply) {
@@ -732,7 +793,7 @@ export class LearningHost {
732
793
  schema: tool.schema,
733
794
  run: (args) => this.serial(async () => {
734
795
  const current = await this.current(session);
735
- if (current.closed || current.mode !== session.mode)
796
+ if (current.closed || current.closing || current.mode !== session.mode)
736
797
  throw new Error("Tool belongs to an inactive Session mode");
737
798
  const result = await this.runtime.prepare(tool.run(args, await this.context(current)), current);
738
799
  const feature = await this.runtime.event({ kind: "feature.used", operation: tool.name, at: new Date().toISOString(), about: current.about }, current);
@@ -793,15 +854,19 @@ export class LearningHost {
793
854
  }
794
855
  if (typeof localSettings(view.profile).timezone !== "string")
795
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);
796
861
  }
797
862
  }
798
863
  export async function openHost(options) {
799
864
  const profile = await openProfile(options.profileDir, options.theories);
800
865
  const config = localSettings(await profile.read());
801
866
  const timezone = checkedTimezone(typeof config.timezone === "string" ? config.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone);
802
- 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)));
803
868
  await learning.start();
804
- 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);
805
870
  return {
806
871
  profile,
807
872
  sessions: {
@@ -809,7 +874,12 @@ export async function openHost(options) {
809
874
  begin: (intent) => learning.serial(() => learning.begin(intent)),
810
875
  turn: (session, input) => learning.serial(() => learning.turn(session, input.learnerMessage)),
811
876
  settle: (session) => learning.serial(() => learning.settle(session)),
812
- close: (session) => learning.serial(() => learning.close(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
+ },
813
883
  },
814
884
  missions: {
815
885
  list: () => learning.missionReadings(),
@@ -823,6 +893,7 @@ export async function openHost(options) {
823
893
  pull: (address) => learning.serial(() => hub.pull(address)),
824
894
  signIn: () => learning.serial(() => hub.signIn()),
825
895
  publish: (input) => learning.serial(() => hub.publish(input)),
896
+ share: (input) => learning.serial(() => hub.share(input)),
826
897
  exportTo: (destination) => learning.serial(() => hub.exportTo(destination)),
827
898
  importFrom: (source) => learning.serial(async () => {
828
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
@@ -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 } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmon-co/ncept-local",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,12 +36,12 @@
36
36
  "prepack": "bun run build"
37
37
  },
38
38
  "dependencies": {
39
- "@mmon-co/ncept-core": "^0.2.0",
39
+ "@mmon-co/ncept-core": "^0.3.0",
40
40
  "@modelcontextprotocol/sdk": "1.32.1",
41
41
  "proper-lockfile": "4.1.2"
42
42
  },
43
43
  "devDependencies": {
44
- "@mmon-co/ncept-default-theory": "^1.1.0",
44
+ "@mmon-co/ncept-default-theory": "^2.0.0",
45
45
  "@types/proper-lockfile": "^4.1.4",
46
46
  "bun-types": "^1.3.14",
47
47
  "typescript": "5.9.3"