@mmon-co/ncept-default-theory 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.md +73 -2
- package/dist/catalog-contract.d.ts +102 -0
- package/dist/catalog-contract.js +75 -0
- package/dist/catalog.d.ts +14 -0
- package/dist/catalog.js +164 -0
- package/dist/chat.d.ts +171 -0
- package/dist/chat.js +232 -0
- package/dist/completion.d.ts +74 -0
- package/dist/completion.js +277 -0
- package/dist/dependent-cone.d.ts +3 -0
- package/dist/dependent-cone.js +26 -0
- package/dist/diagnosis.d.ts +9 -0
- package/dist/diagnosis.js +1 -0
- package/dist/diagnostics.d.ts +25 -0
- package/dist/diagnostics.js +34 -0
- package/dist/evaluation.d.ts +33 -0
- package/dist/evaluation.js +376 -0
- package/dist/event.d.ts +7 -0
- package/dist/event.js +405 -0
- package/dist/history.d.ts +4 -0
- package/dist/history.js +61 -0
- package/dist/implementation.d.ts +184 -0
- package/dist/implementation.js +31 -0
- package/dist/index.d.ts +200 -0
- package/dist/index.js +27 -0
- package/dist/messages.d.ts +167 -0
- package/dist/messages.js +56 -0
- package/dist/opening.d.ts +20 -0
- package/dist/opening.js +33 -0
- package/dist/outcomes.d.ts +143 -0
- package/dist/outcomes.js +323 -0
- package/dist/path.d.ts +19 -0
- package/dist/path.js +293 -0
- package/dist/reading.d.ts +12 -0
- package/dist/reading.js +75 -0
- package/dist/release.d.ts +1 -0
- package/dist/release.js +1 -0
- package/dist/roleplay.d.ts +17 -0
- package/dist/roleplay.js +2 -0
- package/dist/skills/sources.d.ts +12 -0
- package/dist/skills/sources.js +13 -0
- package/dist/skills.d.ts +12 -0
- package/dist/skills.js +70 -0
- package/dist/state.d.ts +316 -0
- package/dist/state.js +1309 -0
- package/dist/tags.d.ts +34 -0
- package/dist/tags.js +306 -0
- package/dist/timing.d.ts +21 -0
- package/dist/timing.js +79 -0
- package/dist/tools.d.ts +394 -0
- package/dist/tools.js +872 -0
- package/package.json +52 -4
package/dist/state.js
ADDED
|
@@ -0,0 +1,1309 @@
|
|
|
1
|
+
import { createEmptyCard, forgetting_curve, fsrs, generatorParameters, Rating } from "ts-fsrs";
|
|
2
|
+
import { readTheoryState } from "@mmon-co/ncept-core/theory";
|
|
3
|
+
import { dependentCones } from "./dependent-cone.js";
|
|
4
|
+
import { COMPLETION_PROPERTY, compileCompletion, completionBoundary, prepareCompletionHistory, } from "./completion.js";
|
|
5
|
+
import { exactPatchRefKey, lastMetadataContribution, metadataSetsForEntity, NODE_CRITERION_PROPERTY, sameExactPatchRef, } from "@mmon-co/ncept-core/patch";
|
|
6
|
+
import { compareObservations, isObservationId, isObservationTimestamp, } from "@mmon-co/ncept-core/observations";
|
|
7
|
+
export const DEFAULT_THEORY_ID = "default";
|
|
8
|
+
export const DEFAULT_THEORY_REF = { theory: DEFAULT_THEORY_ID, version: "1.0.0" };
|
|
9
|
+
function object(value) {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
function nonempty(value) {
|
|
13
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
14
|
+
}
|
|
15
|
+
function isNodeRef(value) {
|
|
16
|
+
return (object(value) && typeof value.node === "string" && /^node-.+/.test(value.node) && isExactReference(value.provenance));
|
|
17
|
+
}
|
|
18
|
+
function isExactReference(value) {
|
|
19
|
+
return (object(value) &&
|
|
20
|
+
typeof value.identity === "string" &&
|
|
21
|
+
/^patch-.+/.test(value.identity) &&
|
|
22
|
+
typeof value.digest === "string" &&
|
|
23
|
+
/^sha256:[a-f0-9]{64}$/.test(value.digest));
|
|
24
|
+
}
|
|
25
|
+
function isCompletionScope(value) {
|
|
26
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
27
|
+
return true;
|
|
28
|
+
if (typeof value === "number")
|
|
29
|
+
return Number.isFinite(value);
|
|
30
|
+
if (Array.isArray(value))
|
|
31
|
+
return value.every(isCompletionScope);
|
|
32
|
+
return object(value) && Object.values(value).every(isCompletionScope);
|
|
33
|
+
}
|
|
34
|
+
export function isCompletionOutcome(value) {
|
|
35
|
+
return (object(value) &&
|
|
36
|
+
value.kind === "completion" &&
|
|
37
|
+
isNodeRef(value.node) &&
|
|
38
|
+
nonempty(value.playground) &&
|
|
39
|
+
"scope" in value &&
|
|
40
|
+
isCompletionScope(value.scope) &&
|
|
41
|
+
(value.state === "complete" || value.state === "incomplete") &&
|
|
42
|
+
(value.validUntil === undefined || isObservationTimestamp(value.validUntil)));
|
|
43
|
+
}
|
|
44
|
+
export function isDemonstration(value) {
|
|
45
|
+
return (object(value) &&
|
|
46
|
+
value.kind === "demonstration" &&
|
|
47
|
+
(value.material === undefined ||
|
|
48
|
+
(object(value.material) && nonempty(value.material.playground) && nonempty(value.material.id))) &&
|
|
49
|
+
(value.item === undefined || nonempty(value.item)) &&
|
|
50
|
+
isNodeRef(value.node) &&
|
|
51
|
+
(value.outcome === "success" || value.outcome === "failure" || value.outcome === "dont-know") &&
|
|
52
|
+
typeof value.unaided === "boolean" &&
|
|
53
|
+
(value.grader === "mechanical" ||
|
|
54
|
+
value.grader === "tutor" ||
|
|
55
|
+
value.grader === "learner" ||
|
|
56
|
+
value.grader === "decision") &&
|
|
57
|
+
typeof value.task === "string" &&
|
|
58
|
+
typeof value.response === "string" &&
|
|
59
|
+
(value.recording === undefined || value.recording === "retrieval-opener"));
|
|
60
|
+
}
|
|
61
|
+
export function isLapse(value) {
|
|
62
|
+
return (object(value) &&
|
|
63
|
+
value.kind === "lapse" &&
|
|
64
|
+
isNodeRef(value.node) &&
|
|
65
|
+
(value.of === undefined || isObservationId(value.of)));
|
|
66
|
+
}
|
|
67
|
+
export function isGrade(value) {
|
|
68
|
+
if (!object(value) || value.kind !== "grade" || !isNodeRef(value.node) || !object(value.day))
|
|
69
|
+
return false;
|
|
70
|
+
return (nonempty(value.day.id) &&
|
|
71
|
+
isObservationTimestamp(value.day.start) &&
|
|
72
|
+
isObservationTimestamp(value.day.end) &&
|
|
73
|
+
Date.parse(value.day.start) < Date.parse(value.day.end) &&
|
|
74
|
+
typeof value.rating === "string" &&
|
|
75
|
+
["Again", "Hard", "Good", "Easy"].includes(value.rating));
|
|
76
|
+
}
|
|
77
|
+
export function isReviewPass(value) {
|
|
78
|
+
return object(value) && value.kind === "review-pass" && isNodeRef(value.node);
|
|
79
|
+
}
|
|
80
|
+
export function isRetrievalOpenerDemonstration(value) {
|
|
81
|
+
return isDemonstration(value) && value.recording === "retrieval-opener";
|
|
82
|
+
}
|
|
83
|
+
export function isFeatureUse(value) {
|
|
84
|
+
return (object(value) && value.kind === "feature-use" && typeof value.operation === "string" && value.operation.length > 0);
|
|
85
|
+
}
|
|
86
|
+
export function isTeaching(value) {
|
|
87
|
+
return (object(value) &&
|
|
88
|
+
value.kind === "teaching" &&
|
|
89
|
+
isNodeRef(value.node) &&
|
|
90
|
+
typeof value.explanation === "string" &&
|
|
91
|
+
value.explanation.trim().length >= 40);
|
|
92
|
+
}
|
|
93
|
+
export function isClaim(value) {
|
|
94
|
+
return (object(value) &&
|
|
95
|
+
value.kind === "claim" &&
|
|
96
|
+
typeof value.statement === "string" &&
|
|
97
|
+
(value.prompt === undefined || typeof value.prompt === "string") &&
|
|
98
|
+
(value.stance === "knows" || value.stance === "forgotten" || value.stance === "unfamiliar"));
|
|
99
|
+
}
|
|
100
|
+
export function isRetraction(value) {
|
|
101
|
+
return object(value) && value.kind === "retraction" && isObservationId(value.of);
|
|
102
|
+
}
|
|
103
|
+
export function isHoming(value) {
|
|
104
|
+
return (object(value) &&
|
|
105
|
+
value.kind === "homing" &&
|
|
106
|
+
isObservationId(value.of) &&
|
|
107
|
+
Array.isArray(value.homes) &&
|
|
108
|
+
value.homes.every((node) => typeof node === "string" && /^node-.+/.test(node)) &&
|
|
109
|
+
new Set(value.homes).size === value.homes.length &&
|
|
110
|
+
isExactReference(value.revision) &&
|
|
111
|
+
(value.pending === undefined || typeof value.pending === "boolean"));
|
|
112
|
+
}
|
|
113
|
+
function isSpeaker(value) {
|
|
114
|
+
return (object(value) &&
|
|
115
|
+
(value.kind === "learner" ||
|
|
116
|
+
value.kind === "tutor" ||
|
|
117
|
+
(value.kind === "material" && typeof value.source === "string" && typeof value.ref === "string")));
|
|
118
|
+
}
|
|
119
|
+
export function isMemory(value) {
|
|
120
|
+
return (object(value) &&
|
|
121
|
+
value.kind === "memory" &&
|
|
122
|
+
Array.isArray(value.entries) &&
|
|
123
|
+
value.entries.every((entry) => object(entry) &&
|
|
124
|
+
typeof entry.text === "string" &&
|
|
125
|
+
isSpeaker(entry.speaker) &&
|
|
126
|
+
isObservationTimestamp(entry.at) &&
|
|
127
|
+
object(entry.source) &&
|
|
128
|
+
(entry.source.kind === "observation"
|
|
129
|
+
? isObservationId(entry.source.observation)
|
|
130
|
+
: entry.source.kind === "transcript" &&
|
|
131
|
+
typeof entry.source.surface === "string" &&
|
|
132
|
+
typeof entry.source.from === "string" &&
|
|
133
|
+
typeof entry.source.to === "string")));
|
|
134
|
+
}
|
|
135
|
+
/** Canonical tags are trimmed, lowercase, nonempty and unique. */
|
|
136
|
+
function isInterpretation(value) {
|
|
137
|
+
return (object(value) &&
|
|
138
|
+
value.kind === "interpretation" &&
|
|
139
|
+
typeof value.text === "string" &&
|
|
140
|
+
value.text.trim() !== "" &&
|
|
141
|
+
Array.isArray(value.tags) &&
|
|
142
|
+
value.tags.every((tag) => typeof tag === "string" && tag !== "" && tag === tag.trim().toLowerCase()) &&
|
|
143
|
+
new Set(value.tags).size === value.tags.length);
|
|
144
|
+
}
|
|
145
|
+
function isSummary(value) {
|
|
146
|
+
if (!object(value))
|
|
147
|
+
return false;
|
|
148
|
+
const { sources, dependencies } = value;
|
|
149
|
+
const dependencyIds = new Set(Array.isArray(dependencies) ? dependencies : []);
|
|
150
|
+
return (value.kind === "memory-summary" &&
|
|
151
|
+
typeof value.text === "string" &&
|
|
152
|
+
Array.isArray(value.materialSources) &&
|
|
153
|
+
value.materialSources.every((speaker) => isSpeaker(speaker) && speaker.kind === "material") &&
|
|
154
|
+
Array.isArray(sources) &&
|
|
155
|
+
sources.every(isObservationId) &&
|
|
156
|
+
Array.isArray(dependencies) &&
|
|
157
|
+
dependencies.every(isObservationId) &&
|
|
158
|
+
sources.every((source) => dependencyIds.has(source)));
|
|
159
|
+
}
|
|
160
|
+
export function isDefaultObservation(observation) {
|
|
161
|
+
return observation.by !== "platform" && observation.by.theory === DEFAULT_THEORY_ID;
|
|
162
|
+
}
|
|
163
|
+
/** Closed default payload vocabulary, not a legacy schema registry or foreign conversion mechanism. */
|
|
164
|
+
function assertDefaultPayload(payload) {
|
|
165
|
+
if (!object(payload))
|
|
166
|
+
return;
|
|
167
|
+
let valid = true;
|
|
168
|
+
switch (payload.kind) {
|
|
169
|
+
case "completion":
|
|
170
|
+
valid = isCompletionOutcome(payload);
|
|
171
|
+
break;
|
|
172
|
+
case "demonstration":
|
|
173
|
+
valid = isDemonstration(payload);
|
|
174
|
+
break;
|
|
175
|
+
case "lapse":
|
|
176
|
+
valid = isLapse(payload);
|
|
177
|
+
break;
|
|
178
|
+
case "grade":
|
|
179
|
+
valid = isGrade(payload);
|
|
180
|
+
break;
|
|
181
|
+
case "review-pass":
|
|
182
|
+
valid = isReviewPass(payload);
|
|
183
|
+
break;
|
|
184
|
+
case "feature-use":
|
|
185
|
+
valid = isFeatureUse(payload);
|
|
186
|
+
break;
|
|
187
|
+
case "teaching":
|
|
188
|
+
valid = isTeaching(payload);
|
|
189
|
+
break;
|
|
190
|
+
case "claim":
|
|
191
|
+
valid = isClaim(payload);
|
|
192
|
+
break;
|
|
193
|
+
case "retraction":
|
|
194
|
+
valid = isRetraction(payload);
|
|
195
|
+
break;
|
|
196
|
+
case "homing":
|
|
197
|
+
valid = isHoming(payload);
|
|
198
|
+
break;
|
|
199
|
+
case "memory":
|
|
200
|
+
valid = isMemory(payload);
|
|
201
|
+
break;
|
|
202
|
+
case "memory-summary":
|
|
203
|
+
valid = isSummary(payload);
|
|
204
|
+
break;
|
|
205
|
+
case "interpretation":
|
|
206
|
+
valid = isInterpretation(payload);
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
if (!valid)
|
|
210
|
+
throw new Error(`Invalid default ${String(payload.kind)} payload`);
|
|
211
|
+
}
|
|
212
|
+
/** Retractions never retract retractions. Excluded sources do not make residual interpretations into evidence.
|
|
213
|
+
* Records rank by the instant the learner produced them, deterministically, which is a different question
|
|
214
|
+
* from the order observations were accepted in: decisions and memory read the supplied sequence instead.
|
|
215
|
+
*/
|
|
216
|
+
export function activeDefaultRecords(observations) {
|
|
217
|
+
return indexDefaultRecords(observations).records;
|
|
218
|
+
}
|
|
219
|
+
function indexDefaultRecords(observations) {
|
|
220
|
+
const own = observations.filter(isDefaultObservation);
|
|
221
|
+
for (const observation of own)
|
|
222
|
+
assertDefaultPayload(observation.payload);
|
|
223
|
+
const byId = new Map();
|
|
224
|
+
for (const observation of own)
|
|
225
|
+
if (!byId.has(observation.id))
|
|
226
|
+
byId.set(observation.id, observation);
|
|
227
|
+
const retracted = new Set();
|
|
228
|
+
for (const observation of own) {
|
|
229
|
+
if (!isRetraction(observation.payload))
|
|
230
|
+
continue;
|
|
231
|
+
const of = observation.payload.of;
|
|
232
|
+
const target = byId.get(of);
|
|
233
|
+
if (target === undefined)
|
|
234
|
+
continue; // The host may have excluded the source from effective evidence.
|
|
235
|
+
if (!isDemonstration(target.payload) && !isClaim(target.payload))
|
|
236
|
+
throw new Error("Default retractions must target a demonstration or claim");
|
|
237
|
+
retracted.add(target.id);
|
|
238
|
+
}
|
|
239
|
+
const records = own
|
|
240
|
+
.filter((observation) => !retracted.has(observation.id) && (isDemonstration(observation.payload) || isClaim(observation.payload)))
|
|
241
|
+
.sort(compareObservations);
|
|
242
|
+
return { records, retracted };
|
|
243
|
+
}
|
|
244
|
+
export function assertDefaultRetraction(of, observations) {
|
|
245
|
+
if (!activeDefaultRecords(observations).some(({ id }) => id === of))
|
|
246
|
+
throw new Error("Retraction requires an active default demonstration or claim");
|
|
247
|
+
}
|
|
248
|
+
/** Whole-day support uses the same active, re-homed demonstrations as acquisition.
|
|
249
|
+
* Diagnoses are retention evidence only; retracted attempts never support a grade. */
|
|
250
|
+
export function nodeDayEvidence(state, node) {
|
|
251
|
+
const attempts = state.records.flatMap((record) => record.payload.kind === "demonstration" &&
|
|
252
|
+
record.payload.unaided &&
|
|
253
|
+
(state.homing.homes[record.id] ?? record.nodes ?? [record.payload.node.node]).includes(node)
|
|
254
|
+
? [{ ...record, payload: record.payload }]
|
|
255
|
+
: []);
|
|
256
|
+
return [
|
|
257
|
+
...attempts,
|
|
258
|
+
...state.observations.flatMap((record) => isDefaultObservation(record) && isLapse(record.payload) && record.payload.node.node === node
|
|
259
|
+
? [{ ...record, payload: record.payload }]
|
|
260
|
+
: []),
|
|
261
|
+
].sort(compareObservations);
|
|
262
|
+
}
|
|
263
|
+
/** A grade stops being active if any cited attempt is retracted, abandoned or superseded.
|
|
264
|
+
* It never becomes acquisition/completion evidence. The scheduler consumes this projection. */
|
|
265
|
+
export function activeDefaultGrades(state) {
|
|
266
|
+
const grades = new Map();
|
|
267
|
+
for (const record of state.observations)
|
|
268
|
+
if (isDefaultObservation(record) && isGrade(record.payload))
|
|
269
|
+
append(grades, record.payload.node.node, { ...record, payload: record.payload });
|
|
270
|
+
return [...grades].flatMap(([node, records]) => activeNodeGrades(records, nodeDayEvidence(state, node)));
|
|
271
|
+
}
|
|
272
|
+
function activeNodeGrades(grades, evidence) {
|
|
273
|
+
const seen = new Set();
|
|
274
|
+
return grades.filter((record) => {
|
|
275
|
+
const { payload } = record;
|
|
276
|
+
const interval = JSON.stringify([payload.day.start, payload.day.end]);
|
|
277
|
+
if (seen.has(interval))
|
|
278
|
+
throw new Error("Duplicate default Node-day grade");
|
|
279
|
+
seen.add(interval);
|
|
280
|
+
const active = new Set(evidence
|
|
281
|
+
.filter(({ at }) => Date.parse(at) >= Date.parse(payload.day.start) && Date.parse(at) < Date.parse(payload.day.end))
|
|
282
|
+
.map(({ id }) => id));
|
|
283
|
+
if (record.nodes?.length !== 1 ||
|
|
284
|
+
record.nodes[0] !== payload.node.node ||
|
|
285
|
+
!record.cites?.length ||
|
|
286
|
+
new Set(record.cites).size !== record.cites.length)
|
|
287
|
+
throw new Error("Grade requires its Node scope and unique evidence citations");
|
|
288
|
+
return record.cites.every((id) => active.has(id));
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
/** Original strings stay citable; a summary is only usable while all its original sources remain effective. */
|
|
292
|
+
export function expandNodeMemory(memory, summary) {
|
|
293
|
+
return memory.originals.filter(({ observation }) => summary.sources.includes(observation));
|
|
294
|
+
}
|
|
295
|
+
export function memoryDefault(memory) {
|
|
296
|
+
return {
|
|
297
|
+
node: memory.node,
|
|
298
|
+
entries: memory.entries,
|
|
299
|
+
...(memory.entries.some(({ kind }) => kind === "entry") ? { marker: "unsummarized activity exists" } : {}),
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
export function emptyNodeMemory(node) {
|
|
303
|
+
return { node, entries: [], originals: [] };
|
|
304
|
+
}
|
|
305
|
+
export function homingCandidates(graph) {
|
|
306
|
+
return graph.nodes.map(({ id }) => {
|
|
307
|
+
const contributions = metadataSetsForEntity(graph, { kind: "node", id }).flatMap((set) => {
|
|
308
|
+
const value = set.properties[NODE_CRITERION_PROPERTY];
|
|
309
|
+
if (value === undefined)
|
|
310
|
+
return [];
|
|
311
|
+
const source = graph.provenance.metadataProperties[set.id]?.[NODE_CRITERION_PROPERTY]?.at(-1);
|
|
312
|
+
if (typeof value !== "string" || source === undefined)
|
|
313
|
+
throw new Error(`Invalid capability statement for ${id}`);
|
|
314
|
+
return [{ value, source }];
|
|
315
|
+
});
|
|
316
|
+
const statement = lastMetadataContribution(graph, contributions)?.value;
|
|
317
|
+
if (statement === undefined)
|
|
318
|
+
throw new Error(`Missing capability statement for ${id}`);
|
|
319
|
+
return { node: id, statement };
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
/** Provisional interpretations for a graph edit: the target revision restates every decision in force. */
|
|
323
|
+
export function projectGraphChange(state, graph, next, successors = {}) {
|
|
324
|
+
const nextIds = new Set(next.nodes.map(({ id }) => id));
|
|
325
|
+
for (const [node, targets] of Object.entries(successors)) {
|
|
326
|
+
if (!graph.nodes.some(({ id }) => id === node) || next.nodes.some(({ id }) => id === node))
|
|
327
|
+
throw new Error(`Successor declaration requires a removed Node: ${node}`);
|
|
328
|
+
if (targets?.some((id) => !nextIds.has(id)))
|
|
329
|
+
throw new Error(`Successor declaration for ${node} targets a missing Node`);
|
|
330
|
+
}
|
|
331
|
+
const sourceIds = new Set(graph.nodes.map(({ id }) => id));
|
|
332
|
+
const moved = !sameExactPatchRef(graph.terminal, next.terminal);
|
|
333
|
+
return state.records.flatMap((record) => {
|
|
334
|
+
const claim = record.payload.kind === "claim";
|
|
335
|
+
const decided = (claim ? state.homing.claims : state.homing.homes)[record.id];
|
|
336
|
+
const intrinsic = record.nodes ?? (record.payload.kind === "demonstration" ? [record.payload.node.node] : []);
|
|
337
|
+
const previous = (decided ?? intrinsic).filter((node) => sourceIds.has(node));
|
|
338
|
+
const removed = previous.some((node) => !nextIds.has(node));
|
|
339
|
+
const retryHomeless = record.payload.kind === "demonstration" &&
|
|
340
|
+
previous.length === 0 &&
|
|
341
|
+
!nextIds.has(record.payload.node.node) &&
|
|
342
|
+
moved;
|
|
343
|
+
const unresolved = removed || retryHomeless || state.homing.pending.includes(record.id);
|
|
344
|
+
// A decision in force is restated for the new revision, which is the only thing that governs there.
|
|
345
|
+
// Pending survives the restatement even where the decided homes are the record's own; a carried
|
|
346
|
+
// decision does not become pending work.
|
|
347
|
+
if (!unresolved && !(decided !== undefined && moved))
|
|
348
|
+
return [];
|
|
349
|
+
const homes = [
|
|
350
|
+
...new Set(previous.flatMap((node) => (nextIds.has(node) ? [node] : claim ? [] : (successors[node] ?? [])))),
|
|
351
|
+
];
|
|
352
|
+
return [
|
|
353
|
+
{
|
|
354
|
+
kind: "homing",
|
|
355
|
+
of: record.id,
|
|
356
|
+
homes,
|
|
357
|
+
revision: next.terminal,
|
|
358
|
+
...(!claim && unresolved ? { pending: true } : {}),
|
|
359
|
+
},
|
|
360
|
+
];
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
export const DEFAULT_PARAMETERS = {
|
|
364
|
+
retention: { due: 0.9, fading: 0.7, claimStabilityDays: 1 },
|
|
365
|
+
};
|
|
366
|
+
const DAY_MS = 86_400_000;
|
|
367
|
+
/** Daily reviews have no learning steps; disabling fuzz keeps replay deterministic. */
|
|
368
|
+
const SCHEDULER = fsrs(generatorParameters({ enable_fuzz: false, enable_short_term: false }));
|
|
369
|
+
/** The latest tentative competence report, newer than any actual failure. */
|
|
370
|
+
function knowsClaim(records) {
|
|
371
|
+
const latest = records.findLast((record) => record.payload.kind === "claim");
|
|
372
|
+
const failure = records.findLast(({ payload }) => payload.kind === "demonstration" && payload.outcome !== "success");
|
|
373
|
+
return latest?.payload.stance === "knows" && (failure === undefined || Date.parse(latest.at) > Date.parse(failure.at))
|
|
374
|
+
? latest
|
|
375
|
+
: undefined;
|
|
376
|
+
}
|
|
377
|
+
/** Acquisition reads only this Node's own active, time-ordered evidence, without a horizon. */
|
|
378
|
+
export function labelDefaultNode(input) {
|
|
379
|
+
const { records } = input;
|
|
380
|
+
const demonstrations = records.filter((record) => record.payload.kind === "demonstration");
|
|
381
|
+
const successes = demonstrations.filter(({ payload }) => payload.unaided && payload.outcome === "success");
|
|
382
|
+
const lastSuccess = successes.at(-1);
|
|
383
|
+
const knows = knowsClaim(records) !== undefined;
|
|
384
|
+
const completion = input.completion ?? { complete: false, counts: [], citations: [] };
|
|
385
|
+
const label = completion.complete ? "demonstrated" : knows ? "probably-known" : "unknown";
|
|
386
|
+
return {
|
|
387
|
+
featureUses: [],
|
|
388
|
+
label,
|
|
389
|
+
completion,
|
|
390
|
+
...(lastSuccess === undefined ? {} : { lastSuccess: lastSuccess.at }),
|
|
391
|
+
aidedPractice: demonstrations.filter(({ payload }) => !payload.unaided).length,
|
|
392
|
+
citations: [...new Set([...records.map(({ id }) => id), ...completion.citations])],
|
|
393
|
+
records,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/** Accepted whole-day grades are the only direct FSRS reviews. Ungraded direct days also
|
|
397
|
+
* suppress implicit credit. Core uses host boundaries, never a clock-zone or UTC-day fallback. */
|
|
398
|
+
function scheduleDefaultNode(records, implicit, lapses, grades, parameters) {
|
|
399
|
+
const direct = [
|
|
400
|
+
...records.flatMap((record) => record.payload.kind === "demonstration" && record.payload.unaided ? [{ ...record, payload: record.payload }] : []),
|
|
401
|
+
...lapses,
|
|
402
|
+
];
|
|
403
|
+
const accepted = activeNodeGrades(grades, direct);
|
|
404
|
+
const directDays = new Set(direct.flatMap(({ learnerDay }) => (learnerDay === undefined ? [] : [learnerDay.id])));
|
|
405
|
+
const credit = implicit.filter(({ learnerDay }) => learnerDay !== undefined && !directDays.has(learnerDay.id));
|
|
406
|
+
const claims = records.filter((record) => record.payload.kind === "claim");
|
|
407
|
+
let card;
|
|
408
|
+
let reviewDay;
|
|
409
|
+
let initializingClaim;
|
|
410
|
+
let lapsed = false;
|
|
411
|
+
const citations = [];
|
|
412
|
+
for (const record of [...claims, ...credit, ...accepted].sort(compareObservations)) {
|
|
413
|
+
const { payload, at, id } = record;
|
|
414
|
+
if (payload.kind === "claim") {
|
|
415
|
+
if (payload.stance !== "knows" || card !== undefined)
|
|
416
|
+
continue;
|
|
417
|
+
card = {
|
|
418
|
+
...SCHEDULER.next(createEmptyCard(at), at, Rating.Good).card,
|
|
419
|
+
stability: parameters.retention.claimStabilityDays,
|
|
420
|
+
reps: 0,
|
|
421
|
+
};
|
|
422
|
+
initializingClaim = at;
|
|
423
|
+
}
|
|
424
|
+
else if (payload.kind === "grade") {
|
|
425
|
+
const earlierSuccess = (initializingClaim !== undefined && Date.parse(initializingClaim) < Date.parse(payload.day.start)) ||
|
|
426
|
+
direct.some(({ at, payload: evidence }) => evidence.kind === "demonstration" &&
|
|
427
|
+
evidence.outcome === "success" &&
|
|
428
|
+
Date.parse(at) < Date.parse(payload.day.start));
|
|
429
|
+
card = SCHEDULER.next(card ?? createEmptyCard(payload.day.end), payload.day.end, Rating[payload.rating]).card;
|
|
430
|
+
lapsed = payload.rating === "Again" && earlierSuccess;
|
|
431
|
+
citations.push(...(record.cites ?? []));
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
const day = record.learnerDay;
|
|
435
|
+
if (day === undefined || day.id === reviewDay)
|
|
436
|
+
continue;
|
|
437
|
+
card = SCHEDULER.next(card ?? createEmptyCard(at), at, Rating.Good).card;
|
|
438
|
+
reviewDay = day.id;
|
|
439
|
+
}
|
|
440
|
+
citations.push(id);
|
|
441
|
+
}
|
|
442
|
+
if (card?.last_review === undefined)
|
|
443
|
+
return undefined;
|
|
444
|
+
return {
|
|
445
|
+
stability: card.stability,
|
|
446
|
+
difficulty: card.difficulty,
|
|
447
|
+
reps: card.reps,
|
|
448
|
+
lapses: card.lapses,
|
|
449
|
+
lastReview: card.last_review.toISOString(),
|
|
450
|
+
lapsed,
|
|
451
|
+
citations: [...new Set(citations)],
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
/** Resolved Node and tag metadata share the ordinary Patch precedence. */
|
|
455
|
+
export function defaultNodeCompletion(graph, node, index) {
|
|
456
|
+
const value = lastMetadataContribution(graph, (index === undefined
|
|
457
|
+
? metadataSetsForEntity(graph, { kind: "node", id: node })
|
|
458
|
+
: (index.metadata.get(node) ?? [])).flatMap((set) => {
|
|
459
|
+
if (!(COMPLETION_PROPERTY in set.properties))
|
|
460
|
+
return [];
|
|
461
|
+
const source = graph.provenance.metadataProperties[set.id]?.[COMPLETION_PROPERTY]?.at(-1);
|
|
462
|
+
if (source === undefined)
|
|
463
|
+
throw new Error(`Missing completion provenance for ${node}`);
|
|
464
|
+
return [{ value: set.properties[COMPLETION_PROPERTY], source }];
|
|
465
|
+
}), index?.patchOrder)?.value;
|
|
466
|
+
// The revision-minting boundary validates this theory-owned metadata shape.
|
|
467
|
+
// eslint-disable-next-line typescript/consistent-type-assertions
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
/** Stable authoring provenance, rather than the terminal of an unrelated graph edit. */
|
|
471
|
+
export function completionNodeRef(graph, node, nodeIds) {
|
|
472
|
+
const provenance = graph.provenance.nodes[node]?.at(-1)?.patch;
|
|
473
|
+
if (!provenance || !(nodeIds?.has(node) ?? graph.nodes.some(({ id }) => id === node)))
|
|
474
|
+
throw new Error(`Unknown completion Node ${node}`);
|
|
475
|
+
return { node, provenance };
|
|
476
|
+
}
|
|
477
|
+
/** Graph edges point from prerequisite to dependent; the strict cone excludes the queried Node. */
|
|
478
|
+
export function defaultDependentCone(graph, node) {
|
|
479
|
+
return dependentCones(graph)(node);
|
|
480
|
+
}
|
|
481
|
+
function append(index, key, value) {
|
|
482
|
+
const values = index.get(key);
|
|
483
|
+
if (values === undefined)
|
|
484
|
+
index.set(key, [value]);
|
|
485
|
+
else
|
|
486
|
+
values.push(value);
|
|
487
|
+
}
|
|
488
|
+
function indexDefaultGraph(graph) {
|
|
489
|
+
const nodeOrder = new Map(graph.nodes.map(({ id }, index) => [id, index]));
|
|
490
|
+
const dependents = new Map();
|
|
491
|
+
const prerequisites = new Map();
|
|
492
|
+
for (const { from, to } of graph.edges) {
|
|
493
|
+
append(dependents, from, to);
|
|
494
|
+
append(prerequisites, to, from);
|
|
495
|
+
}
|
|
496
|
+
const tags = new Map();
|
|
497
|
+
for (const tag of graph.tags)
|
|
498
|
+
if (!tags.has(tag.name))
|
|
499
|
+
tags.set(tag.name, tag.nodes);
|
|
500
|
+
const metadata = new Map();
|
|
501
|
+
for (const set of graph.metadataSets) {
|
|
502
|
+
if (!(COMPLETION_PROPERTY in set.properties))
|
|
503
|
+
continue;
|
|
504
|
+
const nodes = new Set();
|
|
505
|
+
for (const subject of set.subjects) {
|
|
506
|
+
if (subject.kind === "node")
|
|
507
|
+
nodes.add(subject.id);
|
|
508
|
+
else if (subject.kind === "tag")
|
|
509
|
+
for (const node of tags.get(subject.name) ?? [])
|
|
510
|
+
nodes.add(node);
|
|
511
|
+
}
|
|
512
|
+
for (const node of nodes)
|
|
513
|
+
append(metadata, node, set);
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
nodeIds: new Set(nodeOrder.keys()),
|
|
517
|
+
nodeOrder,
|
|
518
|
+
dependents,
|
|
519
|
+
prerequisites,
|
|
520
|
+
metadata,
|
|
521
|
+
patchOrder: new Map(graph.patchOrder.map((ref, index) => [exactPatchRefKey(ref), index])),
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
function initialHomes(record) {
|
|
525
|
+
return record.nodes ?? (record.payload.kind === "demonstration" ? [record.payload.node.node] : []);
|
|
526
|
+
}
|
|
527
|
+
function indexed(value) {
|
|
528
|
+
if (value === undefined)
|
|
529
|
+
throw new Error("Missing indexed default evidence");
|
|
530
|
+
return value;
|
|
531
|
+
}
|
|
532
|
+
/** Two heaps partition elected evidence at the last read instant. A clock tick only touches crossed
|
|
533
|
+
* boundaries, even when acceptance times arrive out of order; backwards reads move the same entries back. */
|
|
534
|
+
function evidenceClock(direction) {
|
|
535
|
+
const entries = [];
|
|
536
|
+
const earlier = (left, right) => direction * (left.time - right.time) < 0;
|
|
537
|
+
return {
|
|
538
|
+
peek: () => entries[0],
|
|
539
|
+
push(entry) {
|
|
540
|
+
let index = entries.length;
|
|
541
|
+
entries.push(entry);
|
|
542
|
+
while (index > 0) {
|
|
543
|
+
const parent = (index - 1) >>> 1;
|
|
544
|
+
if (!earlier(entry, indexed(entries[parent])))
|
|
545
|
+
break;
|
|
546
|
+
entries[index] = indexed(entries[parent]);
|
|
547
|
+
index = parent;
|
|
548
|
+
}
|
|
549
|
+
entries[index] = entry;
|
|
550
|
+
},
|
|
551
|
+
pop() {
|
|
552
|
+
const first = indexed(entries[0]);
|
|
553
|
+
const last = indexed(entries.pop());
|
|
554
|
+
if (entries.length > 0) {
|
|
555
|
+
let index = 0;
|
|
556
|
+
while (index * 2 + 1 < entries.length) {
|
|
557
|
+
let child = index * 2 + 1;
|
|
558
|
+
if (child + 1 < entries.length && earlier(indexed(entries[child + 1]), indexed(entries[child])))
|
|
559
|
+
child++;
|
|
560
|
+
if (!earlier(indexed(entries[child]), last))
|
|
561
|
+
break;
|
|
562
|
+
entries[index] = indexed(entries[child]);
|
|
563
|
+
index = child;
|
|
564
|
+
}
|
|
565
|
+
entries[index] = last;
|
|
566
|
+
}
|
|
567
|
+
return first;
|
|
568
|
+
},
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function changeBucket(buckets, key, position, value, add) {
|
|
572
|
+
let bucket = buckets.get(key);
|
|
573
|
+
if (add) {
|
|
574
|
+
if (bucket === undefined)
|
|
575
|
+
buckets.set(key, (bucket = new Map()));
|
|
576
|
+
bucket.set(position, value);
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
bucket?.delete(position);
|
|
580
|
+
if (bucket?.size === 0)
|
|
581
|
+
buckets.delete(key);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function bucketValues(bucket) {
|
|
585
|
+
return [...(bucket ?? [])].sort(([left], [right]) => left - right).map(([, value]) => value);
|
|
586
|
+
}
|
|
587
|
+
function firstEntry(entries) {
|
|
588
|
+
let first;
|
|
589
|
+
for (const entry of entries)
|
|
590
|
+
if (first === undefined || entry.position < first.position)
|
|
591
|
+
first = entry;
|
|
592
|
+
return first;
|
|
593
|
+
}
|
|
594
|
+
function isRecord(observation) {
|
|
595
|
+
return isDefaultObservation(observation) && (isDemonstration(observation.payload) || isClaim(observation.payload));
|
|
596
|
+
}
|
|
597
|
+
function isInterpretationObservation(observation) {
|
|
598
|
+
return isDefaultObservation(observation) && isInterpretation(observation.payload);
|
|
599
|
+
}
|
|
600
|
+
/** Shared cold/retained preparation. The host resets this closure for graph or annotation replacements.
|
|
601
|
+
* Supersession counts include ALL present elected observations, including superseded corrections.
|
|
602
|
+
* Retractions only exclude Records; their sources remain available to ordinary memory attachments.
|
|
603
|
+
*/
|
|
604
|
+
function initDefaultEvidence(graph) {
|
|
605
|
+
const graphIndex = indexDefaultGraph(graph);
|
|
606
|
+
let suppliedCount = 0;
|
|
607
|
+
const byId = new Map();
|
|
608
|
+
const future = evidenceClock(1);
|
|
609
|
+
const past = evidenceClock(-1);
|
|
610
|
+
let pending = [];
|
|
611
|
+
let invalidTimestamp;
|
|
612
|
+
const superseded = new Map();
|
|
613
|
+
const effective = new Set();
|
|
614
|
+
const own = new Map();
|
|
615
|
+
const retractions = new Map();
|
|
616
|
+
const decisions = new Map();
|
|
617
|
+
const invalidPayloads = new Map();
|
|
618
|
+
const invalidRetractions = new Set();
|
|
619
|
+
const corrections = new Map();
|
|
620
|
+
const invalidCorrections = new Set();
|
|
621
|
+
const invalidScopes = new Set();
|
|
622
|
+
const supported = new Map();
|
|
623
|
+
const interpretationUsers = new Map();
|
|
624
|
+
const memoryUsers = new Map();
|
|
625
|
+
const lapseEntries = new Map();
|
|
626
|
+
const gradeEntries = new Map();
|
|
627
|
+
const reviewPassEntries = new Map();
|
|
628
|
+
const featureEntries = new Map();
|
|
629
|
+
const memoryEntries = new Map();
|
|
630
|
+
const summaryEntries = new Map();
|
|
631
|
+
const completions = new Map();
|
|
632
|
+
const index = {
|
|
633
|
+
firstById: new Map(),
|
|
634
|
+
positions: new Map(),
|
|
635
|
+
memoryPlacements: new Map(),
|
|
636
|
+
lapses: new Map(),
|
|
637
|
+
grades: new Map(),
|
|
638
|
+
reviewPasses: new Map(),
|
|
639
|
+
featureUses: new Map(),
|
|
640
|
+
memories: new Map(),
|
|
641
|
+
summaries: new Map(),
|
|
642
|
+
transcriptMemories: new Map(),
|
|
643
|
+
};
|
|
644
|
+
const placements = new Map();
|
|
645
|
+
const placementByRecord = new Map();
|
|
646
|
+
const homedEntries = new Map();
|
|
647
|
+
const current = new Map();
|
|
648
|
+
const placed = new Map();
|
|
649
|
+
const homed = {};
|
|
650
|
+
const memories = {};
|
|
651
|
+
const dirtyRecords = new Set();
|
|
652
|
+
const dirtySources = new Set();
|
|
653
|
+
const dirtyNodes = new Set(graphIndex.nodeIds);
|
|
654
|
+
const dirtyMemories = new Set(graphIndex.nodeIds);
|
|
655
|
+
const dirtyAux = new Set();
|
|
656
|
+
const dirtyInterpretations = new Set();
|
|
657
|
+
let observationsChanged = true;
|
|
658
|
+
let recordsChanged = true;
|
|
659
|
+
let historyChanged = true;
|
|
660
|
+
let prepared;
|
|
661
|
+
const correctionValid = (entry) => {
|
|
662
|
+
const target = entry.observation.supersedes === undefined ? undefined : byId.get(entry.observation.supersedes)?.[0];
|
|
663
|
+
if (target !== undefined &&
|
|
664
|
+
(target.position >= entry.position ||
|
|
665
|
+
!isDefaultObservation(target.observation) ||
|
|
666
|
+
!isInterpretation(target.observation.payload)))
|
|
667
|
+
invalidCorrections.add(entry);
|
|
668
|
+
else
|
|
669
|
+
invalidCorrections.delete(entry);
|
|
670
|
+
};
|
|
671
|
+
function step(observations) {
|
|
672
|
+
for (const observation of observations) {
|
|
673
|
+
const entry = {
|
|
674
|
+
observation,
|
|
675
|
+
position: suppliedCount++,
|
|
676
|
+
time: Date.parse(observation.at),
|
|
677
|
+
present: false,
|
|
678
|
+
effective: false,
|
|
679
|
+
};
|
|
680
|
+
append(byId, observation.id, entry);
|
|
681
|
+
pending.push(entry);
|
|
682
|
+
if (observation.standing !== "abandoned" && !isObservationTimestamp(observation.at))
|
|
683
|
+
invalidTimestamp ??= entry;
|
|
684
|
+
// Correction validity is about the supplied sequence, even for abandoned/future corrections.
|
|
685
|
+
if (isDefaultObservation(observation) && isInterpretation(observation.payload)) {
|
|
686
|
+
if (observation.supersedes !== undefined) {
|
|
687
|
+
changeBucket(corrections, observation.supersedes, entry.position, entry, true);
|
|
688
|
+
correctionValid(entry);
|
|
689
|
+
}
|
|
690
|
+
for (const source of observation.cites ?? []) {
|
|
691
|
+
let users = interpretationUsers.get(source);
|
|
692
|
+
if (users === undefined)
|
|
693
|
+
interpretationUsers.set(source, (users = new Set()));
|
|
694
|
+
users.add(entry);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
for (const user of corrections.get(observation.id)?.values() ?? [])
|
|
698
|
+
correctionValid(user);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function changeEffective(entry, add) {
|
|
702
|
+
const observation = entry.observation;
|
|
703
|
+
if (add)
|
|
704
|
+
effective.add(entry);
|
|
705
|
+
else
|
|
706
|
+
effective.delete(entry);
|
|
707
|
+
entry.effective = add;
|
|
708
|
+
observationsChanged = true;
|
|
709
|
+
dirtySources.add(observation.id);
|
|
710
|
+
dirtyRecords.add(observation.id);
|
|
711
|
+
if (!isDefaultObservation(observation))
|
|
712
|
+
return;
|
|
713
|
+
changeBucket(own, observation.id, entry.position, entry, add);
|
|
714
|
+
invalidPayloads.delete(entry);
|
|
715
|
+
if (add) {
|
|
716
|
+
try {
|
|
717
|
+
assertDefaultPayload(observation.payload);
|
|
718
|
+
}
|
|
719
|
+
catch (error) {
|
|
720
|
+
if (!(error instanceof Error))
|
|
721
|
+
throw error;
|
|
722
|
+
invalidPayloads.set(entry, error);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const payload = observation.payload;
|
|
726
|
+
const sources = isMemory(payload)
|
|
727
|
+
? payload.entries.flatMap(({ source }) => (source.kind === "observation" ? [source.observation] : []))
|
|
728
|
+
: isSummary(payload)
|
|
729
|
+
? [...payload.sources, ...payload.dependencies]
|
|
730
|
+
: [];
|
|
731
|
+
for (const source of sources)
|
|
732
|
+
changeBucket(memoryUsers, source, entry.position, observation.nodes ?? [], add);
|
|
733
|
+
if (isRetraction(payload)) {
|
|
734
|
+
changeBucket(retractions, payload.of, entry.position, entry, add);
|
|
735
|
+
invalidRetractions.delete(entry);
|
|
736
|
+
dirtyRecords.add(payload.of);
|
|
737
|
+
}
|
|
738
|
+
else if (isHoming(payload)) {
|
|
739
|
+
changeBucket(decisions, payload.of, entry.position, entry, add);
|
|
740
|
+
dirtyRecords.add(payload.of);
|
|
741
|
+
}
|
|
742
|
+
else if (isLapse(payload)) {
|
|
743
|
+
changeBucket(lapseEntries, payload.node.node, entry.position, { ...observation, payload }, add);
|
|
744
|
+
dirtyAux.add(payload.node.node);
|
|
745
|
+
}
|
|
746
|
+
else if (isGrade(payload)) {
|
|
747
|
+
changeBucket(gradeEntries, payload.node.node, entry.position, { ...observation, payload }, add);
|
|
748
|
+
dirtyAux.add(payload.node.node);
|
|
749
|
+
}
|
|
750
|
+
else if (isReviewPass(payload)) {
|
|
751
|
+
changeBucket(reviewPassEntries, payload.node.node, entry.position, { ...observation, payload }, add);
|
|
752
|
+
dirtyAux.add(payload.node.node);
|
|
753
|
+
}
|
|
754
|
+
else if (isFeatureUse(payload)) {
|
|
755
|
+
for (const node of new Set(observation.nodes)) {
|
|
756
|
+
changeBucket(featureEntries, node, entry.position, { ...observation, payload }, add);
|
|
757
|
+
dirtyAux.add(node);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
else if (isMemory(payload)) {
|
|
761
|
+
for (const node of new Set(observation.nodes)) {
|
|
762
|
+
changeBucket(memoryEntries, node, entry.position, { ...observation, payload }, add);
|
|
763
|
+
dirtyAux.add(node);
|
|
764
|
+
dirtyMemories.add(node);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
else if (isSummary(payload)) {
|
|
768
|
+
for (const node of new Set(observation.nodes)) {
|
|
769
|
+
changeBucket(summaryEntries, node, entry.position, { ...observation, payload }, add);
|
|
770
|
+
dirtyAux.add(node);
|
|
771
|
+
dirtyMemories.add(node);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
else if (isCompletionOutcome(payload)) {
|
|
775
|
+
if (add)
|
|
776
|
+
completions.set(entry.position, { ...observation, payload });
|
|
777
|
+
else
|
|
778
|
+
completions.delete(entry.position);
|
|
779
|
+
historyChanged = true;
|
|
780
|
+
}
|
|
781
|
+
else if (isInterpretation(payload)) {
|
|
782
|
+
invalidScopes.delete(entry);
|
|
783
|
+
if (add &&
|
|
784
|
+
((observation.nodes?.length ?? 0) === 0 ||
|
|
785
|
+
(observation.cites?.length ?? 0) === 0 ||
|
|
786
|
+
new Set(observation.cites).size !== observation.cites?.length))
|
|
787
|
+
invalidScopes.add(entry);
|
|
788
|
+
dirtyInterpretations.add(entry);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
function placeRecord(id) {
|
|
792
|
+
const previous = placements.get(id) ?? [];
|
|
793
|
+
const previousPlaced = placed.get(id) ?? [];
|
|
794
|
+
const previousMemory = index.memoryPlacements.get(id);
|
|
795
|
+
const previousHomes = new Map();
|
|
796
|
+
const nextHomes = new Map();
|
|
797
|
+
for (const { position, record, present } of previous) {
|
|
798
|
+
placementByRecord.delete(record);
|
|
799
|
+
for (const node of present) {
|
|
800
|
+
changeBucket(homedEntries, node, position, record, false);
|
|
801
|
+
append(previousHomes, node, record);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
const entries = bucketValues(own.get(id));
|
|
805
|
+
const target = entries[0]?.observation;
|
|
806
|
+
const retractors = retractions.get(id);
|
|
807
|
+
for (const entry of retractors?.values() ?? []) {
|
|
808
|
+
if (target !== undefined && !isRecord(target))
|
|
809
|
+
invalidRetractions.add(entry);
|
|
810
|
+
else
|
|
811
|
+
invalidRetractions.delete(entry);
|
|
812
|
+
}
|
|
813
|
+
const records = (retractors?.size ?? 0) > 0 ? [] : entries.filter(({ observation }) => isRecord(observation));
|
|
814
|
+
records.sort((left, right) => compareObservations(left.observation, right.observation) || left.position - right.position);
|
|
815
|
+
const homing = bucketValues(decisions.get(id));
|
|
816
|
+
let decision;
|
|
817
|
+
for (const { observation } of homing)
|
|
818
|
+
if (isHoming(observation.payload) && sameExactPatchRef(observation.payload.revision, graph.terminal))
|
|
819
|
+
decision = { ...observation, payload: observation.payload };
|
|
820
|
+
const next = [];
|
|
821
|
+
for (const entry of records) {
|
|
822
|
+
const record = entry.observation;
|
|
823
|
+
if (!isRecord(record))
|
|
824
|
+
continue;
|
|
825
|
+
const chosen = decision?.payload.homes ?? initialHomes(record);
|
|
826
|
+
const present = [...new Set(chosen)].filter((node) => graphIndex.nodeIds.has(node));
|
|
827
|
+
const placement = {
|
|
828
|
+
position: entry.position,
|
|
829
|
+
record,
|
|
830
|
+
present,
|
|
831
|
+
decision,
|
|
832
|
+
pending: record.payload.kind === "demonstration" &&
|
|
833
|
+
(decision?.payload.pending === true || chosen.some((node) => !graphIndex.nodeIds.has(node))),
|
|
834
|
+
homeless: present.length === 0 &&
|
|
835
|
+
(record.payload.kind === "demonstration" || decision !== undefined || record.nodes !== undefined),
|
|
836
|
+
};
|
|
837
|
+
next.push(placement);
|
|
838
|
+
placementByRecord.set(record, placement);
|
|
839
|
+
for (const node of present) {
|
|
840
|
+
changeBucket(homedEntries, node, entry.position, record, true);
|
|
841
|
+
append(nextHomes, node, record);
|
|
842
|
+
}
|
|
843
|
+
current.set(id, new Set(present));
|
|
844
|
+
placed.set(id, [...initialHomes(record), ...present]);
|
|
845
|
+
}
|
|
846
|
+
if (next.length === 0) {
|
|
847
|
+
placements.delete(id);
|
|
848
|
+
current.delete(id);
|
|
849
|
+
placed.delete(id);
|
|
850
|
+
index.memoryPlacements.delete(id);
|
|
851
|
+
}
|
|
852
|
+
else {
|
|
853
|
+
placements.set(id, next);
|
|
854
|
+
// ALL revisions affect recording position. Every effective occurrence with this identity resets
|
|
855
|
+
// intrinsic placement; a decision may arrive before the Record or re-enter an earlier home.
|
|
856
|
+
const record = indexed(next.at(-1)).record;
|
|
857
|
+
const placement = { present: new Set(), positions: new Map() };
|
|
858
|
+
const events = [...new Set([...(byId.get(id) ?? []).filter((entry) => entry.effective), ...homing])].sort((left, right) => left.position - right.position);
|
|
859
|
+
for (const { observation, position } of events) {
|
|
860
|
+
if (observation.id === id) {
|
|
861
|
+
placement.present = new Set(initialHomes(record));
|
|
862
|
+
for (const node of placement.present)
|
|
863
|
+
placement.positions.set(node, position);
|
|
864
|
+
}
|
|
865
|
+
if (isDefaultObservation(observation) && isHoming(observation.payload) && observation.payload.of === id) {
|
|
866
|
+
for (const node of observation.payload.homes)
|
|
867
|
+
if (!placement.present.has(node))
|
|
868
|
+
placement.positions.set(node, position);
|
|
869
|
+
placement.present = new Set(observation.payload.homes);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
index.memoryPlacements.set(id, placement);
|
|
873
|
+
}
|
|
874
|
+
for (const node of new Set([...previousHomes.keys(), ...nextHomes.keys()])) {
|
|
875
|
+
const before = previousHomes.get(node) ?? [];
|
|
876
|
+
const after = nextHomes.get(node) ?? [];
|
|
877
|
+
if (before.length !== after.length || before.some((record, i) => record !== after[i])) {
|
|
878
|
+
dirtyNodes.add(node);
|
|
879
|
+
dirtyMemories.add(node);
|
|
880
|
+
historyChanged = true;
|
|
881
|
+
}
|
|
882
|
+
else if (previousMemory?.positions.get(node) !== index.memoryPlacements.get(id)?.positions.get(node)) {
|
|
883
|
+
dirtyMemories.add(node);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
const beforeScope = new Set(previousPlaced);
|
|
887
|
+
const afterScope = new Set(placed.get(id));
|
|
888
|
+
if (beforeScope.size !== afterScope.size || [...beforeScope].some((node) => !afterScope.has(node)))
|
|
889
|
+
dirtySources.add(id);
|
|
890
|
+
if (previous.length > 0 || next.length > 0)
|
|
891
|
+
recordsChanged = true;
|
|
892
|
+
}
|
|
893
|
+
function read(now, validateInterpretations = true) {
|
|
894
|
+
if (!isObservationTimestamp(now))
|
|
895
|
+
throw new Error("State requires an ISO timestamp");
|
|
896
|
+
if (invalidTimestamp !== undefined)
|
|
897
|
+
throw new Error("Invalid observation timestamp: " + invalidTimestamp.observation.id);
|
|
898
|
+
const time = Date.parse(now);
|
|
899
|
+
const changed = new Set();
|
|
900
|
+
const toggle = (entry, present) => {
|
|
901
|
+
if (entry.present === present || entry.observation.standing === "abandoned")
|
|
902
|
+
return;
|
|
903
|
+
entry.present = present;
|
|
904
|
+
changed.add(entry.observation.id);
|
|
905
|
+
const target = entry.observation.supersedes;
|
|
906
|
+
if (target !== undefined) {
|
|
907
|
+
superseded.set(target, (superseded.get(target) ?? 0) + (present ? 1 : -1));
|
|
908
|
+
changed.add(target);
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
while ((future.peek()?.time ?? Infinity) <= time) {
|
|
912
|
+
const entry = future.pop();
|
|
913
|
+
toggle(entry, true);
|
|
914
|
+
past.push(entry);
|
|
915
|
+
}
|
|
916
|
+
while ((past.peek()?.time ?? -Infinity) > time) {
|
|
917
|
+
const entry = past.pop();
|
|
918
|
+
toggle(entry, false);
|
|
919
|
+
future.push(entry);
|
|
920
|
+
}
|
|
921
|
+
for (const entry of pending) {
|
|
922
|
+
if (entry.observation.standing === "abandoned")
|
|
923
|
+
continue;
|
|
924
|
+
toggle(entry, entry.time <= time);
|
|
925
|
+
(entry.present ? past : future).push(entry);
|
|
926
|
+
}
|
|
927
|
+
pending = [];
|
|
928
|
+
if (prepared !== undefined && changed.size === 0 && dirtySources.size === 0 && dirtyRecords.size === 0) {
|
|
929
|
+
if (validateInterpretations && invalidCorrections.size > 0)
|
|
930
|
+
throw new Error("A correction must supersede an earlier interpretation");
|
|
931
|
+
return { ...prepared, dirtyNodes: new Set(), dirtySources: new Set(), historyChanged: false };
|
|
932
|
+
}
|
|
933
|
+
// Finish membership first, so dependencies always observe the final effective batch.
|
|
934
|
+
for (const id of changed) {
|
|
935
|
+
for (const entry of byId.get(id) ?? []) {
|
|
936
|
+
const active = entry.present && (superseded.get(id) ?? 0) === 0;
|
|
937
|
+
if (entry.effective !== active)
|
|
938
|
+
changeEffective(entry, active);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
for (const id of dirtySources) {
|
|
942
|
+
const entries = (byId.get(id) ?? []).filter((entry) => entry.effective);
|
|
943
|
+
const first = entries[0]?.observation;
|
|
944
|
+
if (first === undefined) {
|
|
945
|
+
index.firstById.delete(id);
|
|
946
|
+
index.positions.delete(id);
|
|
947
|
+
index.transcriptMemories.delete(id);
|
|
948
|
+
}
|
|
949
|
+
else {
|
|
950
|
+
index.firstById.set(id, first);
|
|
951
|
+
index.positions.set(id, indexed(entries.at(-1)).position);
|
|
952
|
+
index.transcriptMemories.delete(id);
|
|
953
|
+
for (const { observation } of entries)
|
|
954
|
+
if (isDefaultObservation(observation) &&
|
|
955
|
+
isMemory(observation.payload) &&
|
|
956
|
+
observation.payload.entries.some(({ source }) => source.kind === "transcript"))
|
|
957
|
+
index.transcriptMemories.set(id, observation.nodes ?? []);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
for (const id of dirtyRecords)
|
|
961
|
+
placeRecord(id);
|
|
962
|
+
const invalidPayload = firstEntry(invalidPayloads.keys());
|
|
963
|
+
if (invalidPayload !== undefined)
|
|
964
|
+
throw indexed(invalidPayloads.get(invalidPayload));
|
|
965
|
+
if (invalidRetractions.size > 0)
|
|
966
|
+
throw new Error("Default retractions must target a demonstration or claim");
|
|
967
|
+
for (const node of dirtyAux) {
|
|
968
|
+
index.lapses.set(node, bucketValues(lapseEntries.get(node)));
|
|
969
|
+
index.grades.set(node, bucketValues(gradeEntries.get(node)));
|
|
970
|
+
index.reviewPasses.set(node, bucketValues(reviewPassEntries.get(node)));
|
|
971
|
+
index.featureUses.set(node, bucketValues(featureEntries.get(node)));
|
|
972
|
+
index.memories.set(node, bucketValues(memoryEntries.get(node)));
|
|
973
|
+
index.summaries.set(node, bucketValues(summaryEntries.get(node)));
|
|
974
|
+
dirtyNodes.add(node);
|
|
975
|
+
}
|
|
976
|
+
for (const id of dirtySources) {
|
|
977
|
+
for (const nodes of memoryUsers.get(id)?.values() ?? [])
|
|
978
|
+
for (const node of nodes)
|
|
979
|
+
dirtyMemories.add(node);
|
|
980
|
+
for (const entry of interpretationUsers.get(id) ?? [])
|
|
981
|
+
dirtyInterpretations.add(entry);
|
|
982
|
+
}
|
|
983
|
+
for (const node of dirtyNodes) {
|
|
984
|
+
const records = bucketValues(homedEntries.get(node)).sort(compareObservations);
|
|
985
|
+
if (records.length === 0)
|
|
986
|
+
delete homed[node];
|
|
987
|
+
else
|
|
988
|
+
homed[node] = records;
|
|
989
|
+
}
|
|
990
|
+
for (const node of dirtyMemories) {
|
|
991
|
+
if (graphIndex.nodeIds.has(node))
|
|
992
|
+
memories[node] = projectMemory(node, homed[node] ?? [], index, current);
|
|
993
|
+
}
|
|
994
|
+
if (validateInterpretations && invalidCorrections.size > 0)
|
|
995
|
+
throw new Error("A correction must supersede an earlier interpretation");
|
|
996
|
+
for (const entry of dirtyInterpretations) {
|
|
997
|
+
supported.delete(entry.position);
|
|
998
|
+
const observation = entry.observation;
|
|
999
|
+
if (!entry.effective || !isInterpretationObservation(observation))
|
|
1000
|
+
continue;
|
|
1001
|
+
const { nodes = [], cites = [] } = observation;
|
|
1002
|
+
if (nodes.length === 0 || cites.length === 0 || new Set(cites).size !== cites.length)
|
|
1003
|
+
continue;
|
|
1004
|
+
const scope = new Set(nodes);
|
|
1005
|
+
if (cites.every((id) => (placed.get(id) ?? index.transcriptMemories.get(id) ?? []).some((node) => scope.has(node))))
|
|
1006
|
+
supported.set(entry.position, observation);
|
|
1007
|
+
}
|
|
1008
|
+
if (validateInterpretations && invalidScopes.size > 0)
|
|
1009
|
+
throw new Error("Interpretations require a Node scope and unique support");
|
|
1010
|
+
let records = prepared?.records ?? [];
|
|
1011
|
+
if (recordsChanged) {
|
|
1012
|
+
const previous = records.filter(({ id }) => !dirtyRecords.has(id));
|
|
1013
|
+
const updates = [...dirtyRecords]
|
|
1014
|
+
.flatMap((id) => (placements.get(id) ?? []).map(({ record }) => record))
|
|
1015
|
+
.sort(compareObservations);
|
|
1016
|
+
const next = [];
|
|
1017
|
+
let left = 0;
|
|
1018
|
+
let right = 0;
|
|
1019
|
+
while (left < previous.length && right < updates.length) {
|
|
1020
|
+
if (compareObservations(indexed(previous[left]), indexed(updates[right])) <= 0)
|
|
1021
|
+
next.push(indexed(previous[left++]));
|
|
1022
|
+
else
|
|
1023
|
+
next.push(indexed(updates[right++]));
|
|
1024
|
+
}
|
|
1025
|
+
records = [...next, ...previous.slice(left), ...updates.slice(right)];
|
|
1026
|
+
}
|
|
1027
|
+
let homing = prepared?.homing ?? { homes: {}, claims: {}, pending: [] };
|
|
1028
|
+
let homeless = prepared?.homeless ?? [];
|
|
1029
|
+
if (recordsChanged || prepared === undefined) {
|
|
1030
|
+
const homes = {};
|
|
1031
|
+
const claims = {};
|
|
1032
|
+
const pending = [];
|
|
1033
|
+
const lost = [];
|
|
1034
|
+
for (const record of records) {
|
|
1035
|
+
const { present, decision, pending: unresolved, homeless: unplaced } = indexed(placementByRecord.get(record));
|
|
1036
|
+
if (decision !== undefined)
|
|
1037
|
+
(record.payload.kind === "claim" ? claims : homes)[record.id] = present;
|
|
1038
|
+
if (unresolved)
|
|
1039
|
+
pending.push(record.id);
|
|
1040
|
+
if (unplaced)
|
|
1041
|
+
lost.push(record);
|
|
1042
|
+
}
|
|
1043
|
+
homing = { homes, claims, pending: [...new Set(pending)] };
|
|
1044
|
+
homeless = lost;
|
|
1045
|
+
}
|
|
1046
|
+
let history = prepared?.history ?? [];
|
|
1047
|
+
if (historyChanged) {
|
|
1048
|
+
const next = records
|
|
1049
|
+
.map((observation) => ({
|
|
1050
|
+
observation,
|
|
1051
|
+
nodes: [...(current.get(observation.id) ?? [])].sort((left, right) => (graphIndex.nodeOrder.get(left) ?? 0) - (graphIndex.nodeOrder.get(right) ?? 0)),
|
|
1052
|
+
}))
|
|
1053
|
+
.filter(({ nodes }) => nodes.length > 0);
|
|
1054
|
+
for (const observation of bucketValues(completions)) {
|
|
1055
|
+
const node = observation.payload.node.node;
|
|
1056
|
+
if (graphIndex.nodeIds.has(node) &&
|
|
1057
|
+
sameExactPatchRef(observation.payload.node.provenance, completionNodeRef(graph, node, graphIndex.nodeIds).provenance))
|
|
1058
|
+
next.push({ observation, nodes: [node] });
|
|
1059
|
+
}
|
|
1060
|
+
history = next;
|
|
1061
|
+
}
|
|
1062
|
+
// Only direct prerequisites receive implicit retention credit.
|
|
1063
|
+
const affected = new Set([...dirtyNodes, ...dirtyMemories]);
|
|
1064
|
+
for (const node of dirtyNodes)
|
|
1065
|
+
for (const prerequisite of graphIndex.prerequisites.get(node) ?? [])
|
|
1066
|
+
affected.add(prerequisite);
|
|
1067
|
+
prepared = {
|
|
1068
|
+
graphIndex,
|
|
1069
|
+
index: {
|
|
1070
|
+
lapses: new Map(index.lapses),
|
|
1071
|
+
grades: new Map(index.grades),
|
|
1072
|
+
reviewPasses: new Map(index.reviewPasses),
|
|
1073
|
+
featureUses: new Map(index.featureUses),
|
|
1074
|
+
},
|
|
1075
|
+
observations: observationsChanged
|
|
1076
|
+
? [...effective].sort((left, right) => left.position - right.position).map(({ observation }) => observation)
|
|
1077
|
+
: (prepared?.observations ?? []),
|
|
1078
|
+
records,
|
|
1079
|
+
homed: { ...homed },
|
|
1080
|
+
current: new Map(current),
|
|
1081
|
+
placed: new Map(placed),
|
|
1082
|
+
homeless,
|
|
1083
|
+
homing,
|
|
1084
|
+
memories: { ...memories },
|
|
1085
|
+
interpretations: dirtyInterpretations.size > 0 || prepared === undefined ? bucketValues(supported) : prepared.interpretations,
|
|
1086
|
+
dirtyNodes: affected,
|
|
1087
|
+
dirtySources: new Set(dirtySources),
|
|
1088
|
+
historyChanged,
|
|
1089
|
+
history,
|
|
1090
|
+
};
|
|
1091
|
+
dirtyRecords.clear();
|
|
1092
|
+
dirtySources.clear();
|
|
1093
|
+
dirtyNodes.clear();
|
|
1094
|
+
dirtyMemories.clear();
|
|
1095
|
+
dirtyAux.clear();
|
|
1096
|
+
dirtyInterpretations.clear();
|
|
1097
|
+
observationsChanged = recordsChanged = historyChanged = false;
|
|
1098
|
+
return prepared;
|
|
1099
|
+
}
|
|
1100
|
+
return { step, read };
|
|
1101
|
+
}
|
|
1102
|
+
/** Attachment order is recording order, not source time: old evidence can arrive or gain a home later. */
|
|
1103
|
+
function projectMemory(node, records, index, current) {
|
|
1104
|
+
const effectiveSource = (id) => {
|
|
1105
|
+
const target = index.firstById.get(id);
|
|
1106
|
+
return (target !== undefined &&
|
|
1107
|
+
(!isDefaultObservation(target) ||
|
|
1108
|
+
(!isDemonstration(target.payload) && !isClaim(target.payload)) ||
|
|
1109
|
+
current.get(id)?.has(node) === true));
|
|
1110
|
+
};
|
|
1111
|
+
const attachments = [];
|
|
1112
|
+
for (const record of records) {
|
|
1113
|
+
const position = index.memoryPlacements.get(record.id)?.positions.get(node) ?? -1;
|
|
1114
|
+
const strings = record.payload.kind === "demonstration"
|
|
1115
|
+
? [record.payload.task, record.payload.response]
|
|
1116
|
+
: [...(record.payload.prompt === undefined ? [] : [record.payload.prompt]), record.payload.statement];
|
|
1117
|
+
attachments.push({
|
|
1118
|
+
observation: record.id,
|
|
1119
|
+
position,
|
|
1120
|
+
entries: strings.map((text, index) => ({
|
|
1121
|
+
speaker: { kind: index === strings.length - 1 ? "learner" : "tutor" },
|
|
1122
|
+
text,
|
|
1123
|
+
at: record.at,
|
|
1124
|
+
source: { kind: "observation", observation: record.id },
|
|
1125
|
+
})),
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
for (const observation of index.memories.get(node) ?? []) {
|
|
1129
|
+
const position = index.positions.get(observation.id) ?? -1;
|
|
1130
|
+
const entries = observation.payload.entries.filter(({ source }) => source.kind !== "observation" || effectiveSource(source.observation));
|
|
1131
|
+
attachments.push({ observation: observation.id, position, entries });
|
|
1132
|
+
}
|
|
1133
|
+
attachments.sort((left, right) => left.position - right.position);
|
|
1134
|
+
const originals = [];
|
|
1135
|
+
for (const attachment of attachments)
|
|
1136
|
+
for (const entry of attachment.entries)
|
|
1137
|
+
originals.push({ ...entry, kind: "entry", observation: attachment.observation, position: originals.length });
|
|
1138
|
+
const originalsBySource = new Map();
|
|
1139
|
+
for (const entry of originals)
|
|
1140
|
+
append(originalsBySource, entry.observation, entry);
|
|
1141
|
+
let summary;
|
|
1142
|
+
for (const observation of index.summaries.get(node) ?? []) {
|
|
1143
|
+
const { sources: covered, dependencies } = observation.payload;
|
|
1144
|
+
const dependencyIds = new Set(dependencies);
|
|
1145
|
+
if (observation.payload.sources.length === 0 ||
|
|
1146
|
+
covered.some((source) => !originalsBySource.has(source)) ||
|
|
1147
|
+
dependencies.some((source) => !effectiveSource(source)) ||
|
|
1148
|
+
covered.some((source) => originalsBySource
|
|
1149
|
+
.get(source)
|
|
1150
|
+
?.some((entry) => entry.source.kind === "observation" && !dependencyIds.has(entry.source.observation))))
|
|
1151
|
+
continue;
|
|
1152
|
+
summary = { ...observation.payload, kind: "summary", observation: observation.id, at: observation.at };
|
|
1153
|
+
}
|
|
1154
|
+
const summarized = new Set(summary?.sources);
|
|
1155
|
+
return {
|
|
1156
|
+
node,
|
|
1157
|
+
originals,
|
|
1158
|
+
entries: summary === undefined
|
|
1159
|
+
? originals
|
|
1160
|
+
: [summary, ...originals.filter(({ observation }) => !summarized.has(observation))],
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
/** Deterministic lookup: supplied filters intersect; results keep acceptance order. */
|
|
1164
|
+
export function interpretationsDefault(state, query = {}) {
|
|
1165
|
+
const tag = query.tag?.trim().toLowerCase();
|
|
1166
|
+
return state.interpretations.filter(({ nodes = [], surface, payload }) => (query.nodes === undefined || query.nodes.some((node) => nodes.includes(node))) &&
|
|
1167
|
+
(tag === undefined || payload.tags.includes(tag)) &&
|
|
1168
|
+
(query.surface === undefined || surface === query.surface));
|
|
1169
|
+
}
|
|
1170
|
+
/** Default policy: retain history in the host, but ignore abandoned evidence here. */
|
|
1171
|
+
export function electedObservations(observations) {
|
|
1172
|
+
return observations.filter(({ standing }) => standing !== "abandoned");
|
|
1173
|
+
}
|
|
1174
|
+
/** Homing needs historical structure, not the acquisition vocabulary that revision was authored under. */
|
|
1175
|
+
export function homeDefaultRecords(graph, supplied, now) {
|
|
1176
|
+
const evidence = initDefaultEvidence(graph);
|
|
1177
|
+
evidence.step(supplied);
|
|
1178
|
+
const { observations, records, homed, homeless, placed, current, homing } = evidence.read(now, false);
|
|
1179
|
+
return {
|
|
1180
|
+
observations,
|
|
1181
|
+
records,
|
|
1182
|
+
homed,
|
|
1183
|
+
homeless,
|
|
1184
|
+
placed,
|
|
1185
|
+
current,
|
|
1186
|
+
homing,
|
|
1187
|
+
nodeIds: new Set(graph.nodes.map(({ id }) => id)),
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
const projectionBases = new WeakMap();
|
|
1191
|
+
export function defaultProjectionBasis(state) {
|
|
1192
|
+
return projectionBases.get(state);
|
|
1193
|
+
}
|
|
1194
|
+
function sameRecords(left, right) {
|
|
1195
|
+
return left === right || (left.length === right.length && left.every((record, i) => record === right[i]));
|
|
1196
|
+
}
|
|
1197
|
+
export function initDefaultState(graph) {
|
|
1198
|
+
const evidence = initDefaultEvidence(graph);
|
|
1199
|
+
const graphKey = {};
|
|
1200
|
+
let evidenceKey = {};
|
|
1201
|
+
let indicatorKey = {};
|
|
1202
|
+
const graphIndex = indexDefaultGraph(graph);
|
|
1203
|
+
const plans = new Map(graph.nodes.flatMap(({ id }) => {
|
|
1204
|
+
const query = defaultNodeCompletion(graph, id, graphIndex);
|
|
1205
|
+
return query === undefined ? [] : [[id, { query, evaluate: compileCompletion(query, id) }]];
|
|
1206
|
+
}));
|
|
1207
|
+
const own = new Map();
|
|
1208
|
+
const successes = new Map();
|
|
1209
|
+
const schedules = new Map();
|
|
1210
|
+
const acquisition = new Map();
|
|
1211
|
+
const reviewClearances = new Map();
|
|
1212
|
+
let history = prepareCompletionHistory([]);
|
|
1213
|
+
let boundary = -1;
|
|
1214
|
+
let initialized = false;
|
|
1215
|
+
let homeless;
|
|
1216
|
+
function read(now) {
|
|
1217
|
+
const prepared = evidence.read(now);
|
|
1218
|
+
const { index, homed } = prepared;
|
|
1219
|
+
const changedOwn = new Set();
|
|
1220
|
+
for (const id of prepared.dirtyNodes) {
|
|
1221
|
+
const records = homed[id] ?? [];
|
|
1222
|
+
if (!own.has(id) || !sameRecords(own.get(id) ?? [], records)) {
|
|
1223
|
+
own.set(id, records);
|
|
1224
|
+
const credit = records.filter(({ payload }) => payload.kind === "demonstration" && payload.unaided && payload.outcome === "success");
|
|
1225
|
+
successes.set(id, credit);
|
|
1226
|
+
changedOwn.add(id);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
const dirtySchedules = new Set(prepared.dirtyNodes);
|
|
1230
|
+
if (prepared.historyChanged)
|
|
1231
|
+
history = prepareCompletionHistory(prepared.history);
|
|
1232
|
+
const nextBoundary = completionBoundary(history, now);
|
|
1233
|
+
const completionChanged = !initialized || prepared.historyChanged || boundary !== nextBoundary;
|
|
1234
|
+
boundary = nextBoundary;
|
|
1235
|
+
const indicatorsChanged = !initialized || changedOwn.size > 0 || homeless !== prepared.homeless;
|
|
1236
|
+
let projectionChanged = indicatorsChanged;
|
|
1237
|
+
homeless = prepared.homeless;
|
|
1238
|
+
const nodes = {};
|
|
1239
|
+
for (const { id } of graph.nodes) {
|
|
1240
|
+
const previous = acquisition.get(id);
|
|
1241
|
+
const plan = plans.get(id);
|
|
1242
|
+
let completion = previous?.completion;
|
|
1243
|
+
if (plan !== undefined && completionChanged)
|
|
1244
|
+
completion = { query: plan.query, ...plan.evaluate(history, now, boundary) };
|
|
1245
|
+
if (previous === undefined || changedOwn.has(id) || completion !== previous.completion) {
|
|
1246
|
+
acquisition.set(id, labelDefaultNode({
|
|
1247
|
+
records: own.get(id) ?? [],
|
|
1248
|
+
...(plan === undefined || completion === undefined
|
|
1249
|
+
? {}
|
|
1250
|
+
: { completion: { ...completion, query: plan.query } }),
|
|
1251
|
+
}));
|
|
1252
|
+
projectionChanged = true;
|
|
1253
|
+
}
|
|
1254
|
+
const facts = indexed(acquisition.get(id));
|
|
1255
|
+
const featureUses = index.featureUses.get(id) ?? [];
|
|
1256
|
+
if (!initialized || dirtySchedules.has(id)) {
|
|
1257
|
+
const implicit = (graphIndex.dependents.get(id) ?? []).flatMap((node) => successes.get(node) ?? []);
|
|
1258
|
+
const records = own.get(id) ?? [];
|
|
1259
|
+
const grades = activeNodeGrades(index.grades.get(id) ?? [], [
|
|
1260
|
+
...records.flatMap((record) => isDemonstration(record.payload) && record.payload.unaided ? [{ ...record, payload: record.payload }] : []),
|
|
1261
|
+
...(index.lapses.get(id) ?? []),
|
|
1262
|
+
]);
|
|
1263
|
+
const supportedSuccesses = new Set(records
|
|
1264
|
+
.filter(({ payload }) => isDemonstration(payload) && payload.unaided && payload.outcome === "success")
|
|
1265
|
+
.map(({ id }) => id));
|
|
1266
|
+
reviewClearances.set(id, (index.reviewPasses.get(id) ?? []).some((pass) => (pass.cites?.length ?? 0) > 0 &&
|
|
1267
|
+
pass.cites?.every((source) => supportedSuccesses.has(source)) &&
|
|
1268
|
+
!grades.some(({ payload }) => Date.parse(payload.day.end) > Date.parse(pass.at))));
|
|
1269
|
+
// Grade/support changes and late direct evidence replace the affected day's review;
|
|
1270
|
+
// replay only this Node's chronology rather than retaining a second retention state.
|
|
1271
|
+
schedules.set(id, scheduleDefaultNode(own.get(id) ?? [], implicit, index.lapses.get(id) ?? [], index.grades.get(id) ?? [], DEFAULT_PARAMETERS));
|
|
1272
|
+
}
|
|
1273
|
+
const card = schedules.get(id);
|
|
1274
|
+
const schedule = card === undefined
|
|
1275
|
+
? undefined
|
|
1276
|
+
: {
|
|
1277
|
+
...card,
|
|
1278
|
+
retrievability: forgetting_curve((Date.parse(now) - Date.parse(card.lastReview)) / DAY_MS, card.stability),
|
|
1279
|
+
};
|
|
1280
|
+
nodes[id] = {
|
|
1281
|
+
...facts,
|
|
1282
|
+
featureUses,
|
|
1283
|
+
reviewCleared: reviewClearances.get(id) ?? false,
|
|
1284
|
+
...(schedule === undefined ? {} : { schedule }),
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
if (projectionChanged)
|
|
1288
|
+
evidenceKey = {};
|
|
1289
|
+
if (indicatorsChanged)
|
|
1290
|
+
indicatorKey = {};
|
|
1291
|
+
initialized = true;
|
|
1292
|
+
const state = {
|
|
1293
|
+
nodes,
|
|
1294
|
+
observations: prepared.observations,
|
|
1295
|
+
records: prepared.records,
|
|
1296
|
+
homing: prepared.homing,
|
|
1297
|
+
homeless: prepared.homeless,
|
|
1298
|
+
memories: prepared.memories,
|
|
1299
|
+
interpretations: prepared.interpretations,
|
|
1300
|
+
};
|
|
1301
|
+
projectionBases.set(state, { graph, graphKey, evidenceKey, indicatorKey });
|
|
1302
|
+
return state;
|
|
1303
|
+
}
|
|
1304
|
+
return { step: evidence.step, read };
|
|
1305
|
+
}
|
|
1306
|
+
/** Pure default policy, derived from the same reducer used by retained replays. */
|
|
1307
|
+
export function stateDefault(graph, supplied, now) {
|
|
1308
|
+
return readTheoryState({ initState: initDefaultState }, graph, supplied, now);
|
|
1309
|
+
}
|