@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 CHANGED
@@ -15,7 +15,7 @@ const tar = await profile.pack();
15
15
  await unpackDirectory(tar, "/path/to/moved-profile", [defaultTheory]);
16
16
  ```
17
17
 
18
- `init` creates an empty personal Patch, empty log and reserved directories in an ordinary project directory. `profile.json` contains `format: 1`, `personal`, `theory` (Core's requirement), `theories` (package names, initially `@mmon-co/ncept-default-theory`) and `sessions` (surface → pi filename). Account credentials live at `credentialsPath()`, outside the Profile, in `~/.config/mmon/credentials.json`.
18
+ `init` creates an empty personal Patch, empty log and reserved directories in an ordinary project directory. `profile.json` contains `format: 1`, `personal`, `theory` (Core's requirement), `theories` (package names, initially `@mmon-co/ncept-default-theory`) and `sessions` (surface → pi filename). Account credentials live at `credentialsPath()`, outside the Profile, in `~/.config/ncept/credentials.json`.
19
19
 
20
20
  `openProfile` and `unpack` migrate a stored minor pin (or an exact web-export release) with the supplied executable Theory’s `migrations` before strict resolution. Broad requirements still use strict resolution without migration. Migration writes new immutable Patch revisions and a content-addressed log snapshot, then atomically switches `profile.json`’s personal head, Theory requirement and optional `log` digest together. Interrupted writes leave the old generation active; reopening retries pure steps from that generation. Old revision/log files remain unread history. Host futures are rebuilt from the migrated Profile; captured Session transcripts are not rewritten as futures.
21
21
 
@@ -38,16 +38,18 @@ const session = await host.sessions.open({ mode: "charting", entry: { kind: "goa
38
38
  const setup = await host.sessions.turn(session, {});
39
39
  const claim = setup.tools.find((tool) => tool.name === "record_claim")!;
40
40
  await claim.run({ statement: "I can add one and one", stance: "knows" });
41
- await host.sessions.close(session);
41
+ const next = await host.sessions.settle(session);
42
42
  ```
43
43
 
44
+ After the whole conversation turn stops and its transcript is saved, call `.settle(session)`. It closes a completed Lesson through the same lifecycle as `.close` and returns a Charting switch for its Mission; an unfinished Lesson stays open. Keep the Session open across all tool batches and the tutor's final reply.
45
+
44
46
  After a switch result, call `.open(result.switch)` for `next`/`aside`; for `here`, keep the same Session handle and request a fresh turn. `.close(session)` records its closing transcript through the Theory. Resume a closed Session with `.open({ mode, resume: session.id })`. Session identities, mode, scope, acceptance provenance and learner-day receipts are platform observations in `log.jsonl`, so they travel with the Profile.
45
47
 
46
48
  The front end writes pi transcripts and registers their filenames against `session.surface` after trust. `turn(session, { learnerMessage })` takes the selected learner **message entry id**, not message text; it runs a declared reply grader before setup. Reads follow the selected pi branch, and locally recorded evidence derives its standing from its acceptance branch. A library caller without a transcript still retains tool-recorded evidence, but has no closing conversation to record.
47
49
 
48
50
  Graph drafts stay unsaved until a confirmed `propose`. Mission and guidance/graph proposals and preference changes use `confirm`; a refusal changes no Profile files. Materials use the `local` playground, immutable blob bytes and working copies under `materials/<node>/<material>/<filename>`. Opening preserves an existing working copy. Read-back returns both the saved body and current working-copy text. Other playgrounds' Materials remain readable as saved data without claiming a runner.
49
51
 
