@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
package/dist/tools.js ADDED
@@ -0,0 +1,872 @@
1
+ /* eslint-disable require-yield -- Zero-effect tools are synchronous Programs, not plain values. */
2
+ import { prepareEstimateDefault, progressDefault, estimateDefault } from "./reading.js";
3
+ import { projectDefault } from "./tags.js";
4
+ import { contentDigest } from "@mmon-co/ncept-core/digest";
5
+ import { CATALOG_MAX_PAGE_SIZE, CATALOG_PAGE_SIZE } from "./catalog-contract.js";
6
+ import { effectiveObservations, isObservationId, read, write, } from "@mmon-co/ncept-core/observations";
7
+ import { materialKey, projectVisualGraph, route } from "@mmon-co/ncept-core/patch";
8
+ import { readMissionPath } from "@mmon-co/ncept-core/theory/path";
9
+ import { pathDefault } from "./path.js";
10
+ import { event, refinePendingHomes } from "./event.js";
11
+ import { isAttemptOutcome } from "./outcomes.js";
12
+ import { activeDefaultRecords, completionNodeRef, electedObservations, assertDefaultRetraction, emptyNodeMemory, interpretationsDefault, isClaim, isDefaultObservation, isDemonstration, isRetrievalOpenerDemonstration, isTeaching, memoryDefault, stateDefault, DEFAULT_THEORY_REF, DEFAULT_PARAMETERS, } from "./state.js";
13
+ import { defaultNodeState, defaultQueryTokens, indicatorsDefault, isDefaultKnown, isDefaultReviewable, } from "./tags.js";
14
+ const nodeProperty = { type: "string", pattern: "^node-.+" };
15
+ const scopeProperties = { scope: { type: "array", items: nodeProperty } };
16
+ const surfaceProperty = { type: "string", pattern: "^surface-.+" };
17
+ const schema = (properties, required = []) => ({
18
+ type: "object",
19
+ properties,
20
+ required,
21
+ additionalProperties: false,
22
+ });
23
+ function object(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function nodeIdentity(value) {
27
+ return typeof value === "string" && /^node-.+/.test(value);
28
+ }
29
+ function args(raw, allowed, required = []) {
30
+ if (!object(raw))
31
+ throw new Error("Tool arguments must be an object");
32
+ if (Object.keys(raw).some((key) => !allowed.includes(key)))
33
+ throw new Error("Unknown tool argument");
34
+ if (required.some((key) => !(key in raw)))
35
+ throw new Error("Missing required tool argument");
36
+ return raw;
37
+ }
38
+ function nodeId(value) {
39
+ if (!nodeIdentity(value))
40
+ throw new Error("Expected a Node identity");
41
+ return value;
42
+ }
43
+ function nodes(value) {
44
+ if (!Array.isArray(value))
45
+ throw new Error("Expected Node identities");
46
+ return value.map(nodeId);
47
+ }
48
+ function observationId(value) {
49
+ if (!isObservationId(value))
50
+ throw new Error("Expected an observation identity");
51
+ return value;
52
+ }
53
+ function observationIds(value) {
54
+ if (!Array.isArray(value))
55
+ throw new Error("Expected observation identities");
56
+ return value.map(observationId);
57
+ }
58
+ function surfaceIdentity(value) {
59
+ return typeof value === "string" && /^surface-.+/.test(value);
60
+ }
61
+ function surfaceId(value) {
62
+ if (!surfaceIdentity(value))
63
+ throw new Error("Expected a surface identity");
64
+ return value;
65
+ }
66
+ function sourceHandle(source, support) {
67
+ if (!object(source))
68
+ return [];
69
+ if (source.kind === "observation" && isObservationId(source.observation))
70
+ return [{ support, kind: "observation", observation: source.observation }];
71
+ if (source.kind === "transcript" &&
72
+ surfaceIdentity(source.surface) &&
73
+ typeof source.from === "string" &&
74
+ typeof source.to === "string")
75
+ return [{ support, kind: "transcript", surface: source.surface, from: source.from, to: source.to }];
76
+ return [];
77
+ }
78
+ function interpretationSourceHandles(ctx, supportIds) {
79
+ return supportIds.flatMap((support) => {
80
+ const source = ctx.state.observations.find(({ id }) => id === support);
81
+ if (source !== undefined &&
82
+ object(source.payload) &&
83
+ source.payload.kind === "memory" &&
84
+ Array.isArray(source.payload.entries))
85
+ return source.payload.entries.flatMap((entry) => (object(entry) ? sourceHandle(entry.source, support) : []));
86
+ return [{ support, kind: "observation", observation: support }];
87
+ });
88
+ }
89
+ function validationIdentity(observations) {
90
+ const used = new Set(observations.map(({ id }) => id));
91
+ for (let attempt = 0;; attempt++) {
92
+ const id = `obs-interpretation-validation-${attempt}`;
93
+ if (isObservationId(id) && !used.has(id))
94
+ return id;
95
+ }
96
+ }
97
+ function string(value) {
98
+ if (typeof value !== "string")
99
+ throw new Error("Expected a string");
100
+ return value;
101
+ }
102
+ function strings(value) {
103
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string"))
104
+ throw new Error("Expected strings");
105
+ return value;
106
+ }
107
+ function nodesInScope(ctx, scope) {
108
+ if (scope?.some((id) => !ctx.graph.nodes.some((node) => node.id === id)))
109
+ throw new Error("Scope contains a missing Node");
110
+ return ctx.graph.nodes
111
+ .map(({ id }) => id)
112
+ .filter((id) => scope === undefined || scope.includes(id))
113
+ .sort();
114
+ }
115
+ function readingNodes(ctx, scope) {
116
+ const selected = nodesInScope(ctx, scope);
117
+ if (scope !== undefined || ctx.unscopedNodes === undefined)
118
+ return selected;
119
+ const defaultScope = new Set(ctx.unscopedNodes);
120
+ return selected.filter((id) => defaultScope.has(id));
121
+ }
122
+ function missionFacts(ctx, scope) {
123
+ const selected = new Set(nodesInScope(ctx, scope));
124
+ return (ctx.missions ?? []).filter(({ nodes }) => scope === undefined || nodes.some((id) => selected.has(id)));
125
+ }
126
+ function candidate(ctx, node) {
127
+ const state = defaultNodeState(ctx.state, node);
128
+ const missions = missionFacts(ctx).filter(({ nodes }) => nodes.includes(node));
129
+ return {
130
+ node,
131
+ label: state.label,
132
+ ...(state.lastSuccess === undefined ? {} : { lastSuccess: state.lastSuccess }),
133
+ missions: missions.map(({ id }) => id),
134
+ openSurfaces: (ctx.openSurfaces ?? []).filter(({ about }) => about.includes(node)).map(({ surface }) => surface),
135
+ citations: state.citations,
136
+ };
137
+ }
138
+ function trail(ctx, node) {
139
+ nodesInScope(ctx, [node]);
140
+ const state = defaultNodeState(ctx.state, node);
141
+ const rule = state.completion.query !== undefined
142
+ ? "completion-query"
143
+ : state.label === "demonstrated"
144
+ ? "demonstration-window"
145
+ : state.label === "probably-known"
146
+ ? "knows-claim-newer-than-failure"
147
+ : "no-qualifying-evidence";
148
+ return {
149
+ node,
150
+ state,
151
+ counts: state.completion.counts.map(({ k, required }) => k + " of " + required),
152
+ rule,
153
+ records: state.records.toReversed(),
154
+ citations: state.citations,
155
+ };
156
+ }
157
+ function pagedTrail(ctx, raw) {
158
+ const input = args(raw, ["node", "cursor", "limit"], ["node"]);
159
+ const node = nodeId(input.node);
160
+ const limit = input.limit ?? CATALOG_PAGE_SIZE;
161
+ if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit <= 0)
162
+ throw new Error("Trail limit must be a positive integer");
163
+ const reading = trail(ctx, node);
164
+ const revision = contentDigest({
165
+ node,
166
+ records: ctx.state.records.map(({ id }) => id),
167
+ order: reading.records.map(({ id }) => id),
168
+ });
169
+ let offset = 0;
170
+ if (input.cursor !== undefined) {
171
+ let cursor;
172
+ try {
173
+ cursor = JSON.parse(string(input.cursor));
174
+ }
175
+ catch {
176
+ throw new Error("Invalid trail cursor; restart theory.trail without a cursor");
177
+ }
178
+ if (!object(cursor) ||
179
+ cursor.node !== node ||
180
+ cursor.revision !== revision ||
181
+ typeof cursor.offset !== "number" ||
182
+ !Number.isSafeInteger(cursor.offset) ||
183
+ cursor.offset <= 0 ||
184
+ cursor.offset >= reading.records.length)
185
+ throw new Error("Stale or invalid trail cursor; restart theory.trail without a cursor");
186
+ offset = cursor.offset;
187
+ }
188
+ return projectTrailPage(reading, revision, offset, limit);
189
+ }
190
+ /** Pure projection shared by live reads and the one-off historical catalog migration. */
191
+ export function projectTrailPage(reading, revision, offset, limit) {
192
+ const node = reading.node;
193
+ const page = reading.records.slice(offset, offset + Math.min(limit, CATALOG_MAX_PAGE_SIZE));
194
+ const next = offset + page.length;
195
+ const { records: _records, ...standing } = reading.state;
196
+ return {
197
+ node,
198
+ rule: reading.rule,
199
+ standing,
200
+ page,
201
+ isDone: next >= reading.records.length,
202
+ continueCursor: next >= reading.records.length ? null : JSON.stringify({ node, revision, offset: next }),
203
+ };
204
+ }
205
+ function retractionCandidates(ctx, observations) {
206
+ const state = stateDefault(ctx.graph, observations, ctx.now);
207
+ return state.records
208
+ .filter((record) => record.surface === ctx.surface)
209
+ .map(({ id, nodes, payload }) => ({
210
+ id,
211
+ nodes: (payload.kind === "claim" ? state.homing.claims : state.homing.homes)[id] ??
212
+ nodes ??
213
+ (payload.kind === "demonstration" ? [payload.node.node] : []),
214
+ outcome: payload.kind === "demonstration" ? payload.outcome : payload.stance,
215
+ task: payload.kind === "demonstration" ? payload.task : (payload.prompt ?? payload.statement),
216
+ }));
217
+ }
218
+ function lessonCompletion(ctx) {
219
+ const lesson = ctx.lesson?.lesson ?? (ctx.entry?.kind === "lesson" ? ctx.entry.lesson : undefined);
220
+ if (ctx.mode !== "lesson" || lesson === undefined)
221
+ return undefined;
222
+ const nodes = lesson.nodes.map((node) => {
223
+ const completion = ctx.state.nodes[node]?.completion;
224
+ return {
225
+ node,
226
+ complete: completion?.complete ?? false,
227
+ query: completion?.query ?? "no completion set",
228
+ counts: completion?.counts ?? [],
229
+ needs: completion?.query === undefined
230
+ ? "Set pedagogy:completion with edit_metadata; without a completion query this Node cannot complete."
231
+ : completion.complete
232
+ ? "Completion query holds."
233
+ : "Evidence satisfying the completion query; counts below are current matches and required totals.",
234
+ };
235
+ });
236
+ const complete = nodes.every(({ complete }) => complete);
237
+ return {
238
+ complete,
239
+ status: complete
240
+ ? "This Lesson's completion queries hold; the host owns closure and the next Lesson."
241
+ : "This Lesson stays open; the next Lesson is not cleared for starting.",
242
+ nodes,
243
+ };
244
+ }
245
+ function closeRecount(ctx, rawPractising) {
246
+ const lesson = lessonCompletion(ctx);
247
+ if (lesson !== undefined)
248
+ throw new Error("close_recount is for Review. The host closes Lessons when every focus Node's pedagogy:completion query holds.\n" +
249
+ JSON.stringify(lesson));
250
+ const practising = rawPractising === undefined ? [] : rawPractising;
251
+ if (!Array.isArray(practising))
252
+ throw new Error("Expected practice directions");
253
+ const directions = practising.map((entry) => {
254
+ if (!object(entry) || Object.keys(entry).some((key) => key !== "node" && key !== "why"))
255
+ throw new Error("Expected practice directions with a Node and reason");
256
+ const node = nodeId(entry.node);
257
+ if (!ctx.graph.nodes.some((candidate) => candidate.id === node))
258
+ throw new Error("Missing Node " + node);
259
+ const why = string(entry.why).trim();
260
+ if (why === "")
261
+ throw new Error("A practice direction needs a reason");
262
+ return { node, why };
263
+ });
264
+ const labelByNode = new Map(projectVisualGraph({ graph: ctx.graph, annotations: {} }).nodes.map(({ id, label }) => [id, label]));
265
+ const labelOf = (node) => {
266
+ const label = labelByNode.get(node);
267
+ if (label === undefined)
268
+ throw new Error(`Missing display label for ${node}`);
269
+ return label;
270
+ };
271
+ const homes = (record) => (record.payload.kind === "claim" ? ctx.state.homing.claims : ctx.state.homing.homes)[record.id] ?? [];
272
+ const records = ctx.state.records
273
+ .filter((record) => record.surface === ctx.surface)
274
+ .map((record) => ({ record, about: homes(record).map(labelOf) }));
275
+ const nodes = new Set(ctx.about);
276
+ for (const { record } of records)
277
+ for (const node of homes(record))
278
+ nodes.add(node);
279
+ return {
280
+ capabilities: [...nodes]
281
+ .map((node) => ({ label: labelOf(node), standing: defaultNodeState(ctx.state, node).label }))
282
+ .sort((left, right) => left.label.localeCompare(right.label)),
283
+ recordsScope: "Conversational Records on this Session surface only. Material attempts have their own surfaces and are reported separately to the conversation; absence here does not mean unanswered.",
284
+ records: records.map(({ record, about }) => {
285
+ const association = about.length === 0 ? {} : { about };
286
+ const payload = record.payload;
287
+ return payload.kind === "claim"
288
+ ? {
289
+ ...association,
290
+ kind: payload.kind,
291
+ stance: payload.stance,
292
+ statement: payload.statement,
293
+ ...(payload.prompt === undefined ? {} : { prompt: payload.prompt }),
294
+ }
295
+ : {
296
+ ...association,
297
+ kind: payload.kind,
298
+ outcome: payload.outcome,
299
+ unaided: payload.unaided,
300
+ task: payload.task,
301
+ response: payload.response,
302
+ };
303
+ }),
304
+ practising: directions,
305
+ };
306
+ }
307
+ function nodeTool(name, description, run) {
308
+ return {
309
+ name,
310
+ description,
311
+ schema: schema({ node: nodeProperty }, ["node"]),
312
+ *run(raw, ctx) {
313
+ const node = nodeId(args(raw, ["node"], ["node"]).node);
314
+ nodesInScope(ctx, [node]);
315
+ return run(ctx, node);
316
+ },
317
+ };
318
+ }
319
+ function scopedTool(name, description, run) {
320
+ return {
321
+ name,
322
+ description,
323
+ schema: schema(scopeProperties),
324
+ *run(raw, ctx) {
325
+ const input = args(raw, ["scope"]);
326
+ const scope = input.scope === undefined ? undefined : nodes(input.scope);
327
+ nodesInScope(ctx, scope);
328
+ return run(ctx, scope);
329
+ },
330
+ };
331
+ }
332
+ /** Evidence readings, retrieval context and the Session's closing diagnosis. */
333
+ export const defaultInstrumentTools = [
334
+ scopedTool("frontier", "Reachable not-known Nodes, facts and citations; no ranking.", (ctx, scope) => {
335
+ const frontier = defaultQueryTokens.frontier(ctx.state, ctx.graph);
336
+ return readingNodes(ctx, scope)
337
+ .filter((id) => frontier.has(id))
338
+ .map((id) => ({
339
+ ...candidate(ctx, id),
340
+ prerequisites: ctx.graph.edges
341
+ .filter(({ to }) => to === id)
342
+ .map(({ from }) => ({
343
+ node: from,
344
+ label: defaultNodeState(ctx.state, from).label,
345
+ citations: defaultNodeState(ctx.state, from).citations,
346
+ })),
347
+ }));
348
+ }),
349
+ {
350
+ name: "route",
351
+ description: "Not-known prerequisite cone in dependency order.",
352
+ schema: schema({ target: nodeProperty }, ["target"]),
353
+ *run(raw, ctx) {
354
+ const target = nodeId(args(raw, ["target"], ["target"]).target);
355
+ const result = route(ctx.graph, target);
356
+ if (result.kind === "missing-target")
357
+ throw new Error(`Missing Node ${target}`);
358
+ return result.nodes
359
+ .filter(({ id }) => !isDefaultKnown(defaultNodeState(ctx.state, id)))
360
+ .map(({ id }) => candidate(ctx, id));
361
+ },
362
+ },
363
+ {
364
+ name: "interpretations",
365
+ description: "Retrieve current supported interpretations by optional tag, Node scope and originating surface. Defaults to this Session's attached Nodes; returns identity and source handles, never transcript text. Retrieve before reusing or correcting one.",
366
+ schema: schema({
367
+ tag: { type: "string" },
368
+ scope: { type: "array", items: nodeProperty },
369
+ surface: surfaceProperty,
370
+ }),
371
+ *run(raw, ctx) {
372
+ const input = args(raw, ["tag", "scope", "surface"]);
373
+ const scope = input.scope === undefined ? ctx.about : nodes(input.scope);
374
+ const selected = nodesInScope(ctx, scope);
375
+ const tag = input.tag === undefined ? undefined : string(input.tag);
376
+ const query = {
377
+ nodes: selected,
378
+ ...(tag === undefined ? {} : { tag }),
379
+ ...(input.surface === undefined ? {} : { surface: surfaceId(input.surface) }),
380
+ };
381
+ return interpretationsDefault(ctx.state, query).map(({ id, nodes: related = [], cites = [], surface, payload }) => ({
382
+ id,
383
+ text: payload.text,
384
+ tags: payload.tags,
385
+ nodes: related,
386
+ supportIds: cites,
387
+ sourceHandles: interpretationSourceHandles(ctx, cites),
388
+ ...(surface === undefined ? {} : { surface }),
389
+ }));
390
+ },
391
+ },
392
+ {
393
+ name: "trail",
394
+ schema: {
395
+ ...schema({
396
+ ...scopeProperties,
397
+ node: nodeProperty,
398
+ cursor: { type: "string" },
399
+ limit: { type: "integer", minimum: 1 },
400
+ }),
401
+ required: [],
402
+ // Exactly one of node or scope; a cursor with scope is refused at run. Zod's JSON Schema reader rejects `not`.
403
+ oneOf: [
404
+ { type: "object", properties: { node: nodeProperty }, required: ["node"], additionalProperties: true },
405
+ {
406
+ type: "object",
407
+ properties: { scope: scopeProperties.scope },
408
+ required: ["scope"],
409
+ additionalProperties: true,
410
+ },
411
+ ],
412
+ },
413
+ description: [
414
+ "Original records and the rule producing each Node's label. Pass node for one paged trail, or scope: [node, ...] for an array of independently paged trails. Follow each continueCursor with node and cursor, not scope. Limit applies per Node. The first qualifying rule applies:",
415
+ 'pedagogy:completion is a query on Node or tag metadata: all/any combine counts; {count, of} counts observations matching a predicate. Predicates support all, any, not, field/is and latest: {per: [fields], of: predicate}. Example: {count: 16, of: {all: [{latest: {per: ["material", "item"], of: {all: [{field: "node", is: "self"}, {field: "material", is: {playground: "quizzes", id: "set-verbs-1"}}, {field: "unaided", is: true}]}}}, {field: "outcome", is: "success"}]}}. Without node: self a query can count other Nodes too. playground projects a demonstration\'s material.playground or a report\'s Playground; kind distinguishes them. Reports also expose scope, state and current (not expired). Trail displays each count as k of required, the query and citations.',
416
+ "1. demonstrated: the Node query holds. A Node with no completion is never demonstrated. Aided attempts count only as practice unless the query selects them.",
417
+ "2. probably-known: an attached knows claim is newer than any failure on this Node.",
418
+ "3. unknown: otherwise. Only demonstrated and probably-known count as known for routing.",
419
+ "Retention is separate: the schedule replays the first unaided attempt per Node per UTC day as Good or Again. Unaided success also gives Good to direct prerequisites, at most once per day; failure never flows down. A diagnosed component regression supplies Again unless its slip is already recorded. An unresolved failure stays due for Review until an unaided success, independently of the forgetting curve. Claims start a short schedule without covering prerequisites. Review tags select ordinary acquired Nodes and scheduled completion-bound Nodes below the retention thresholds. Scheduled completion-bound Nodes remain eligible despite acquisition withdrawal; incomplete or expired reports do not supply Again.",
420
+ "A newer knows claim can follow failure; a later failure defeats that claim unless completion still holds.",
421
+ ].join("\n"),
422
+ *run(raw, ctx) {
423
+ const input = args(raw, ["node", "scope", "cursor", "limit"]);
424
+ if (input.scope === undefined)
425
+ return pagedTrail(ctx, raw);
426
+ if (input.node !== undefined || input.cursor !== undefined)
427
+ throw new Error("Trail scope cannot accompany node or cursor; follow each page with node and cursor");
428
+ return nodesInScope(ctx, nodes(input.scope)).map((node) => pagedTrail(ctx, { node, limit: input.limit }));
429
+ },
430
+ },
431
+ scopedTool("coverage", "Nodes with no records.", (ctx, scope) => readingNodes(ctx, scope)
432
+ .filter((id) => defaultNodeState(ctx.state, id).records.length === 0)
433
+ .map((id) => candidate(ctx, id))),
434
+ scopedTool("probes", "Claimed or due Nodes with acquisition and retention facts.", (ctx, scope) => readingNodes(ctx, scope).flatMap((id) => {
435
+ const state = defaultNodeState(ctx.state, id);
436
+ return state.label === "probably-known" ||
437
+ (isDefaultReviewable(state) &&
438
+ (state.schedule?.lapsed === true || (state.schedule?.retrievability ?? 1) < DEFAULT_PARAMETERS.retention.due))
439
+ ? [{ ...candidate(ctx, id), schedule: state.schedule, rule: trail(ctx, id).rule }]
440
+ : [];
441
+ })),
442
+ scopedTool("warnings", "Read all theory indicators and their evidence; nothing fires.", (ctx, scope) => {
443
+ const selected = new Set(nodesInScope(ctx, scope));
444
+ return indicatorsDefault(ctx.state, ctx.graph).filter(({ nodes }) => nodes.length === 0 || nodes.some((id) => selected.has(id)));
445
+ }),
446
+ nodeTool("items", "Patch Materials whose about includes this Node, with content references, inline text bodies when available, and contribution provenance.", (ctx, node) => ctx.graph.materials
447
+ .filter((material) => material.about.includes(node))
448
+ .map((material) => ({
449
+ material,
450
+ provenance: ctx.graph.provenance.materials[materialKey(material)] ?? [],
451
+ }))),
452
+ nodeTool("memory", "Opaque Node memory tail or summary with original Record citations.", (ctx, node) => {
453
+ const memory = ctx.state.memories[node] ?? emptyNodeMemory(node);
454
+ return {
455
+ ...memoryDefault(memory),
456
+ citations: [
457
+ ...new Set(memory.originals.flatMap(({ source }) => (source.kind === "observation" ? [source.observation] : []))),
458
+ ],
459
+ };
460
+ }),
461
+ scopedTool("mission", "Effective Missions, revisions and resolved scopes. Each run shows its active Session, open asides, recent past and next stops; the path shows numbered lesson sections, cleared stops and estimated minutes left. Checkpoints follow milestone Lessons and refine the next section.", (ctx, scope) => missionFacts(ctx, scope).map((mission) => ({
462
+ ...mission,
463
+ path: readMissionPath(pathDefault({
464
+ graph: ctx.graph,
465
+ targets: mission.targets ??
466
+ mission.nodes.filter((id) => !ctx.graph.edges.some((edge) => edge.from === id && mission.nodes.includes(edge.to))),
467
+ past: mission.run?.past ?? [],
468
+ ...(mission.run?.retired ? { retired: mission.run.retired } : {}),
469
+ now: ctx.now,
470
+ minutes: ctx.sessionMinutes ?? Number.POSITIVE_INFINITY,
471
+ projection: projectDefault(ctx.graph, ctx.state),
472
+ observations: ctx.state.observations,
473
+ activities: ctx.lessonActivities ?? [],
474
+ }), { progress: progressDefault, estimate: estimateDefault, prepareEstimate: prepareEstimateDefault }, {
475
+ graph: ctx.graph,
476
+ projection: projectDefault(ctx.graph, ctx.state),
477
+ observations: ctx.state.observations,
478
+ activities: ctx.lessonActivities ?? [],
479
+ }),
480
+ }))),
481
+ {
482
+ name: "close_recount",
483
+ description: "Learner-facing close material for this Session: display labels, current standing, and active conversational Records on this Session surface (not its Material surfaces). Material attempt notices are separate; absence here does not mean unanswered. Statements are verbatim. This presentation intentionally omits internal identities and Patch provenance; use it for the closing recount. Optionally prescribe practice on existing Nodes with a concise reason; this is a host presentation direction, not theory evidence.",
484
+ schema: schema({
485
+ practising: {
486
+ type: "array",
487
+ items: {
488
+ type: "object",
489
+ properties: { node: nodeProperty, why: { type: "string", minLength: 1 } },
490
+ required: ["node", "why"],
491
+ additionalProperties: false,
492
+ },
493
+ },
494
+ }),
495
+ *run(raw, ctx) {
496
+ const input = args(raw, ["practising"]);
497
+ const recount = closeRecount(ctx, input.practising);
498
+ if (ctx.entry?.kind === "review") {
499
+ const session = new Set(ctx.sessionObservations ?? []);
500
+ for (const node of ctx.entry.nodes) {
501
+ const verdict = ctx.state.nodes[node]?.records.findLast((record) => session.has(record.id) && isDemonstration(record.payload));
502
+ if (verdict === undefined ||
503
+ !isDemonstration(verdict.payload) ||
504
+ !verdict.payload.unaided ||
505
+ verdict.payload.outcome !== "success")
506
+ continue;
507
+ yield* write({
508
+ at: ctx.now,
509
+ surface: ctx.surface,
510
+ nodes: [node],
511
+ cites: [verdict.id],
512
+ payload: { kind: "review-pass", node: completionNodeRef(ctx.graph, node) },
513
+ });
514
+ }
515
+ }
516
+ return recount;
517
+ },
518
+ },
519
+ ];
520
+ /** Only theory evidence is written. The host assigns identity and attribution, not pedagogy. */
521
+ const recordDemonstration = {
522
+ name: "record_demonstration",
523
+ description: [
524
+ "Record one attempted posed check: a posed task with a determinable outcome and an attempt. Reading, explanation, a remark in passing, dialogue is not one. An explicit I don’t know response to a posed task is a dont-know demonstration; closing without answering is not.",
525
+ "Use it for a free response, a requested Artifact section, an observed step, or an explicitly posed conversational check. Preserve task and response verbatim; grade success/failure with grader tutor. For a lesson-opening retrieval prompt, use record_retrieval_opener instead.",
526
+ "Decide unaided when posing: the task must be at least as demanding as the Node's capability statement in every respect. Hints, candidates on a production capability, a missing required clock, or tools on a no-tool task make it aided. Help before outcome makes it aided; the completion after help is not a second attempt.",
527
+ "For an answer to a Material item, use record_material_attempt. A runner records its own outcome; correct a wrong runner grade with evaluation_override and a reason. An option's optional error string remains verbatim in the response.",
528
+ "Never infer prerequisite failures. Record a prerequisite only if its own posed step was attempted; the label query accounts for structural evidence.",
529
+ ].join(" "),
530
+ schema: schema({
531
+ node: nodeProperty,
532
+ outcome: { enum: ["success", "failure", "dont-know"] },
533
+ unaided: { type: "boolean" },
534
+ grader: { enum: ["mechanical", "tutor", "learner"] },
535
+ task: { type: "string" },
536
+ response: { type: "string" },
537
+ }, ["node", "outcome", "unaided", "grader"]),
538
+ *run(raw, ctx) {
539
+ const input = args(raw, ["node", "outcome", "unaided", "grader", "task", "response"], ["node", "outcome", "unaided", "grader"]);
540
+ const node = nodeId(input.node);
541
+ nodesInScope(ctx, [node]);
542
+ const payload = { ...input, kind: "demonstration", node: { node, provenance: ctx.graph.terminal } };
543
+ if (!isDemonstration(payload))
544
+ throw new Error("Invalid demonstration");
545
+ const observation = { at: ctx.now, about: [...ctx.about], nodes: [node], surface: ctx.surface, payload };
546
+ const id = yield* write(observation);
547
+ const lesson = ctx.mode === "lesson" && (ctx.lesson !== undefined || ctx.entry?.kind === "lesson")
548
+ ? lessonCompletion({ ...ctx, state: stateDefault(ctx.graph, yield* read.observations({}), ctx.now) })
549
+ : undefined;
550
+ return { observation: { ...observation, id }, citations: [id], ...(lesson === undefined ? {} : { lesson }) };
551
+ },
552
+ };
553
+ export const defaultRecordingTools = [
554
+ recordDemonstration,
555
+ {
556
+ name: "record_material_attempt",
557
+ description: "Record a learner's chat answer to an existing Material's item, on any host. Supply the Material's playground and id, stable item id, assessed Node, verbatim task and response, outcome and unaided status fixed when posing (help makes it aided). The tutor grades success/failure; an explicit I don't know is dont-know. Ordinary conversational checks use record_demonstration. An identical retry returns its existing Record; a later different answer is a new attempt. A runner's outcome stays the record; correct a wrong grade with evaluation_override and a reason.",
558
+ schema: schema({
559
+ material: schema({ playground: { type: "string", minLength: 1 }, id: { type: "string", minLength: 1 } }, [
560
+ "playground",
561
+ "id",
562
+ ]),
563
+ node: nodeProperty,
564
+ item: { type: "string", minLength: 1 },
565
+ task: { type: "string", minLength: 1 },
566
+ response: { type: "string" },
567
+ outcome: { enum: ["success", "failure", "dont-know"] },
568
+ unaided: { type: "boolean" },
569
+ }, ["material", "node", "item", "task", "response", "outcome", "unaided"]),
570
+ *run(raw, ctx) {
571
+ const fields = ["material", "node", "item", "task", "response", "outcome", "unaided"];
572
+ const input = args(raw, fields, fields);
573
+ const rawIdentity = args(input.material, ["playground", "id"], ["playground", "id"]);
574
+ const identity = { playground: string(rawIdentity.playground), id: string(rawIdentity.id) };
575
+ const node = nodeId(input.node);
576
+ const item = string(input.item);
577
+ const task = string(input.task);
578
+ const response = string(input.response);
579
+ if (!item.trim() || !task.trim() || typeof input.unaided !== "boolean")
580
+ throw new Error("Supply an item, posed task and unaided status");
581
+ if (input.outcome !== "success" && input.outcome !== "failure" && input.outcome !== "dont-know")
582
+ throw new Error("Invalid Material attempt outcome");
583
+ const observations = yield* read.observations();
584
+ const session = new Set(ctx.sessionObservations ?? []);
585
+ const existing = effectiveObservations(electedObservations(observations), ctx.now).filter((observation) => isDefaultObservation(observation) &&
586
+ (observation.surface === ctx.surface || session.has(observation.id)) &&
587
+ isDemonstration(observation.payload) &&
588
+ observation.payload.material?.playground === identity.playground &&
589
+ observation.payload.material.id === identity.id &&
590
+ observation.payload.item === item &&
591
+ // Material surfaces belong to runners; a chat retry repeats the recorded Node, task and response, so a regrade of it stays an override.
592
+ (observation.surface !== ctx.surface ||
593
+ (observation.payload.node.node === node &&
594
+ observation.payload.task === task &&
595
+ observation.payload.response === response)));
596
+ if (existing.length)
597
+ return {
598
+ alreadyRecorded: true,
599
+ records: existing.map(({ id }) => id),
600
+ correction: "Use evaluation_override with the Record identity, corrected outcome and reason.",
601
+ };
602
+ // Inline runner Materials need not belong to the Patch; their captured Records above suffice.
603
+ const material = ctx.graph.materials.find((candidate) => candidate.playground === identity.playground && candidate.id === identity.id);
604
+ if (material === undefined)
605
+ throw new Error("Expected an existing Material");
606
+ if (!material.about.includes(node))
607
+ throw new Error("Node is outside the Material's scope");
608
+ const problem = {
609
+ id: item,
610
+ about: [node],
611
+ prompt: task,
612
+ answer: { kind: "text" },
613
+ grader: { by: "tutor" },
614
+ };
615
+ const payload = {
616
+ kind: "attempt",
617
+ problem: { ...problem, digest: contentDigest(problem) },
618
+ response,
619
+ assessment: {
620
+ correct: input.outcome === "success",
621
+ grader: input.outcome === "dont-know" ? "learner" : "tutor",
622
+ ...(input.unaided ? {} : { aided: true }),
623
+ ...(input.outcome === "dont-know" ? { dontKnow: true } : {}),
624
+ },
625
+ revision: ctx.graph.terminal,
626
+ };
627
+ if (!isAttemptOutcome(payload))
628
+ throw new Error("Invalid Material attempt");
629
+ yield* event({
630
+ kind: "outcome",
631
+ material: { playground: material.playground, id: material.id },
632
+ at: ctx.now,
633
+ surface: ctx.surface,
634
+ about: [node],
635
+ payload,
636
+ }, ctx);
637
+ const before = new Set(observations.map(({ id }) => id));
638
+ const after = yield* read.observations();
639
+ const records = after.filter(({ id }) => !before.has(id));
640
+ const lesson = lessonCompletion({ ...ctx, state: stateDefault(ctx.graph, after, ctx.now) });
641
+ return {
642
+ observations: records,
643
+ citations: records.map(({ id }) => id),
644
+ ...(lesson === undefined ? {} : { lesson }),
645
+ };
646
+ },
647
+ },
648
+ {
649
+ name: "record_retrieval_opener",
650
+ description: "Record the learner's actual attempted answer to a posed conversational retrieval prompt at the opening of a lesson. Use only for that explicit lesson-opening check, never for a Quiz, Review, Material outcome, or generic demonstration.",
651
+ schema: schema({
652
+ node: nodeProperty,
653
+ outcome: { enum: ["success", "failure", "dont-know"] },
654
+ unaided: { type: "boolean" },
655
+ grader: { enum: ["mechanical", "tutor", "learner"] },
656
+ task: { type: "string" },
657
+ response: { type: "string" },
658
+ }, ["node", "outcome", "unaided", "grader", "task", "response"]),
659
+ *run(raw, ctx) {
660
+ const input = args(raw, ["node", "outcome", "unaided", "grader", "task", "response"], ["node", "outcome", "unaided", "grader", "task", "response"]);
661
+ const node = nodeId(input.node);
662
+ nodesInScope(ctx, [node]);
663
+ const payload = {
664
+ ...input,
665
+ kind: "demonstration",
666
+ recording: "retrieval-opener",
667
+ node: { node, provenance: ctx.graph.terminal },
668
+ };
669
+ if (!isRetrievalOpenerDemonstration(payload))
670
+ throw new Error("Invalid retrieval opener demonstration");
671
+ const observation = { at: ctx.now, about: [...ctx.about], nodes: [node], surface: ctx.surface, payload };
672
+ const id = yield* write(observation);
673
+ return { observation: { ...observation, id }, citations: [id] };
674
+ },
675
+ },
676
+ {
677
+ name: "record_teaching",
678
+ description: [
679
+ "Record one explicit teaching act for a scoped Node after you have actually explained its content to the learner, with a worked example or equivalent reasoning.",
680
+ "Do not call on Skill entry, scope, reading, practice, an unrelated explanation, or merely creating/opening a Material. For a Document, accepted presentation of its opened surface records the occurrence instead.",
681
+ "Copy a substantial passage of the explanation you just delivered, including its worked step; this is not competence evidence.",
682
+ ].join(" "),
683
+ schema: schema({
684
+ node: nodeProperty,
685
+ explanation: { type: "string", minLength: 40 },
686
+ }, ["node", "explanation"]),
687
+ *run(raw, ctx) {
688
+ const input = args(raw, ["node", "explanation"], ["node", "explanation"]);
689
+ const node = nodeId(input.node);
690
+ nodesInScope(ctx, [node]);
691
+ const payload = {
692
+ kind: "teaching",
693
+ node: { node, provenance: ctx.graph.terminal },
694
+ explanation: string(input.explanation),
695
+ };
696
+ if (!isTeaching(payload))
697
+ throw new Error("Teaching needs an actual explanation");
698
+ const observation = { at: ctx.now, about: [...ctx.about], nodes: [node], surface: ctx.surface, payload };
699
+ const id = yield* write(observation);
700
+ return { observation: { ...observation, id }, citations: [id] };
701
+ },
702
+ },
703
+ {
704
+ name: "record_claim",
705
+ description: "Record a competence self-report: the learner's verbatim statement, optional eliciting prompt, and knows, forgotten, or unfamiliar. It names no Node at write; claims are attached by content, not Edges. Preferences are not claims.",
706
+ schema: schema({
707
+ statement: { type: "string" },
708
+ prompt: { type: "string" },
709
+ stance: { enum: ["knows", "forgotten", "unfamiliar"] },
710
+ }, ["statement", "stance"]),
711
+ *run(raw, ctx) {
712
+ const input = args(raw, ["statement", "prompt", "stance"], ["statement", "stance"]);
713
+ const payload = { ...input, kind: "claim" };
714
+ if (!isClaim(payload))
715
+ throw new Error("Invalid claim");
716
+ const observation = { at: ctx.now, about: [...ctx.about], surface: ctx.surface, payload };
717
+ const id = yield* write(observation);
718
+ return { observation: { ...observation, id }, citations: [id] };
719
+ },
720
+ },
721
+ {
722
+ name: "record_retraction",
723
+ description: "Correct evidence by retracting an existing demonstration or claim; never rewrite a Record. Pass either of (an exact Record id) or node (the latest active Record on that Node in this Session). Never retract a retraction or platform record.",
724
+ schema: {
725
+ ...schema({ of: { type: "string", pattern: "^obs-.+" }, node: nodeProperty }),
726
+ oneOf: [
727
+ { type: "object", properties: { of: { type: "string" } }, required: ["of"], additionalProperties: true },
728
+ { type: "object", properties: { node: nodeProperty }, required: ["node"], additionalProperties: true },
729
+ ],
730
+ },
731
+ *run(raw, ctx) {
732
+ const input = args(raw, ["of", "node"]);
733
+ if ((input.of === undefined) === (input.node === undefined))
734
+ throw new Error("Pass exactly one of of (Record id) or node (latest active Record in this Session)");
735
+ const supplied = yield* read.observations({});
736
+ const observations = effectiveObservations(electedObservations(supplied), ctx.now);
737
+ let of;
738
+ if (input.of !== undefined) {
739
+ of = observationId(input.of);
740
+ if (!supplied.some(({ id }) => id === of))
741
+ throw new Error(`Unknown Record id: ${of}. Retry record_retraction with an exact id from this Session's active Records (of), or their Node (node): ${JSON.stringify(retractionCandidates(ctx, supplied))}`);
742
+ }
743
+ else {
744
+ const node = nodeId(input.node);
745
+ nodesInScope(ctx, [node]);
746
+ const latest = retractionCandidates(ctx, supplied).findLast((record) => record.nodes.includes(node));
747
+ if (latest === undefined)
748
+ throw new Error(`No active demonstration or claim on ${node} in this Session`);
749
+ of = latest.id;
750
+ }
751
+ assertDefaultRetraction(of, observations);
752
+ const observation = {
753
+ at: ctx.now,
754
+ about: [...ctx.about],
755
+ surface: ctx.surface,
756
+ cites: [of],
757
+ payload: { kind: "retraction", of },
758
+ };
759
+ const id = yield* write(observation);
760
+ return { observation: { ...observation, id }, citations: [id, of] };
761
+ },
762
+ },
763
+ {
764
+ name: "correct_interpretation",
765
+ description: "Correct one current interpretation in the Session's attached Nodes (or explicit scope) by writing a replacement with fresh current support. Its predecessor remains in history; this does not change learner labels or Records.",
766
+ schema: schema({
767
+ of: { type: "string", pattern: "^obs-.+" },
768
+ text: { type: "string" },
769
+ tags: { type: "array", items: { type: "string" } },
770
+ support: { type: "array", items: { type: "string", pattern: "^obs-.+" } },
771
+ scope: { type: "array", items: nodeProperty },
772
+ }, ["of", "text", "tags", "support"]),
773
+ *run(raw, ctx) {
774
+ const input = args(raw, ["of", "text", "tags", "support", "scope"], ["of", "text", "tags", "support"]);
775
+ const of = observationId(input.of);
776
+ const text = string(input.text);
777
+ const tags = strings(input.tags);
778
+ const support = observationIds(input.support);
779
+ if (text.trim() === "")
780
+ throw new Error("An interpretation needs text");
781
+ if (tags.some((tag) => tag === "" || tag !== tag.trim().toLowerCase()) || new Set(tags).size !== tags.length)
782
+ throw new Error("Interpretation tags must be canonical and unique");
783
+ if (support.length === 0 || new Set(support).size !== support.length)
784
+ throw new Error("Correction requires unique support identities");
785
+ const scope = nodesInScope(ctx, input.scope === undefined ? ctx.about : nodes(input.scope));
786
+ const supplied = yield* read.observations({});
787
+ const freshState = stateDefault(ctx.graph, supplied, ctx.now);
788
+ const target = interpretationsDefault(freshState, { nodes: scope }).find(({ id }) => id === of);
789
+ if (target === undefined)
790
+ throw new Error("Correction requires a current interpretation in the selected Node scope");
791
+ const interpretationNodes = target.nodes ?? [];
792
+ const payload = { kind: "interpretation", text, tags };
793
+ const observation = {
794
+ at: ctx.now,
795
+ about: [...ctx.about],
796
+ nodes: interpretationNodes,
797
+ cites: support,
798
+ surface: target.surface,
799
+ supersedes: target.id,
800
+ payload,
801
+ };
802
+ const probe = {
803
+ ...observation,
804
+ id: validationIdentity(supplied),
805
+ by: DEFAULT_THEORY_REF,
806
+ };
807
+ const valid = stateDefault(ctx.graph, [...supplied, probe], ctx.now).interpretations.some(({ id }) => id === probe.id);
808
+ if (!valid)
809
+ throw new Error("Correction support must be current evidence related to the interpretation's Nodes");
810
+ const id = yield* write(observation);
811
+ return { observation: { ...observation, id }, citations: [id, ...support] };
812
+ },
813
+ },
814
+ ];
815
+ /** Claim-homing and system-revision tools: no revision fences, cache saves, journals or retry contracts in Core. */
816
+ export const defaultBackgroundTools = [
817
+ {
818
+ name: "attach_claim",
819
+ description: [
820
+ "Attach an active claim to current Nodes by their capability statements, never by topic or Edges. An empty nodes list explicitly leaves it homeless.",
821
+ "After a charting Confirmation that adds Nodes, and at close before close_recount: call warnings and inspect its homeless citations; re-home each current-Session claim you can identify from its citation and conversation to the Node(s) whose capability statements match, and leave unmatched existing claims as they are.",
822
+ "Attach a newly recorded claim directly; it is not reported as homeless until explicitly attached. Use nodes: [] only when no current Node fits.",
823
+ ].join(" "),
824
+ schema: schema({
825
+ record: { type: "string", pattern: "^obs-.+" },
826
+ nodes: { type: "array", items: nodeProperty, uniqueItems: true },
827
+ }, ["record", "nodes"]),
828
+ *run(raw, ctx) {
829
+ const input = args(raw, ["record", "nodes"], ["record", "nodes"]);
830
+ const of = observationId(input.record);
831
+ const homes = nodes(input.nodes);
832
+ nodesInScope(ctx, homes);
833
+ if (new Set(homes).size !== homes.length)
834
+ throw new Error("Claim attachment requires distinct current Nodes");
835
+ const observations = effectiveObservations(electedObservations(yield* read.observations({})), ctx.now);
836
+ const claim = activeDefaultRecords(observations).find(({ id }) => id === of);
837
+ if (claim?.payload.kind !== "claim")
838
+ throw new Error("Attachment requires an active default claim");
839
+ const observation = {
840
+ at: ctx.now,
841
+ about: [...ctx.about],
842
+ surface: ctx.surface,
843
+ nodes: homes,
844
+ cites: [of],
845
+ payload: { kind: "homing", of, homes, revision: ctx.graph.terminal },
846
+ };
847
+ const id = yield* write(observation);
848
+ return { observation: { ...observation, id }, citations: [id, of] };
849
+ },
850
+ },
851
+ {
852
+ name: "refine_records",
853
+ description: "Re-home pending demonstrations by verbatim task text after a Patch edit, preserve claim homes, and attach all current Record strings to Node memory. No new evidence is inferred.",
854
+ schema: schema({}),
855
+ *run(raw, ctx) {
856
+ args(raw, []);
857
+ const observations = yield* read.observations({});
858
+ yield* refinePendingHomes({ ...ctx, state: stateDefault(ctx.graph, observations, ctx.now) });
859
+ },
860
+ },
861
+ ];
862
+ /** Keyed scoring retains the selected option's error verbatim; skips never call this. */
863
+ export function keyedDemonstration(input) {
864
+ const { option, ...attempt } = input;
865
+ return {
866
+ ...attempt,
867
+ kind: "demonstration",
868
+ grader: "mechanical",
869
+ outcome: option.correct ? "success" : "failure",
870
+ response: option.error === undefined ? input.response : `${input.response}\n${option.error}`,
871
+ };
872
+ }