@mmon-co/ncept-default-theory 0.0.0-stage → 1.0.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -2
  3. package/dist/catalog-contract.d.ts +102 -0
  4. package/dist/catalog-contract.js +75 -0
  5. package/dist/catalog.d.ts +14 -0
  6. package/dist/catalog.js +164 -0
  7. package/dist/chat.d.ts +171 -0
  8. package/dist/chat.js +203 -0
  9. package/dist/completion.d.ts +74 -0
  10. package/dist/completion.js +277 -0
  11. package/dist/dependent-cone.d.ts +3 -0
  12. package/dist/dependent-cone.js +26 -0
  13. package/dist/diagnosis.d.ts +9 -0
  14. package/dist/diagnosis.js +1 -0
  15. package/dist/diagnostics.d.ts +25 -0
  16. package/dist/diagnostics.js +34 -0
  17. package/dist/evaluation.d.ts +33 -0
  18. package/dist/evaluation.js +376 -0
  19. package/dist/event.d.ts +7 -0
  20. package/dist/event.js +405 -0
  21. package/dist/history.d.ts +4 -0
  22. package/dist/history.js +61 -0
  23. package/dist/implementation.d.ts +170 -0
  24. package/dist/implementation.js +30 -0
  25. package/dist/index.d.ts +185 -0
  26. package/dist/index.js +26 -0
  27. package/dist/messages.d.ts +167 -0
  28. package/dist/messages.js +56 -0
  29. package/dist/outcomes.d.ts +143 -0
  30. package/dist/outcomes.js +323 -0
  31. package/dist/path.d.ts +17 -0
  32. package/dist/path.js +292 -0
  33. package/dist/reading.d.ts +12 -0
  34. package/dist/reading.js +75 -0
  35. package/dist/release.d.ts +1 -0
  36. package/dist/release.js +1 -0
  37. package/dist/roleplay.d.ts +17 -0
  38. package/dist/roleplay.js +2 -0
  39. package/dist/skills/sources.d.ts +12 -0
  40. package/dist/skills/sources.js +13 -0
  41. package/dist/skills.d.ts +12 -0
  42. package/dist/skills.js +70 -0
  43. package/dist/state.d.ts +316 -0
  44. package/dist/state.js +1309 -0
  45. package/dist/tags.d.ts +34 -0
  46. package/dist/tags.js +306 -0
  47. package/dist/timing.d.ts +21 -0
  48. package/dist/timing.js +79 -0
  49. package/dist/tools.d.ts +394 -0
  50. package/dist/tools.js +872 -0
  51. package/package.json +52 -4