50
- `host.config.update({ ...await host.config.read(), timezone: "America/New_York" })` configures learner-days. The initial zone is the machine's IANA zone; each learner-day ends at 04:00 local, including across DST. At startup, the host raises `day.ended` once per elapsed day and records its receipt alongside the Theory's writes. No account or background daemon is needed.
52
+ `host.config.update({ ...await host.config.read(), timezone: "America/New_York" })` configures learner-days. The initial zone is the machine's IANA zone; each learner-day ends at 04:00 local, including across DST. At startup, the host raises `day.ended` once per elapsed day and records its receipt alongside the Theory's writes. No account or background daemon is needed. Set `sessionLength` through the same config API to choose the Session budget in minutes (default 20). Review opens the Theory’s budgeted maintenance stop, preserving its Node order; the due count still describes all due Nodes.
51
53
 
52
54
  ## Hub and web exchange
53
55
 
@@ -66,7 +68,7 @@ Pull verifies the closed bundle and all attachment digests before adopting its r
66
68
 
67
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.
68
70
 
69
- 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.
70
72
 
71
73
  ## First use from this repository
72
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>;
@@ -27,6 +28,8 @@ export interface ProfileDirectory {
27
28
  }): Promise<string>;
28
29
  pack(): Promise<Uint8Array>;
29
30
  }
30
- export declare function openProfile(dir: string, theories: readonly ConfiguredTheory[]): Promise<ProfileDirectory>;
31
+ export declare function openProfile(dir: string, theories: readonly ConfiguredTheory[], options?: {
32
+ readOnly?: boolean;
33
+ }): Promise<ProfileDirectory>;
31
34
  /** Unpack into a new Profile, leaving unrelated project files alone and never following links. */
32
35
  export declare function unpackDirectory(archive: Uint8Array, dir: string, theories: readonly ConfiguredTheory[]): Promise<ProfileDirectory>;