@@ -0,0 +1,323 @@
1
+ import { isContentDigest } from "@mmon-co/ncept-core/digest";
2
+ import { isObservationTimestamp } from "@mmon-co/ncept-core/observations";
3
+ export { isCompletionOutcome } from "./state.js";
4
+ function object(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function text(value) {
8
+ return typeof value === "string" && value.trim().length > 0;
9
+ }
10
+ const checkOutcome = (value) => value === "shown" || value === "absent" || value === "mistaken" || value === "skipped";
11
+ const nodeId = (value) => typeof value === "string" && /^node-.+/.test(value);
12
+ const exactRef = (value) => object(value) &&
13
+ typeof value.identity === "string" &&
14
+ /^patch-.+/.test(value.identity) &&
15
+ isContentDigest(value.digest);
16
+ const nodeRef = (value) => object(value) && nodeId(value.node) && exactRef(value.provenance);
17
+ export function isAttemptOutcome(value) {
18
+ if (!object(value) || value.kind !== "attempt" || !object(value.problem) || !object(value.assessment))
19
+ return false;
20
+ const { problem, assessment, response } = value;
21
+ const optional = (field) => field === undefined || text(field);
22
+ if (!text(problem.id) ||
23
+ !isContentDigest(problem.digest) ||
24
+ !Array.isArray(problem.about) ||
25
+ problem.about.length === 0 ||
26
+ !problem.about.every(nodeId) ||
27
+ new Set(problem.about).size !== problem.about.length ||
28
+ !text(problem.prompt) ||
29
+ !optional(problem.presentation) ||
30
+ typeof response !== "string" ||
31
+ typeof assessment.correct !== "boolean" ||
32
+ (assessment.aided !== undefined && assessment.aided !== true) ||
33
+ !optional(assessment.feedback) ||
34
+ (assessment.dontKnow !== undefined &&
35
+ (assessment.dontKnow !== true || assessment.correct !== false || assessment.grader !== "learner")) ||
36
+ !exactRef(value.revision))
37
+ return false;
38
+ const dontKnow = assessment.dontKnow === true;
39
+ const { answer, grader } = problem;
40
+ if (!object(answer) || !object(grader))
41
+ return false;
42
+ if (answer.kind === "choice") {
43
+ const options = answer.options;
44
+ if (grader.by !== "mechanical" ||
45
+ grader.accepted !== undefined ||
46
+ !Array.isArray(options) ||
47
+ !options.every((option) => object(option) &&
48
+ text(option.id) &&
49
+ text(option.label) &&
50
+ typeof option.correct === "boolean" &&
51
+ optional(option.error)) ||
52
+ new Set(options.map(({ id }) => id)).size !== options.length)
53
+ return false;
54
+ const chosen = options.find(({ id }) => id === response);
55
+ return (dontKnow ||
56
+ (chosen !== undefined &&
57
+ (assessment.grader === "tutor" ||
58
+ (assessment.grader === "mechanical" && chosen.correct === assessment.correct))));
59
+ }
60
+ if (answer.kind === "short")
61
+ return (grader.by === "mechanical" &&
62
+ Array.isArray(grader.accepted) &&
63
+ grader.accepted.length > 0 &&
64
+ grader.accepted.every(text) &&
65
+ // Natural-language assessment standards can require adjudicating the authored answer key.
66
+ (dontKnow || assessment.grader === "mechanical" || assessment.grader === "tutor"));
67
+ if (answer.kind === "applet") {
68
+ if (!object(answer.material) ||
69
+ !text(answer.material.id) ||
70
+ !exactRef(answer.material.revision) ||
71
+ !text(answer.read) ||
72
+ (answer.setup !== undefined &&
73
+ (!Array.isArray(answer.setup) ||
74
+ !answer.setup.every((step) => object(step) && text(step.command) && Object.hasOwn(step, "input")))))
75
+ return false;
76
+ }
77
+ else if (answer.kind === "roleplay") {
78
+ if (!object(answer.material) || !text(answer.material.id) || !exactRef(answer.material.revision))
79
+ return false;
80
+ }
81
+ else if (answer.kind !== "text")
82
+ return false;
83
+ if (grader.by === "tutor" || grader.by === "learner")
84
+ return optional(grader.rubric) && (dontKnow || assessment.grader === grader.by);
85
+ if (grader.by !== "checks")
86
+ return false;
87
+ const checks = grader.checks;
88
+ const about = new Set(Array.isArray(problem.about) ? problem.about : []);
89
+ if (!Array.isArray(checks) || checks.length === 0 || !Array.isArray(grader.pumps))
90
+ return false;
91
+ const valid = checks.every((c) => object(c) &&
92
+ text(c.id) &&
93
+ text(c.ask) &&
94
+ text(c.shown) &&
95
+ text(c.absent) &&
96
+ Array.isArray(c.about) &&
97
+ c.about.length > 0 &&
98
+ c.about.every((node) => nodeId(node) && about.has(node)));
99
+ const results = (value) => object(value) && Object.values(value).every((r) => object(r) && checkOutcome(r.outcome));
100
+ const final = assessment.checks;
101
+ return (valid &&
102
+ ["pump", "hint", "correct"].includes(String(grader.help)) &&
103
+ (dontKnow ||
104
+ // Decision outages can delegate the whole assessment to the tutor.
105
+ assessment.grader === "tutor" ||
106
+ (assessment.grader === "decision" &&
107
+ results(final) &&
108
+ (assessment.helped === undefined || results(assessment.helped)) &&
109
+ assessment.correct ===
110
+ checks.every((c) => {
111
+ const result = object(final) ? final[c.id] : undefined;
112
+ return object(result) && result.outcome === "shown";
113
+ }))));
114
+ }
115
+ /** Guards validate the supported payload, including the captured grading invariants. */
116
+ export function isRecallOutcome(value) {
117
+ if (!object(value) || value.kind !== "recall" || !object(value.card) || !object(value.grade))
118
+ return false;
119
+ const { card, grade } = value;
120
+ return (text(card.id) &&
121
+ typeof card.front === "string" &&
122
+ typeof card.back === "string" &&
123
+ Array.isArray(card.nodes) &&
124
+ card.nodes.length > 0 &&
125
+ card.nodes.every(nodeRef) &&
126
+ new Set(card.nodes.map((node) => node.node)).size === card.nodes.length &&
127
+ text(grade.id) &&
128
+ grade.cardId === card.id &&
129
+ isObservationTimestamp(grade.gradedAt) &&
130
+ text(grade.answer) &&
131
+ typeof grade.grade === "string" &&
132
+ ["again", "hard", "good", "easy"].includes(grade.grade) &&
133
+ !(grade.answer.trim() === card.back.trim() && grade.grade === "again"));
134
+ }
135
+ export function isQuizOutcome(value) {
136
+ if (!object(value) ||
137
+ value.kind !== "quiz" ||
138
+ !text(value.id) ||
139
+ !isObservationTimestamp(value.at) ||
140
+ !nodeRef(value.node) ||
141
+ !Array.isArray(value.questions) ||
142
+ !Array.isArray(value.responses))
143
+ return false;
144
+ if (!value.questions.every((question) => object(question) &&
145
+ text(question.id) &&
146
+ typeof question.prompt === "string" &&
147
+ Array.isArray(question.options) &&
148
+ question.options.length > 0 &&
149
+ question.options.every((option) => object(option) &&
150
+ text(option.id) &&
151
+ typeof option.label === "string" &&
152
+ typeof option.correct === "boolean" &&
153
+ (option.error === undefined || typeof option.error === "string")) &&
154
+ new Set(question.options.map((option) => option.id)).size === question.options.length))
155
+ return false;
156
+ if (!value.responses.every((response) => object(response) &&
157
+ text(response.questionId) &&
158
+ typeof response.skipped === "boolean" &&
159
+ (response.selectedOptionId === undefined || text(response.selectedOptionId)) &&
160
+ (response.comment === undefined || typeof response.comment === "string")))
161
+ return false;
162
+ const { questions, responses } = value;
163
+ return (responses.length === questions.length &&
164
+ new Set(questions.map(({ id }) => id)).size === questions.length &&
165
+ new Set(responses.map(({ questionId }) => questionId)).size === questions.length &&
166
+ questions.every((question) => {
167
+ const response = responses.find(({ questionId }) => questionId === question.id);
168
+ return (response !== undefined &&
169
+ (response.skipped
170
+ ? response.selectedOptionId === undefined
171
+ : question.options.some(({ id }) => id === response.selectedOptionId)));
172
+ }));
173
+ }
174
+ /** The existing verbatim unaided-card rule, recomputed from the attempt's content. */
175
+ export function recallUnaided(card) {
176
+ const normalize = (value) => value.trim().toLocaleLowerCase().replace(/\s+/g, " ");
177
+ const front = normalize(card.front);
178
+ const back = normalize(card.back);
179
+ const leaksAnswer = back.length > 0 && front.includes(back);
180
+ const offersCandidates = /(^|\n)\s*(?:[a-d][).]|[-*•])\s+/i.test(card.front) || /\bwhich of\b/i.test(card.front);
181
+ return !leaksAnswer && !offersCandidates;
182
+ }
183
+ function checkNote(check, { outcome, error }) {
184
+ if (outcome === "shown")
185
+ return `Shown: ${check.shown}`;
186
+ if (outcome === "absent")
187
+ return `Not taken up: ${check.absent}`;
188
+ if (outcome === "skipped")
189
+ return "Set aside: I can't say";
190
+ return `Mistaken (${error ?? "unnamed"}): ${(error && check.mistaken?.[error]) ?? "a wrong version"}`;
191
+ }
192
+ /** One demonstration per Node and help state, pinned to the revision the Problem was opened at. */
193
+ export function problemAttempts(outcome, at) {
194
+ const { problem, response, assessment } = outcome;
195
+ if (assessment.dontKnow)
196
+ return problem.about.map((node) => ({
197
+ at,
198
+ payload: {
199
+ kind: "demonstration",
200
+ item: problem.id,
201
+ node: { node, provenance: { ...outcome.revision } },
202
+ outcome: "dont-know",
203
+ unaided: !assessment.aided,
204
+ grader: "learner",
205
+ task: problem.prompt,
206
+ response,
207
+ },
208
+ }));
209
+ // Checks judged from one response are dependent evidence, not separate window entries.
210
+ if (problem.grader.by === "checks" && assessment.grader !== "tutor") {
211
+ const checksByNode = new Map();
212
+ for (const check of problem.grader.checks)
213
+ for (const node of check.about) {
214
+ const checks = checksByNode.get(node) ?? [];
215
+ checks.push(check);
216
+ checksByNode.set(node, checks);
217
+ }
218
+ return [...checksByNode].flatMap(([node, checks]) => {
219
+ const record = (beforeHelp) => {
220
+ const results = checks.map((check) => ({
221
+ check,
222
+ result: (beforeHelp ? assessment.helped?.[check.id] : undefined) ??
223
+ assessment.checks?.[check.id] ?? { outcome: "absent" },
224
+ }));
225
+ const result = results.some(({ result: { outcome } }) => outcome === "absent" || outcome === "mistaken")
226
+ ? "failure"
227
+ : results.some(({ result: { outcome } }) => outcome === "skipped")
228
+ ? "dont-know"
229
+ : "success";
230
+ return {
231
+ at,
232
+ payload: {
233
+ kind: "demonstration",
234
+ item: problem.id,
235
+ node: { node, provenance: { ...outcome.revision } },
236
+ outcome: result,
237
+ unaided: beforeHelp && !assessment.aided,
238
+ grader: result === "dont-know" ? "learner" : assessment.grader,
239
+ task: [problem.prompt, ...checks.map((check) => `Check: ${check.ask}`)].join("\n"),
240
+ response: [response, ...results.map(({ check, result }) => checkNote(check, result))].join("\n"),
241
+ },
242
+ };
243
+ };
244
+ return checks.some((check) => assessment.helped?.[check.id] !== undefined)
245
+ ? [record(true), record(false)]
246
+ : [record(true)];
247
+ });
248
+ }
249
+ const choice = problem.answer.kind === "choice" ? problem.answer.options : undefined;
250
+ const answer = choice?.find(({ id }) => id === response)?.label ?? response;
251
+ return problem.about.map((node) => ({
252
+ at,
253
+ payload: {
254
+ kind: "demonstration",
255
+ item: problem.id,
256
+ node: { node, provenance: { ...outcome.revision } },
257
+ outcome: assessment.correct ? "success" : "failure",
258
+ unaided: !assessment.aided,
259
+ grader: assessment.grader,
260
+ task: choice ? `${problem.prompt}\n${choice.map(({ label }) => `- ${label}`).join("\n")}` : problem.prompt,
261
+ response: answer,
262
+ },
263
+ }));
264
+ }
265
+ /** Pure scoring over captured values; no current Material or graph read can rewrite an attempt. */
266
+ export function practiceAttempts(outcome) {
267
+ if (outcome.kind === "recall") {
268
+ const { card, grade } = outcome;
269
+ return card.nodes.map((node) => ({
270
+ at: grade.gradedAt,
271
+ payload: {
272
+ kind: "demonstration",
273
+ item: card.id,
274
+ node: { node: node.node, provenance: { ...node.provenance } },
275
+ outcome: grade.grade === "again" ? "failure" : "success",
276
+ unaided: recallUnaided(card),
277
+ grader: grade.answer.trim() === card.back.trim() ? "mechanical" : "learner",
278
+ task: card.front,
279
+ response: grade.answer,
280
+ },
281
+ }));
282
+ }
283
+ return outcome.questions.flatMap((question) => {
284
+ const response = outcome.responses.find(({ questionId }) => questionId === question.id);
285
+ if (response === undefined)
286
+ return [];
287
+ if (response.skipped)
288
+ return [
289
+ {
290
+ at: outcome.at,
291
+ payload: {
292
+ kind: "demonstration",
293
+ item: question.id,
294
+ node: { ...outcome.node },
295
+ outcome: "dont-know",
296
+ unaided: true,
297
+ grader: "learner",
298
+ task: question.prompt,
299
+ response: response.comment ? `I don\u0027t know\n${response.comment}` : "I don\u0027t know",
300
+ },
301
+ },
302
+ ];
303
+ const option = question.options.find(({ id }) => id === response.selectedOptionId);
304
+ if (option === undefined)
305
+ throw new Error("Invalid question response");
306
+ const answer = response.comment ? `${option.label}\n${response.comment}` : option.label;
307
+ return [
308
+ {
309
+ at: outcome.at,
310
+ payload: {
311
+ kind: "demonstration",
312
+ item: question.id,
313
+ node: { node: outcome.node.node, provenance: { ...outcome.node.provenance } },
314
+ outcome: option.correct ? "success" : "failure",
315
+ unaided: true,
316
+ grader: "mechanical",
317
+ task: `${question.prompt}\n${question.options.map((choice) => `- ${choice.label}`).join("\n")}`,
318
+ response: option.error === undefined ? answer : `${answer}\n${option.error}`,
319
+ },
320
+ },
321
+ ];
322
+ });
323
+ }
package/dist/path.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type NodeId, type ResolvedGraph } from "@mmon-co/ncept-core/patch";
2
+ import { type MissionPath, type MissionFuture, type PathContext } from "@mmon-co/ncept-core/theory";
3
+ /** Default-theory authoring metadata, not Core graph vocabulary. */
4
+ export declare function pathProperty(graph: ResolvedGraph, node: NodeId, key: string): unknown;
5
+ /** Default-theory hint: an absolute integer, higher first, inherited from tags. */
6
+ export declare function nodePriority(graph: ResolvedGraph, node: NodeId): number;
7
+ /** A topological schedule with atomic lesson groups wherever their external blockers allow it.
8
+ * If contraction would create a cycle, emit a ready prefix and leave the rest for after the
9
+ * outside blocker. Overlapping tags remain separate lessons; coverage is claimed by section,
10
+ * not by lesson, so a Node may be taught in more than one group.
11
+ */
12
+ export declare function teachingPath(graph: ResolvedGraph, targets: readonly NodeId[]): MissionPath;
13
+ /** The syllabus stays addressable as progress changes; only the future is upcoming.
14
+ * A trailing unnumbered review is maintenance; a review with numberOffset 1 blocks the
15
+ * following teaching stop. A graph-wide reading has only maintenance, and no Mission.
16
+ */
17
+ export declare function pathDefault(context: PathContext): MissionFuture;
package/dist/path.js ADDED
@@ -0,0 +1,292 @@
1
+ import { lastMetadataContribution, metadataSetsForEntity, NODE_ELABORATE_PROPERTY, nodeCascadedProperty, route, unscopedCopyTagName, } from "@mmon-co/ncept-core/patch";
2
+ import { dependentCones } from "./dependent-cone.js";
3
+ import { LESSON_TAG_PREFIX, tagIndex, } from "@mmon-co/ncept-core/theory";
4
+ import { prepareEstimateDefault, progressDefault } from "./reading.js";
5
+ import { DEFAULT_PARAMETERS, stateDefault } from "./state.js";
6
+ import { forgetting_curve } from "ts-fsrs";
7
+ /** Default-theory authoring metadata, not Core graph vocabulary. */
8
+ export function pathProperty(graph, node, key) {
9
+ return lastMetadataContribution(graph, metadataSetsForEntity(graph, { kind: "node", id: node }).flatMap((set) => {
10
+ const source = graph.provenance.metadataProperties[set.id]?.[key]?.at(-1);
11
+ return source === undefined ? [] : [{ value: set.properties[key], source }];
12
+ }))?.value;
13
+ }
14
+ /** Default-theory hint: an absolute integer, higher first, inherited from tags. */
15
+ export function nodePriority(graph, node) {
16
+ const value = nodeCascadedProperty(graph, node, "pedagogy:priority");
17
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : 0;
18
+ }
19
+ /** A topological schedule with atomic lesson groups wherever their external blockers allow it.
20
+ * If contraction would create a cycle, emit a ready prefix and leave the rest for after the
21
+ * outside blocker. Overlapping tags remain separate lessons; coverage is claimed by section,
22
+ * not by lesson, so a Node may be taught in more than one group.
23
+ */
24
+ export function teachingPath(graph, targets) {
25
+ const stable = [];
26
+ const cones = new Map();
27
+ const cone = (id) => {
28
+ let held = cones.get(id);
29
+ if (held === undefined) {
30
+ const result = route(graph, id);
31
+ held = result.kind === "found" ? result.nodes.map(({ id }) => id) : [];
32
+ cones.set(id, held);
33
+ }
34
+ return held;
35
+ };
36
+ for (const target of targets)
37
+ for (const id of cone(target))
38
+ if (!stable.includes(id))
39
+ stable.push(id);
40
+ const rank = new Map(stable.map((id, index) => [id, index]));
41
+ const dependents = dependentCones(graph);
42
+ const priority = new Map(stable.map((id) => [id, nodePriority(graph, id)]));
43
+ const importance = new Map(stable.map((id) => [id, dependents(id).filter((node) => rank.has(node)).length]));
44
+ const compare = (a, b) => (priority.get(b) ?? 0) - (priority.get(a) ?? 0) ||
45
+ (importance.get(b) ?? 0) - (importance.get(a) ?? 0) ||
46
+ (rank.get(a) ?? 0) - (rank.get(b) ?? 0);
47
+ const prerequisites = new Map(stable.map((id) => [id, []]));
48
+ for (const edge of graph.edges)
49
+ prerequisites.get(edge.to)?.push(edge.from);
50
+ const targetSet = new Set(targets);
51
+ const milestones = stable.filter((id) => targetSet.has(id) || pathProperty(graph, id, "pedagogy:milestone") === true);
52
+ const pendingMilestones = new Set(milestones);
53
+ const orderedMilestones = [];
54
+ while (pendingMilestones.size) {
55
+ const ready = [...pendingMilestones].filter((id) => cone(id).every((prerequisite) => prerequisite === id || !pendingMilestones.has(prerequisite)));
56
+ // Targets are the final milestones unless another target depends on them. Independent
57
+ // sections follow the Mission's target order; independent non-target milestones use priority.
58
+ ready.sort((a, b) => Number(targetSet.has(a)) - Number(targetSet.has(b)) ||
59
+ (targetSet.has(a) && targetSet.has(b) ? (rank.get(a) ?? 0) - (rank.get(b) ?? 0) : compare(a, b)));
60
+ const next = ready[0];
61
+ if (next === undefined)
62
+ throw new Error("Milestone dependency cycle");
63
+ pendingMilestones.delete(next);
64
+ orderedMilestones.push(next);
65
+ }
66
+ const milestoneSet = new Set(milestones);
67
+ const groups = graph.tags.filter((tag) => unscopedCopyTagName(tag.name).startsWith(LESSON_TAG_PREFIX));
68
+ const warnings = new Map();
69
+ const warn = (name, nodes) => {
70
+ warnings.set(name, {
71
+ kind: "lesson-split",
72
+ name: unscopedCopyTagName(name).slice(LESSON_TAG_PREFIX.length),
73
+ nodes,
74
+ });
75
+ };
76
+ const claimed = new Set();
77
+ const sections = [];
78
+ const sectionOf = new Map();
79
+ for (const milestone of orderedMilestones) {
80
+ const members = cone(milestone).filter((id) => !claimed.has(id));
81
+ for (const id of members) {
82
+ claimed.add(id);
83
+ sectionOf.set(id, sections.length);
84
+ }
85
+ sections.push({ milestone, lessons: [] });
86
+ }
87
+ for (const group of groups) {
88
+ const members = group.nodes.filter((id) => sectionOf.has(id));
89
+ if (new Set(members.map((id) => sectionOf.get(id))).size > 1 ||
90
+ (members.some((id) => milestoneSet.has(id)) && members.length > 1))
91
+ warn(group.name, members);
92
+ }
93
+ const emitted = new Set();
94
+ for (const [index, section] of sections.entries()) {
95
+ const members = stable.filter((id) => sectionOf.get(id) === index);
96
+ const units = groups.flatMap((group) => {
97
+ const nodes = group.nodes.filter((id) => sectionOf.get(id) === index && !milestoneSet.has(id));
98
+ return nodes.length
99
+ ? [
100
+ {
101
+ name: unscopedCopyTagName(group.name).slice(LESSON_TAG_PREFIX.length),
102
+ groupKey: group.name,
103
+ nodes: [...new Set(nodes)],
104
+ },
105
+ ]
106
+ : [];
107
+ });
108
+ const grouped = new Set(units.flatMap(({ nodes }) => nodes));
109
+ for (const id of members)
110
+ if (!grouped.has(id))
111
+ units.push({ nodes: [id] });
112
+ const readyPrefix = (unit) => {
113
+ const remaining = new Set(unit.nodes);
114
+ const local = new Set(emitted);
115
+ const prefix = [];
116
+ while (remaining.size) {
117
+ const next = [...remaining]
118
+ .filter((id) => (prerequisites.get(id) ?? []).every((prerequisite) => local.has(prerequisite)))
119
+ .sort(compare)[0];
120
+ if (next === undefined)
121
+ break;
122
+ remaining.delete(next);
123
+ local.add(next);
124
+ prefix.push(next);
125
+ }
126
+ return prefix;
127
+ };
128
+ while (units.length) {
129
+ const candidates = units.map((unit) => ({ unit, prefix: readyPrefix(unit) }));
130
+ const whole = candidates.filter(({ unit, prefix }) => prefix.length === unit.nodes.length);
131
+ const available = whole.length ? whole : candidates.filter(({ prefix }) => prefix.length);
132
+ available.sort((a, b) => {
133
+ const left = a.prefix[0], right = b.prefix[0];
134
+ return left === undefined || right === undefined ? 0 : compare(left, right);
135
+ });
136
+ const chosen = available[0];
137
+ if (chosen === undefined)
138
+ throw new Error("Lesson dependency cycle");
139
+ const { unit, prefix } = chosen;
140
+ if (prefix.length !== unit.nodes.length && unit.groupKey !== undefined)
141
+ warn(unit.groupKey, groups.find((tag) => tag.name === unit.groupKey)?.nodes ?? unit.nodes);
142
+ section.lessons.push({
143
+ kind: "lesson",
144
+ numbered: true,
145
+ ...(unit.name === undefined ? {} : { name: unit.name, tag: unit.name }),
146
+ nodes: prefix,
147
+ });
148
+ for (const id of prefix)
149
+ emitted.add(id);
150
+ unit.nodes = unit.nodes.filter((id) => !prefix.includes(id));
151
+ if (!unit.nodes.length)
152
+ units.splice(units.indexOf(unit), 1);
153
+ }
154
+ }
155
+ for (const [index, section] of sections.entries()) {
156
+ const next = sections[index + 1];
157
+ const required = next === undefined ||
158
+ next.lessons.some((lesson) => lesson.nodes.some((node) => pathProperty(graph, node, NODE_ELABORATE_PROPERTY) === true));
159
+ section.lessons.push({
160
+ kind: "checkpoint",
161
+ numbered: false,
162
+ milestone: section.milestone,
163
+ nodes: [section.milestone],
164
+ checkpoint: { milestone: section.milestone, required, ...(next === undefined ? { final: true } : {}) },
165
+ });
166
+ }
167
+ // Nothing precedes the first span, so its check-in has no milestone and is due only while the span is coarse.
168
+ const first = sections[0];
169
+ if (first?.lessons.some((lesson) => lesson.nodes.some((node) => pathProperty(graph, node, NODE_ELABORATE_PROPERTY) === true)))
170
+ first.lessons.unshift({ kind: "checkpoint", numbered: false, nodes: [], checkpoint: { required: true } });
171
+ return { sections, warnings: [...warnings.values()] };
172
+ }
173
+ /** Most overdue first, with deterministic ties independent of projection assembly order. */
174
+ function ranked(nodes, context) {
175
+ const rank = (id) => context.projection.nodes[id]?.find((tag) => tag.tag === "review:due")?.rank ?? 0;
176
+ return [...nodes].sort((a, b) => rank(b) - rank(a) || a.localeCompare(b));
177
+ }
178
+ /** Nodes are indivisible: an over-budget first Node must still make progress. */
179
+ function packed(candidates, context) {
180
+ const estimate = prepareEstimateDefault(context);
181
+ const nodes = [];
182
+ for (const node of ranked(candidates, context)) {
183
+ if (nodes.length &&
184
+ estimate([{ kind: "review", numbered: false, nodes: [...nodes, node] }]).minutes > context.minutes)
185
+ break;
186
+ nodes.push(node);
187
+ }
188
+ return nodes;
189
+ }
190
+ /** Invalidate at the next membership threshold or candidate rank change. FSRS rounds
191
+ * retrievability, so an unrounded analytic crossing would miss the first effective tick.
192
+ * Rank changes are conservative: the order may survive one, but cannot change before it.
193
+ */
194
+ function pathValidity(context, scope) {
195
+ const now = Date.parse(context.now);
196
+ const boundaries = context.projection.validUntil === undefined ? [] : [Date.parse(context.projection.validUntil)];
197
+ const state = stateDefault(context.graph, context.observations, context.now);
198
+ const candidates = context.graph.nodes.flatMap(({ id }) => {
199
+ const schedule = state.nodes[id]?.schedule;
200
+ const rank = context.projection.nodes[id]?.find(({ tag }) => tag === "review:due")?.rank;
201
+ return scope.has(id) && schedule && rank !== undefined
202
+ ? [{ id, schedule, priority: Math.round(rank - 1 + schedule.retrievability) }]
203
+ : [];
204
+ });
205
+ // Integer priority dominates decay. Identical curves keep even their stable ties forever.
206
+ const competing = new Set(candidates
207
+ .filter((a) => candidates.some((b) => a.priority === b.priority &&
208
+ (a.schedule.lastReview !== b.schedule.lastReview || a.schedule.stability !== b.schedule.stability)))
209
+ .map(({ id }) => id));
210
+ for (const { id } of context.graph.nodes) {
211
+ const node = state.nodes[id];
212
+ const schedule = node?.schedule;
213
+ if (!scope.has(id) ||
214
+ !schedule ||
215
+ node.reviewCleared ||
216
+ pathProperty(context.graph, id, "pedagogy:milestone") === true)
217
+ continue;
218
+ const last = Date.parse(schedule.lastReview);
219
+ const at = (time) => forgetting_curve((time - last) / 86_400_000, schedule.stability);
220
+ const nextBelow = (threshold) => {
221
+ if (threshold <= 0 || at(now) < threshold)
222
+ return;
223
+ let low = now, high = now + 86_400_000;
224
+ while (at(high) >= threshold && high < 8_640_000_000_000_000)
225
+ high = Math.min(8_640_000_000_000_000, now + (high - now) * 2);
226
+ if (at(high) >= threshold)
227
+ return;
228
+ while (high - low > 1) {
229
+ const mid = Math.floor(low + (high - low) / 2);
230
+ if (at(mid) < threshold)
231
+ high = mid;
232
+ else
233
+ low = mid;
234
+ }
235
+ boundaries.push(high);
236
+ };
237
+ if (!schedule.lapsed) {
238
+ nextBelow(DEFAULT_PARAMETERS.retention.due);
239
+ nextBelow(DEFAULT_PARAMETERS.retention.fading);
240
+ }
241
+ if (competing.has(id))
242
+ nextBelow(schedule.retrievability);
243
+ }
244
+ const expiry = Math.min(...boundaries);
245
+ return Number.isFinite(expiry) ? { validUntil: new Date(expiry).toISOString() } : {};
246
+ }
247
+ /** The syllabus stays addressable as progress changes; only the future is upcoming.
248
+ * A trailing unnumbered review is maintenance; a review with numberOffset 1 blocks the
249
+ * following teaching stop. A graph-wide reading has only maintenance, and no Mission.
250
+ */
251
+ export function pathDefault(context) {
252
+ if (context.retired?.outcome === "abandoned")
253
+ return { sections: [], warnings: [], future: [] };
254
+ const { graph, targets, projection } = context;
255
+ const path = teachingPath(graph, targets ?? []);
256
+ const tags = tagIndex(projection);
257
+ const scope = targets === undefined
258
+ ? new Set(graph.nodes.map(({ id }) => id))
259
+ : new Set(path.sections.flatMap(({ lessons }) => lessons.flatMap(({ nodes }) => nodes)));
260
+ const due = packed(graph.nodes.map(({ id }) => id).filter((id) => scope.has(id) && tags("review:due").has(id)), context);
261
+ const maintenance = due.length ? [{ kind: "review", numbered: false, nodes: due }] : [];
262
+ if (context.retired?.outcome === "achieved" || targets === undefined)
263
+ return { ...path, ...pathValidity(context, scope), future: maintenance };
264
+ const progress = progressDefault(graph, projection, [...scope]);
265
+ const next = path.sections
266
+ .flatMap(({ lessons }) => lessons)
267
+ .find((lesson) => lesson.numbered && lesson.nodes.some((id) => progress[id]?.status === "open"));
268
+ const cone = new Set(next?.nodes.flatMap((id) => {
269
+ const result = route(graph, id);
270
+ return result.kind === "found" ? result.nodes.map(({ id }) => id) : [];
271
+ }) ?? []);
272
+ const fading = packed(graph.nodes
273
+ .map(({ id }) => id)
274
+ .filter((id) => cone.has(id) && !next?.nodes.includes(id) && tags("review:fading").has(id)), context);
275
+ const sections = path.sections.map((section) => ({
276
+ ...section,
277
+ lessons: section.lessons.flatMap((lesson) => lesson === next && fading.length
278
+ ? [{ kind: "review", numbered: false, numberOffset: 1, nodes: fading }, lesson]
279
+ : [lesson]),
280
+ }));
281
+ return {
282
+ ...path,
283
+ ...pathValidity(context, scope),
284
+ sections,
285
+ future: [
286
+ ...sections
287
+ .flatMap(({ lessons }) => lessons)
288
+ .filter((lesson) => !lesson.numbered || lesson.nodes.some((id) => progress[id]?.status === "open")),
289
+ ...maintenance,
290
+ ],
291
+ };
292
+ }
@@ -0,0 +1,12 @@
1
+ import type { NodeId, ResolvedGraph } from "@mmon-co/ncept-core/patch";
2
+ import type { Estimate, EstimateContext, Lesson, NodeProgress, Progress, Tag, TheoryProjection } from "@mmon-co/ncept-core/theory";
3
+ /** Read a frozen default assessment through the same boundary as a live projection. */
4
+ export declare function defaultTagProgress(tags: readonly Tag[]): NodeProgress;
5
+ /** Interpret only the theory vocabulary. Names survive bounded projection publication; the
6
+ * assessment tag is first in projectDefault, so its explanatory display survives there too. */
7
+ export declare function progressDefault(graph: ResolvedGraph, projection: TheoryProjection, nodes: readonly NodeId[]): Progress;
8
+ /** Teaching is unique across the requested scope. Review is a separate activity at each stop,
9
+ * including review of already-acquired Nodes; checkpoints carry no acquisition cost. */
10
+ export declare function estimateDefault(context: EstimateContext, lessons: readonly Lesson[]): Estimate;
11
+ /** Historical inputs belong to this immutable reading, never to a module or a scope cache. */
12
+ export declare function prepareEstimateDefault(context: EstimateContext): (lessons: readonly Lesson[]) => Estimate;