package/dist/directory.js CHANGED
@@ -2,6 +2,7 @@ import { link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "no
2
2
  import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { lock, lockSync } from "proper-lockfile";
5
6
  import { attachmentDigest, candidateRevision, emptyPatch, isPatchId, mergeProfileLogs, PERSONAL_PATCH_ID, } from "@mmon-co/ncept-core";
6
7
  import { DEFAULT_THEORY_PACKAGES, DEFAULT_THEORY_REQUIREMENT, jsonBytes, logBytes, liveLogPath, migrateProfileFiles, pack, parseManifest, sessionFilename, unpack, utf8, validate, } from "./exchange.js";
7
8
  import { parsePiSession, piSessionFilename, relocatePiSession, serializePiSession, } from "./sessions.js";
@@ -99,34 +100,59 @@ export async function init(dir, options = {}) {
99
100
  await immutable(dir, "patches/" + patch.ref.digest + ".json", jsonBytes(emptyPatch()));
100
101
  await writeFile(join(dir, "log.jsonl"), new Uint8Array(), { flag: "wx" });
101
102
  }
102
- export async function openProfile(dir, theories) {
103
- dir = resolve(dir);
104
- const stored = await filesAt(dir);
105
- const initial = migrateProfileFiles(stored, theories);
106
- // Immutable data first, then a single atomic live-head/log/pin switch. An interruption
107
- // leaves either the old generation or the complete new one; retry never repeats a step.
108
- for (const [path, bytes] of initial) {
109
- if (path !== "profile.json" && !stored.has(path))
110
- await immutable(dir, path, bytes);
111
- }
112
- const manifest = initial.get("profile.json");
113
- if (manifest !== stored.get("profile.json") && manifest)
114
- await atomic(dir, "profile.json", manifest);
115
- const profile = validate(initial, theories);
116
- // A copied or moved Profile must still appear in pi's cwd-filtered /resume list.
117
- for (const filename of Object.values(profile.manifest.sessions)) {
118
- const path = "sessions/" + filename;
119
- const bytes = initial.get(path);
120
- if (bytes) {
121
- const source = new TextDecoder().decode(bytes);
122
- if (parsePiSession(source).header.cwd !== dir)
123
- await atomic(dir, path, utf8.encode(relocatePiSession(source, dir)));
124
- }
103
+ async function locked(dir, operation) {
104
+ let release;
105
+ try {
106
+ // The uncontended path avoids callback round trips for each filesystem step.
107
+ release = lockSync(dir);
125
108
  }
126
- // Serialize this handle's mutations, including read/merge/write of the immutable-identity log.
109
+ catch (error) {
110
+ if (!(error instanceof Error && "code" in error && error.code === "ELOCKED"))
111
+ throw error;
112
+ release = await lock(dir, {
113
+ retries: { forever: true, minTimeout: 10, maxTimeout: 100, randomize: true },
114
+ });
115
+ }
116
+ try {
117
+ return await operation();
118
+ }
119
+ finally {
120
+ await release();
121
+ }
122
+ }
123
+ export async function openProfile(dir, theories, options = {}) {
124
+ dir = resolve(dir);
125
+ if (!options.readOnly)
126
+ await locked(dir, async () => {
127
+ const stored = await filesAt(dir);
128
+ const initial = migrateProfileFiles(stored, theories);
129
+ // Immutable data first, then a single atomic live-head/log/pin switch. An interruption
130
+ // leaves either the old generation or the complete new one; retry never repeats a step.
131
+ for (const [path, bytes] of initial) {
132
+ if (path !== "profile.json" && !stored.has(path))
133
+ await immutable(dir, path, bytes);
134
+ }
135
+ const manifest = initial.get("profile.json");
136
+ if (manifest !== stored.get("profile.json") && manifest)
137
+ await atomic(dir, "profile.json", manifest);
138
+ const profile = validate(initial, theories);
139
+ // A copied or moved Profile must still appear in pi's cwd-filtered /resume list.
140
+ for (const filename of Object.values(profile.manifest.sessions)) {
141
+ const path = "sessions/" + filename;
142
+ const bytes = initial.get(path);
143
+ if (bytes) {
144
+ const source = new TextDecoder().decode(bytes);
145
+ if (parsePiSession(source).header.cwd !== dir)
146
+ await atomic(dir, path, utf8.encode(relocatePiSession(source, dir)));
147
+ }
148
+ }
149
+ });
150
+ // Queue this handle's writes before contending with other handles and processes.
127
151
  let tail = Promise.resolve();
128
152
  function serial(operation) {
129
- const result = tail.then(operation);
153
+ if (options.readOnly)
154
+ return Promise.reject(new Error("Cannot write through a read-only Profile"));
155
+ const result = tail.then(() => locked(dir, operation));
130
156
  tail = result.catch(() => { });
131
157
  return result;
132
158
  }
@@ -137,6 +163,12 @@ export async function openProfile(dir, theories) {
137
163
  const files = await filesAt(dir);
138
164
  const manifest = { ...parseManifest(files.get("profile.json")), ...change };
139
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);
140
172
  for (const filename of Object.values(manifest.sessions)) {
141
173
  const path = "sessions/" + filename;
142
174
  if (!files.has(path))
@@ -162,8 +194,10 @@ export async function openProfile(dir, theories) {
162
194
  dir,
163
195
  read,
164
196
  files: () => filesAt(dir),
165
- appendLog: (entries) => serial(async () => {
197
+ appendLog: (entries, accept) => serial(async () => {
166
198
  const current = await read();
199
+ if (accept && !accept(current))
200
+ return;
167
201
  const bytes = logBytes(mergeProfileLogs(current.log, entries));
168
202
  const manifest = { ...current.manifest, log: attachmentDigest(bytes) };
169
203
  await immutable(dir, liveLogPath(manifest), bytes);
package/dist/exchange.js CHANGED
@@ -1,4 +1,4 @@
1
- import { attachmentDigest, bundleForRevision, isContentDigest, isPatchId, isProfileLogEntry, mergeProfileLogs, migrateTheoryProfile, resolveTheory, revisionDigest, } from "@mmon-co/ncept-core";
1
+ import { attachmentDigest, notebookBundleForRevision, isContentDigest, isPatchId, isProfileLogEntry, mergeProfileLogs, migrateTheoryProfile, resolveTheory, revisionDigest, } from "@mmon-co/ncept-core";
2
2
  import { object, parsePiSession, relocatePiSession } from "./sessions.js";
3
3
  import { decodeTar, encodeTar } from "./tar.js";
4
4
  export const DEFAULT_THEORY_PACKAGES = ["@mmon-co/ncept-default-theory"];
@@ -139,7 +139,7 @@ function validateStructure(files) {
139
139
  else
140
140
  throw new Error("Unexpected Profile exchange file: " + path);
141
141
  }
142
- const patches = bundleForRevision(manifest.personal, contents);
142
+ const patches = notebookBundleForRevision(manifest.personal, contents);
143
143
  for (const content of contents.values())
144
144
  requireAttachments(content, blobs);
145
145
  const sessions = new Map();
@@ -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") {
@@ -435,7 +435,9 @@ export function hostTools(host, opened, capabilities, skills, metadataKeys) {
435
435
  });
436
436
  }
437
437
  if (metadataKeys.length) {
438
- mount("edit_metadata", "Edit this mode's authorized metadata keys on existing Nodes: " + metadataKeys.join(", "), schema({ nodes: nodeList, properties: { type: "object" } }, ["nodes", "properties"]), async (raw, session) => {
438
+ mount("edit_metadata", "Edit this mode's authorized metadata keys on existing Nodes: " +
439
+ metadataKeys.join(", ") +
440
+ ". Material completion queries use the created Material's identity; local file-item attempts, including card recalls, have playground local.", schema({ nodes: nodeList, properties: { type: "object" } }, ["nodes", "properties"]), async (raw, session) => {
439
441
  const attached = nodes(raw.nodes);
440
442
  const properties = metadataProperties(raw.properties);
441
443
  if (Object.keys(properties).some((key) => !metadataKeys.includes(key)))
package/dist/host.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ChatSetup, HostCapability, ExactPatchRef, JsonSchema, LessonReading, Mission, MissionRunReading, ModeEntry, ModeSwitchDefault, NodeId, Request, SessionRef, Theory, TheoryRequirement } from "@mmon-co/ncept-core";
1
+ import type { ChatSetup, HostCapability, ExactPatchRef, JsonSchema, LessonReading, MissionPathReading, Mission, MissionRunReading, ModeEntry, ModeSwitchDefault, NodeId, Request, SessionRef, Theory, TheoryRequirement } from "@mmon-co/ncept-core";
2
2
  import type { ProfileDirectory } from "./directory.js";
3
3
  /** The host supplies both judge and assess with the concrete JSON reply schema. */
4
4
  export type ModelRequest = Extract<Request, {
@@ -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<{
@@ -42,6 +43,7 @@ export interface MissionReading {
42
43
  readonly mission: Mission;
43
44
  readonly run: MissionRunReading;
44
45
  readonly next: readonly LessonReading[];
46
+ readonly path?: MissionPathReading;
45
47
  }
46
48
  export interface HostReading {
47
49
  readonly missions: readonly MissionReading[];
@@ -61,18 +63,56 @@ export interface HostConfig {
61
63
  readonly theories: readonly string[];
62
64
  /** IANA zone for learner-days; defaults to the local machine's configured zone. */
63
65
  readonly timezone?: string;
66
+ /** Positive Session budget in minutes; defaults to 20. */
67
+ readonly sessionLength?: number;
64
68
  }
69
+ export type SessionOpening = Readonly<{
70
+ mode: string;
71
+ entry?: ModeEntry;
72
+ resume?: SessionRef;
73
+ mission?: string;
74
+ }> & Readonly<{
75
+ skip?: {
76
+ mission: string;
77
+ kind: "skip-lesson";
78
+ } | {
79
+ mission: string;
80
+ kind: "skip-to";
81
+ stop: Pick<LessonReading, "kind" | "number" | "checkpoint">;
82
+ };
83
+ }>;
84
+ /** Learner entry controls; resolved against current Profile state by its writing tutor. */
85
+ export type SessionIntent = Readonly<{
86
+ kind: "skip-lesson";
87
+ missionId: string;
88
+ }> | Readonly<{
89
+ kind: "skip-to";
90
+ missionId: string;
91
+ stop: Pick<LessonReading, "kind" | "number" | "checkpoint">;
92
+ }> | Readonly<{
93
+ kind: "continue" | "revise-lesson" | "revise-route";
94
+ missionId: string;
95
+ }> | Readonly<{
96
+ kind: "tell-tutor";
97
+ missionId: string;
98
+ request: string;
99
+ }> | Readonly<{
100
+ kind: "new-mission" | "review";
101
+ }>;
65
102
  export interface Host {
66
103
  readonly profile: ProfileDirectory;
67
104
  readonly sessions: {
68
- open(input: Readonly<{
69
- mode: string;
70
- entry?: ModeEntry;
71
- resume?: SessionRef;
72
- }>): Promise<HostSession>;
105
+ open(input: SessionOpening): Promise<HostSession>;
106
+ begin(intent: SessionIntent): Promise<HostSession>;
73
107
  turn(session: HostSession, input: Readonly<{
74
108
  learnerMessage?: string;
75
109
  }>): Promise<HostChatSetup>;
110
+ /** After the conversation stops, end a completed Lesson and return its next surface. */
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>;
76
116
  close(session: HostSession): Promise<void>;
77
117
  };
78
118
  readonly missions: {
@@ -91,6 +131,15 @@ export interface Host {
91
131
  title: string;
92
132
  description?: string;
93
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>;
94
143
  exportTo(destination: "web"): Promise<void>;
95
144
  importFrom(source: "web"): Promise<ImportResult>;
96
145
  };
@@ -118,5 +167,7 @@ export interface OpenHostOptions<S> {
118
167
  readonly theories: readonly Theory<S>[];
119
168
  readonly model: Model;
120
169
  readonly confirm: Confirm;
170
+ /** Receives failures from the background recovery sweep. */
171
+ readonly onCloseError?: (error: unknown) => void;
121
172
  }
122
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
@@ -1,14 +1,99 @@
1
1
  import { mkdtemp, rename, rm } from "node:fs/promises";
2
2
  import { dirname, basename, join } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
- import { attachmentDigest, bundleForRevision, candidateRevision, exactPatchRefKey, isAttachment, isContentDigest, isPatchId, migrateTheoryPatchClosure, releasePrecedenceKey, resolveTheory, resolvePatchBundle, revisionContent, sameExactPatchRef, } from "@mmon-co/ncept-core";
4
+ import metadata from "../package.json" with { type: "json" };
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,16 +179,15 @@ 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
- const { version } = createRequire(import.meta.url)("../package.json");
101
- const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + version };
185
+ const headers = { "User-Agent": options.userAgent ?? "@mmon-co/ncept-local/" + metadata.version };
102
186
  async function connected(operation) {
103
187
  const provider = await HubAuth.open(resource, options);
104
188
  if (!provider.tokens())
105
189
  throw new Error("Sign in first with host.hub.signIn()");
106
- const client = new Client({ name: "@mmon-co/ncept-local", version: "0.1.0" });
190
+ const client = new Client({ name: metadata.name, version: metadata.version });
107
191
  try {
108
192
  await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider }));
109
193
  return await operation(async (name, args) => {
@@ -136,6 +220,25 @@ export function connectHub(profile, theories, confirm, options = {}) {
136
220
  });
137
221
  return hash;
138
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
+ }
139
242
  return {
140
243
  async pull(address) {
141
244
  const selected = releaseAddress(address, base);
@@ -194,6 +297,21 @@ export function connectHub(profile, theories, confirm, options = {}) {
194
297
  const next = candidateRevision(personal.ref.identity, content);
195
298
  contents.set(next.ref.digest, content);
196
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
+ }
197
315
  // Nothing touches the live head until every downloaded revision and blob verifies.
198
316
  for (const bytes of blobs.values())
199
317
  await profile.addBlob(bytes);
@@ -203,6 +321,8 @@ export function connectHub(profile, theories, confirm, options = {}) {
203
321
  if (!revisions.has(exactPatchRefKey(revision.ref)))
204
322
  await profile.addRevision(revision.ref.identity, revisionContent(revision));
205
323
  await profile.setPersonal(await profile.addRevision(personal.ref.identity, content));
324
+ for (const mission of selectedMissions)
325
+ await createMission(mission);
206
326
  return adopted.ref;
207
327
  },
208
328
  async signIn() {
@@ -238,54 +358,51 @@ export function connectHub(profile, theories, confirm, options = {}) {
238
358
  detail: { ...input, bundle },
239
359
  })))
240
360
  throw new Error("Publication declined");
241
- return connected(async (call) => {
242
- for (const attachment of attachments(bundle)) {
243
- const bytes = current.blobs.get(attachment.hash);
244
- if (!bytes)
245
- throw new Error("Missing Profile blob: " + attachment.hash);
246
- await upload(call, bytes, attachment.mediaType);
247
- }
248
- const captured = await call("capture", { bundle });
249
- await call("name", { patchId: captured.ref.identity, digest: captured.ref.digest, version: input.version });
250
- await call("publish", { patchId: captured.ref.identity, version: input.version });
251
- return {
252
- ref: captured.ref,
253
- version: input.version,
254
- url: base + "/hub/" + captured.ref.identity + "/releases/" + encodeURIComponent(input.version),
255
- };
256
- });
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);
257
390
  },
258
391
  async exportTo() {
259
392
  const archive = await profile.pack();
260
393
  await connected(async (call) => {
261
394
  const hash = await upload(call, archive, "application/x-tar");
262
395
  const preview = await call("import_profile", { hash });
263
- let missions;
264
- if (preview.status === "choose-missions") {
265
- missions = [];
266
- for (const mission of preview.missions) {
267
- if (preview.available !== null && missions.length >= preview.available)
268
- break;
269
- if (await confirm({
270
- kind: "hub.choose-mission",
271
- title: "Keep Mission: " + mission.statement,
272
- description: "Choose Missions to move to the web within your allowance, or upgrade on the web first.",
273
- detail: { mission, available: preview.available, upgrade: preview.upgrade },
274
- }))
275
- missions.push(mission.id);
276
- }
277
- }
278
396
  if (!(await confirm({
279
397
  kind: "hub.export",
280
398
  title: "Replace web Main with this local Profile",
281
- description: "The old web Main is retained as history. Unchosen Missions remain here locally.",
282
- detail: { ...preview, chosenMissions: missions },
399
+ description: "The old web Main is retained as history.",
400
+ detail: preview,
283
401
  })))
284
402
  return;
285
403
  const result = await call("import_profile", {
286
404
  hash,
287
405
  expectedMainProfileId: preview.mainProfileId,
288
- ...(missions === undefined ? {} : { missions }),
289
406
  });
290
407
  if (result.status !== "imported")
291
408
  throw new Error("Web import needs a new preview: " + JSON.stringify(result));
package/dist/index.d.ts CHANGED
@@ -2,3 +2,4 @@ export * from "./exchange.js";
2
2
  export * from "./sessions.js";
3
3
  export * from "./directory.js";
4
4
  export * from "./host.js";
5
+ export { openLearningReader } from "./learning.js";
package/dist/index.js CHANGED
@@ -2,3 +2,4 @@ export * from "./exchange.js";
2
2
  export * from "./sessions.js";
3
3
  export * from "./directory.js";
4
4
  export * from "./host.js";
5
+ export { openLearningReader } from "./learning.js";