@0xbuff/retention 0.0.0-stage → 0.0.2
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/CHANGELOG.md +33 -0
- package/COPYRIGHT.md +7 -0
- package/LICENSE +201 -0
- package/README.md +131 -2
- package/dist/index.d.ts +219 -0
- package/dist/index.js +1427 -0
- package/package.json +63 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1427 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
function failure(code, field, limit) {
|
|
3
|
+
return {
|
|
4
|
+
ok: false,
|
|
5
|
+
errors: [{
|
|
6
|
+
code,
|
|
7
|
+
...field === void 0 ? {} : { field },
|
|
8
|
+
...limit === void 0 ? {} : { limit }
|
|
9
|
+
}]
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function success(value) {
|
|
13
|
+
return {
|
|
14
|
+
ok: true,
|
|
15
|
+
value
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
// src/time/elapsed.ts
|
|
19
|
+
const DAY_MS = 864e5;
|
|
20
|
+
const MINUTE_MS = 6e4;
|
|
21
|
+
function isInstant(value) {
|
|
22
|
+
return typeof value === "number" && Number.isSafeInteger(value) && Math.abs(value) <= 864e13;
|
|
23
|
+
}
|
|
24
|
+
function isDayInterval(days) {
|
|
25
|
+
return typeof days === "number" && Number.isSafeInteger(days) && days >= 1 && days <= 3650;
|
|
26
|
+
}
|
|
27
|
+
function checkedAdd(left, right) {
|
|
28
|
+
if (!isInstant(left) || !isInstant(right)) return null;
|
|
29
|
+
const sum = left + right;
|
|
30
|
+
return isInstant(sum) ? sum + 0 : null;
|
|
31
|
+
}
|
|
32
|
+
function addElapsedDays(anchorMs, days) {
|
|
33
|
+
if (!isInstant(anchorMs)) return failure("INVALID_TIMESTAMP", "atMs");
|
|
34
|
+
if (!isDayInterval(days)) return failure("INVALID_POLICY", "intervalsDays");
|
|
35
|
+
const target = checkedAdd(anchorMs, days * DAY_MS);
|
|
36
|
+
return target === null ? failure("INVALID_TIMESTAMP", "dueAtMs") : success(target);
|
|
37
|
+
}
|
|
38
|
+
// src/time/calendar.ts
|
|
39
|
+
const MAX_OFFSET_MS = 1440 * MINUTE_MS;
|
|
40
|
+
function hasValidCalendarArithmetic(profile) {
|
|
41
|
+
let start = profile.coverageStartMs;
|
|
42
|
+
let offset = profile.initialOffsetMinutes;
|
|
43
|
+
for (const transition of profile.transitions) {
|
|
44
|
+
if (checkedAdd(start, offset * 6e4) === null || checkedAdd(transition.atMs, offset * 6e4) === null) return false;
|
|
45
|
+
start = transition.atMs;
|
|
46
|
+
offset = transition.offsetMinutes;
|
|
47
|
+
}
|
|
48
|
+
return checkedAdd(start, offset * 6e4) !== null && checkedAdd(profile.coverageEndMs, offset * 6e4) !== null;
|
|
49
|
+
}
|
|
50
|
+
function coversWindow(profile, localMs) {
|
|
51
|
+
const lower = checkedAdd(localMs, -864e5);
|
|
52
|
+
const upper = checkedAdd(localMs, MAX_OFFSET_MS);
|
|
53
|
+
return lower !== null && upper !== null && lower >= profile.coverageStartMs && upper < profile.coverageEndMs;
|
|
54
|
+
}
|
|
55
|
+
function offsetAt(profile, instant) {
|
|
56
|
+
let offset = profile.initialOffsetMinutes;
|
|
57
|
+
for (const transition of profile.transitions) {
|
|
58
|
+
if (transition.atMs > instant) break;
|
|
59
|
+
offset = transition.offsetMinutes;
|
|
60
|
+
}
|
|
61
|
+
return offset;
|
|
62
|
+
}
|
|
63
|
+
function earliestInstant(profile, localMs) {
|
|
64
|
+
let start = profile.coverageStartMs;
|
|
65
|
+
let offset = profile.initialOffsetMinutes;
|
|
66
|
+
for (const transition of profile.transitions) {
|
|
67
|
+
const candidate = checkedAdd(localMs, -offset * MINUTE_MS);
|
|
68
|
+
if (candidate !== null && candidate >= start && candidate < transition.atMs) return candidate;
|
|
69
|
+
start = transition.atMs;
|
|
70
|
+
offset = transition.offsetMinutes;
|
|
71
|
+
}
|
|
72
|
+
const candidate = checkedAdd(localMs, -offset * MINUTE_MS);
|
|
73
|
+
return candidate !== null && candidate >= start && candidate < profile.coverageEndMs ? candidate : null;
|
|
74
|
+
}
|
|
75
|
+
function gapShift(profile, localMs) {
|
|
76
|
+
let prior = profile.initialOffsetMinutes;
|
|
77
|
+
let shift = null;
|
|
78
|
+
for (const transition of profile.transitions) {
|
|
79
|
+
const next = transition.offsetMinutes;
|
|
80
|
+
if (next > prior) {
|
|
81
|
+
const start = checkedAdd(transition.atMs, prior * MINUTE_MS);
|
|
82
|
+
const end = checkedAdd(transition.atMs, next * MINUTE_MS);
|
|
83
|
+
if (start === null || end === null) return null;
|
|
84
|
+
if (localMs >= start && localMs < end) {
|
|
85
|
+
if (shift !== null) return null;
|
|
86
|
+
shift = (next - prior) * MINUTE_MS;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
prior = next;
|
|
90
|
+
}
|
|
91
|
+
return shift;
|
|
92
|
+
}
|
|
93
|
+
function addCalendarDays(anchorMs, days, profile) {
|
|
94
|
+
if (!isInstant(anchorMs)) return failure("INVALID_TIMESTAMP", "atMs");
|
|
95
|
+
if (!isDayInterval(days)) return failure("INVALID_POLICY", "intervalsDays");
|
|
96
|
+
if (anchorMs < profile.coverageStartMs || anchorMs >= profile.coverageEndMs) return failure("CALENDAR_PROFILE_MISMATCH", "calendarProfile");
|
|
97
|
+
const local = checkedAdd(anchorMs, offsetAt(profile, anchorMs) * MINUTE_MS);
|
|
98
|
+
const target = local === null ? null : checkedAdd(local, days * DAY_MS);
|
|
99
|
+
if (target === null) return failure("INVALID_TIMESTAMP", "dueAtMs");
|
|
100
|
+
if (checkedAdd(target, -864e5) === null || checkedAdd(target, MAX_OFFSET_MS) === null) return failure("INVALID_TIMESTAMP", "dueAtMs");
|
|
101
|
+
if (!coversWindow(profile, target)) return failure("CALENDAR_PROFILE_MISMATCH", "calendarProfile");
|
|
102
|
+
const direct = earliestInstant(profile, target);
|
|
103
|
+
if (direct !== null) return success(direct);
|
|
104
|
+
const shift = gapShift(profile, target);
|
|
105
|
+
if (shift === null) return failure("CALENDAR_PROFILE_MISMATCH", "calendarProfile");
|
|
106
|
+
const shifted = checkedAdd(target, shift);
|
|
107
|
+
if (shifted === null || checkedAdd(shifted, -864e5) === null || checkedAdd(shifted, MAX_OFFSET_MS) === null) return failure("INVALID_TIMESTAMP", "dueAtMs");
|
|
108
|
+
if (!coversWindow(profile, shifted)) return failure("CALENDAR_PROFILE_MISMATCH", "calendarProfile");
|
|
109
|
+
const resolved = earliestInstant(profile, shifted);
|
|
110
|
+
return resolved === null ? failure("CALENDAR_PROFILE_MISMATCH", "calendarProfile") : success(resolved);
|
|
111
|
+
}
|
|
112
|
+
// src/validation/limits.ts
|
|
113
|
+
const LIMITS = Object.freeze({
|
|
114
|
+
distinctEvents: 1e4,
|
|
115
|
+
rawEvents: 2e4,
|
|
116
|
+
concepts: 1e3,
|
|
117
|
+
relations: 1e4,
|
|
118
|
+
calendarTransitions: 4096,
|
|
119
|
+
jsonDepth: 12,
|
|
120
|
+
stringLength: 256,
|
|
121
|
+
aggregateStringLength: 4e6,
|
|
122
|
+
identifierLength: 128,
|
|
123
|
+
intervals: 64,
|
|
124
|
+
misses: 1e3,
|
|
125
|
+
weight: 1e3
|
|
126
|
+
});
|
|
127
|
+
function integer(value, min, max) {
|
|
128
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max;
|
|
129
|
+
}
|
|
130
|
+
function identifier(value) {
|
|
131
|
+
return typeof value === "string" && value.length <= LIMITS.identifierLength && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(value);
|
|
132
|
+
}
|
|
133
|
+
function label(value) {
|
|
134
|
+
return typeof value === "string" && value.length > 0 && value.length <= LIMITS.stringLength;
|
|
135
|
+
}
|
|
136
|
+
function record(value, required, optional = []) {
|
|
137
|
+
if (typeof value !== "object" || value === null) return null;
|
|
138
|
+
const prototype = Object.getPrototypeOf(value);
|
|
139
|
+
if (prototype !== Object.prototype && prototype !== null) return null;
|
|
140
|
+
let count = 0;
|
|
141
|
+
for (const key in value) if (Object.hasOwn(value, key)) {
|
|
142
|
+
count += 1;
|
|
143
|
+
if (count > required.length + optional.length) return null;
|
|
144
|
+
if (!required.includes(key) && !optional.includes(key)) return null;
|
|
145
|
+
}
|
|
146
|
+
if (count < required.length) return null;
|
|
147
|
+
const keys = Reflect.ownKeys(value);
|
|
148
|
+
if (keys.length !== count) return null;
|
|
149
|
+
const result = {};
|
|
150
|
+
for (const key of keys) {
|
|
151
|
+
if (typeof key !== "string" || !required.includes(key) && !optional.includes(key)) return null;
|
|
152
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
153
|
+
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) return null;
|
|
154
|
+
Object.defineProperty(result, key, {
|
|
155
|
+
value: descriptor.value,
|
|
156
|
+
enumerable: true
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
if (!required.every((key) => Object.hasOwn(result, key))) return null;
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
function arrayLength(value) {
|
|
163
|
+
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) return null;
|
|
164
|
+
const length = Object.getOwnPropertyDescriptor(value, "length")?.value;
|
|
165
|
+
return integer(length, 0, 0xffffffff) ? length : null;
|
|
166
|
+
}
|
|
167
|
+
function array(value, max) {
|
|
168
|
+
const length = arrayLength(value);
|
|
169
|
+
if (length === null || length > max || !Array.isArray(value)) return null;
|
|
170
|
+
let count = 0;
|
|
171
|
+
for (const key in value) if (Object.hasOwn(value, key)) {
|
|
172
|
+
if (key.length > 10) return null;
|
|
173
|
+
const index = Number(key);
|
|
174
|
+
if (!integer(index, 0, length - 1) || String(index) !== key) return null;
|
|
175
|
+
count += 1;
|
|
176
|
+
}
|
|
177
|
+
if (count !== length || Reflect.ownKeys(value).length !== length + 1) return null;
|
|
178
|
+
const result = [];
|
|
179
|
+
for (let index = 0; index < length; index += 1) {
|
|
180
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
181
|
+
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) return null;
|
|
182
|
+
result.push(descriptor.value);
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
}
|
|
186
|
+
// src/validation/policies.ts
|
|
187
|
+
function invalid$2(field) {
|
|
188
|
+
return failure("INVALID_POLICY", field);
|
|
189
|
+
}
|
|
190
|
+
function calendar(value) {
|
|
191
|
+
const fields = record(value, [
|
|
192
|
+
"zoneId",
|
|
193
|
+
"rulesVersion",
|
|
194
|
+
"coverageStartMs",
|
|
195
|
+
"coverageEndMs",
|
|
196
|
+
"initialOffsetMinutes",
|
|
197
|
+
"transitions"
|
|
198
|
+
]);
|
|
199
|
+
if (!fields) return invalid$2("calendarProfile");
|
|
200
|
+
const { zoneId, rulesVersion, coverageStartMs, coverageEndMs, initialOffsetMinutes } = fields;
|
|
201
|
+
if (!label(zoneId) || !identifier(rulesVersion)) return invalid$2("calendarProfile");
|
|
202
|
+
if (!isInstant(coverageStartMs) || !isInstant(coverageEndMs)) return failure("INVALID_TIMESTAMP", "calendarProfile");
|
|
203
|
+
if (coverageStartMs >= coverageEndMs || !integer(initialOffsetMinutes, -1440, 1440)) return invalid$2("calendarProfile");
|
|
204
|
+
const length = arrayLength(fields.transitions);
|
|
205
|
+
if (length !== null && length > LIMITS.calendarTransitions) return failure("RESOURCE_LIMIT_EXCEEDED", "transitions", LIMITS.calendarTransitions);
|
|
206
|
+
const entries = array(fields.transitions, LIMITS.calendarTransitions);
|
|
207
|
+
if (!entries) return invalid$2("transitions");
|
|
208
|
+
const transitions = [];
|
|
209
|
+
let prior = coverageStartMs;
|
|
210
|
+
for (const entry of entries) {
|
|
211
|
+
const transition = record(entry, ["atMs", "offsetMinutes"]);
|
|
212
|
+
if (!transition) return invalid$2("transitions");
|
|
213
|
+
const { atMs, offsetMinutes } = transition;
|
|
214
|
+
if (!isInstant(atMs)) return failure("INVALID_TIMESTAMP", "atMs");
|
|
215
|
+
if (atMs <= prior || atMs >= coverageEndMs || !integer(offsetMinutes, -1440, 1440)) return invalid$2("transitions");
|
|
216
|
+
transitions.push(Object.freeze({
|
|
217
|
+
atMs: atMs + 0,
|
|
218
|
+
offsetMinutes: offsetMinutes + 0
|
|
219
|
+
}));
|
|
220
|
+
prior = atMs;
|
|
221
|
+
}
|
|
222
|
+
const profile = Object.freeze({
|
|
223
|
+
zoneId,
|
|
224
|
+
rulesVersion,
|
|
225
|
+
coverageStartMs: coverageStartMs + 0,
|
|
226
|
+
coverageEndMs: coverageEndMs + 0,
|
|
227
|
+
initialOffsetMinutes: initialOffsetMinutes + 0,
|
|
228
|
+
transitions: Object.freeze(transitions)
|
|
229
|
+
});
|
|
230
|
+
return hasValidCalendarArithmetic(profile) ? success(profile) : failure("INVALID_TIMESTAMP", "calendarProfile");
|
|
231
|
+
}
|
|
232
|
+
function scheduling(value) {
|
|
233
|
+
const fields = record(value, [
|
|
234
|
+
"intervalsDays",
|
|
235
|
+
"retryDays",
|
|
236
|
+
"maintenanceDays",
|
|
237
|
+
"supportAfterMisses",
|
|
238
|
+
"longProbeAction",
|
|
239
|
+
"dateArithmetic"
|
|
240
|
+
], ["calendarProfile"]);
|
|
241
|
+
if (!fields) return invalid$2("scheduling");
|
|
242
|
+
const entries = array(fields.intervalsDays, LIMITS.intervals);
|
|
243
|
+
if (!entries || entries.length === 0) return invalid$2("intervalsDays");
|
|
244
|
+
const intervalsDays = [];
|
|
245
|
+
for (const entry of entries) {
|
|
246
|
+
if (!isDayInterval(entry)) return invalid$2("intervalsDays");
|
|
247
|
+
intervalsDays.push(entry);
|
|
248
|
+
}
|
|
249
|
+
const { retryDays, maintenanceDays, supportAfterMisses, longProbeAction, dateArithmetic } = fields;
|
|
250
|
+
if (!isDayInterval(retryDays)) return invalid$2("retryDays");
|
|
251
|
+
if (!isDayInterval(maintenanceDays)) return invalid$2("maintenanceDays");
|
|
252
|
+
if (!integer(supportAfterMisses, 1, LIMITS.misses)) return invalid$2("supportAfterMisses");
|
|
253
|
+
if (longProbeAction !== "restart" && longProbeAction !== "support" && longProbeAction !== "keep") return invalid$2("longProbeAction");
|
|
254
|
+
const common = {
|
|
255
|
+
intervalsDays: Object.freeze(intervalsDays),
|
|
256
|
+
retryDays,
|
|
257
|
+
maintenanceDays,
|
|
258
|
+
supportAfterMisses,
|
|
259
|
+
longProbeAction
|
|
260
|
+
};
|
|
261
|
+
if (dateArithmetic === "elapsed_milliseconds") return Object.hasOwn(fields, "calendarProfile") ? invalid$2("calendarProfile") : success(Object.freeze({
|
|
262
|
+
...common,
|
|
263
|
+
dateArithmetic
|
|
264
|
+
}));
|
|
265
|
+
if (dateArithmetic !== "local_calendar_days" || !Object.hasOwn(fields, "calendarProfile")) return invalid$2("dateArithmetic");
|
|
266
|
+
const result = calendar(fields.calendarProfile);
|
|
267
|
+
return result.ok ? success(Object.freeze({
|
|
268
|
+
...common,
|
|
269
|
+
dateArithmetic,
|
|
270
|
+
calendarProfile: result.value
|
|
271
|
+
})) : result;
|
|
272
|
+
}
|
|
273
|
+
function eligibility(value) {
|
|
274
|
+
const fields = record(value, [
|
|
275
|
+
"eligibilityPolicyVersion",
|
|
276
|
+
"minSuccesses",
|
|
277
|
+
"minSessions",
|
|
278
|
+
"minSpanMs",
|
|
279
|
+
"requireFresh",
|
|
280
|
+
"maxHints",
|
|
281
|
+
"minLadder",
|
|
282
|
+
"onFailure",
|
|
283
|
+
"onNonqualifying"
|
|
284
|
+
]);
|
|
285
|
+
if (!fields) return invalid$2("eligibility");
|
|
286
|
+
const { eligibilityPolicyVersion, minSuccesses, minSessions, minSpanMs, requireFresh, maxHints, minLadder, onFailure, onNonqualifying } = fields;
|
|
287
|
+
if (!identifier(eligibilityPolicyVersion)) return invalid$2("eligibilityPolicyVersion");
|
|
288
|
+
if (!integer(minSuccesses, 1, 1e3)) return invalid$2("minSuccesses");
|
|
289
|
+
if (!integer(minSessions, 1, minSuccesses)) return invalid$2("minSessions");
|
|
290
|
+
if (!integer(minSpanMs, 0, Number.MAX_SAFE_INTEGER)) return invalid$2("minSpanMs");
|
|
291
|
+
if (typeof requireFresh !== "boolean") return invalid$2("requireFresh");
|
|
292
|
+
if (!integer(maxHints, 0, LIMITS.weight)) return invalid$2("maxHints");
|
|
293
|
+
if (!integer(minLadder, 0, LIMITS.weight)) return invalid$2("minLadder");
|
|
294
|
+
if (onFailure !== "reset" && onFailure !== "ignore") return invalid$2("onFailure");
|
|
295
|
+
if (onNonqualifying !== "reset" && onNonqualifying !== "ignore") return invalid$2("onNonqualifying");
|
|
296
|
+
return success(Object.freeze({
|
|
297
|
+
eligibilityPolicyVersion,
|
|
298
|
+
minSuccesses,
|
|
299
|
+
minSessions,
|
|
300
|
+
minSpanMs: minSpanMs + 0,
|
|
301
|
+
requireFresh,
|
|
302
|
+
maxHints: maxHints + 0,
|
|
303
|
+
minLadder: minLadder + 0,
|
|
304
|
+
onFailure,
|
|
305
|
+
onNonqualifying
|
|
306
|
+
}));
|
|
307
|
+
}
|
|
308
|
+
function priority(value) {
|
|
309
|
+
const fields = record(value, [
|
|
310
|
+
"overdue",
|
|
311
|
+
"support",
|
|
312
|
+
"relation",
|
|
313
|
+
"stage"
|
|
314
|
+
]);
|
|
315
|
+
if (!fields) return invalid$2("priority");
|
|
316
|
+
const { overdue, support, relation, stage } = fields;
|
|
317
|
+
if (!integer(overdue, 0, LIMITS.weight) || !integer(support, 0, LIMITS.weight) || !integer(relation, 0, LIMITS.weight) || !integer(stage, 0, LIMITS.weight)) return invalid$2("priority");
|
|
318
|
+
return success(Object.freeze({
|
|
319
|
+
overdue: overdue + 0,
|
|
320
|
+
support: support + 0,
|
|
321
|
+
relation: relation + 0,
|
|
322
|
+
stage: stage + 0
|
|
323
|
+
}));
|
|
324
|
+
}
|
|
325
|
+
function validatePolicy(input) {
|
|
326
|
+
const fields = record(input, [
|
|
327
|
+
"schemaVersion",
|
|
328
|
+
"algorithmVersion",
|
|
329
|
+
"policyId",
|
|
330
|
+
"policyVersion",
|
|
331
|
+
"scheduling"
|
|
332
|
+
], ["eligibility", "priority"]);
|
|
333
|
+
if (!fields) return invalid$2("policy");
|
|
334
|
+
if (fields.schemaVersion !== 1 || fields.algorithmVersion !== "1") return failure("UNSUPPORTED_VERSION", "policy");
|
|
335
|
+
const { policyId, policyVersion } = fields;
|
|
336
|
+
if (!identifier(policyId) || !identifier(policyVersion)) return invalid$2("policy");
|
|
337
|
+
const schedule = scheduling(fields.scheduling);
|
|
338
|
+
if (!schedule.ok) return schedule;
|
|
339
|
+
let normalized = {
|
|
340
|
+
schemaVersion: 1,
|
|
341
|
+
algorithmVersion: "1",
|
|
342
|
+
policyId,
|
|
343
|
+
policyVersion,
|
|
344
|
+
scheduling: schedule.value
|
|
345
|
+
};
|
|
346
|
+
if (Object.hasOwn(fields, "eligibility")) {
|
|
347
|
+
const candidate = eligibility(fields.eligibility);
|
|
348
|
+
if (!candidate.ok) return candidate;
|
|
349
|
+
normalized = {
|
|
350
|
+
...normalized,
|
|
351
|
+
eligibility: candidate.value
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
if (Object.hasOwn(fields, "priority")) {
|
|
355
|
+
const weights = priority(fields.priority);
|
|
356
|
+
if (!weights.ok) return weights;
|
|
357
|
+
normalized = {
|
|
358
|
+
...normalized,
|
|
359
|
+
priority: weights.value
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
return success(Object.freeze(normalized));
|
|
363
|
+
}
|
|
364
|
+
// src/events/identity.ts
|
|
365
|
+
function canonicalJson(value) {
|
|
366
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
367
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
|
|
368
|
+
const object = value;
|
|
369
|
+
return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`;
|
|
370
|
+
}
|
|
371
|
+
function policyIdentity(policy) {
|
|
372
|
+
return canonicalJson(policy);
|
|
373
|
+
}
|
|
374
|
+
function eventIdentity(event) {
|
|
375
|
+
return canonicalJson(event);
|
|
376
|
+
}
|
|
377
|
+
// src/validation/projections.ts
|
|
378
|
+
const maxReasons = LIMITS.distinctEvents * 5;
|
|
379
|
+
const maxPolicyIdentity = LIMITS.calendarTransitions * 128 + 4096;
|
|
380
|
+
const maxWatermark = LIMITS.aggregateStringLength * 6 + LIMITS.distinctEvents * 1024 + 2;
|
|
381
|
+
function invalid$1(field) {
|
|
382
|
+
return failure("INVALID_EVENT", field);
|
|
383
|
+
}
|
|
384
|
+
function derivedString(value, max, start, end) {
|
|
385
|
+
return typeof value === "string" && value.length <= max && value.startsWith(start) && value.endsWith(end);
|
|
386
|
+
}
|
|
387
|
+
function validateProjectionIdentity(input) {
|
|
388
|
+
const fields = record(input, [
|
|
389
|
+
"schemaVersion",
|
|
390
|
+
"algorithmVersion",
|
|
391
|
+
"scopeId",
|
|
392
|
+
"policyIdentity",
|
|
393
|
+
"evaluatedAtMs",
|
|
394
|
+
"watermark"
|
|
395
|
+
]);
|
|
396
|
+
if (!fields) return invalid$1("identity");
|
|
397
|
+
const { schemaVersion, algorithmVersion, scopeId, policyIdentity, evaluatedAtMs, watermark } = fields;
|
|
398
|
+
if (schemaVersion !== 1 || algorithmVersion !== "1") return failure("UNSUPPORTED_VERSION", "identity");
|
|
399
|
+
if (!identifier(scopeId)) return invalid$1("scopeId");
|
|
400
|
+
if (!isInstant(evaluatedAtMs)) return failure("INVALID_TIMESTAMP", "evaluatedAtMs");
|
|
401
|
+
if (!derivedString(policyIdentity, maxPolicyIdentity, "{\"algorithmVersion\":\"1\",", "}")) return invalid$1("policyIdentity");
|
|
402
|
+
if (!derivedString(watermark, maxWatermark, "[", "]")) return invalid$1("watermark");
|
|
403
|
+
return success(Object.freeze({
|
|
404
|
+
schemaVersion,
|
|
405
|
+
algorithmVersion,
|
|
406
|
+
scopeId,
|
|
407
|
+
policyIdentity,
|
|
408
|
+
evaluatedAtMs: evaluatedAtMs + 0,
|
|
409
|
+
watermark
|
|
410
|
+
}));
|
|
411
|
+
}
|
|
412
|
+
function reasonBound(code) {
|
|
413
|
+
switch (code) {
|
|
414
|
+
case "FIRST_PASS":
|
|
415
|
+
case "EARLY_PASS":
|
|
416
|
+
case "DUE_PASS": return 63;
|
|
417
|
+
case "MISS":
|
|
418
|
+
case "SUPPORT_THRESHOLD":
|
|
419
|
+
case "QUALIFYING_SUCCESS": return 1e4;
|
|
420
|
+
case "RESTART":
|
|
421
|
+
case "FORCED_SUPPORT":
|
|
422
|
+
case "DELAYED_PROBE":
|
|
423
|
+
case "MAINTENANCE":
|
|
424
|
+
case "NO_OBSERVATION":
|
|
425
|
+
case "CREDIT_CORRECTION":
|
|
426
|
+
case "CREDIT_REVOCATION":
|
|
427
|
+
case "EVENT_DELETION":
|
|
428
|
+
case "SCOPE_DELETION":
|
|
429
|
+
case "CANDIDATE_RESET":
|
|
430
|
+
case "CANDIDATE_IGNORE": return null;
|
|
431
|
+
default: return;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
function readReasons(input, remaining, budget) {
|
|
435
|
+
const length = arrayLength(input);
|
|
436
|
+
if (length !== null && length > remaining) return failure("RESOURCE_LIMIT_EXCEEDED", "reasons", maxReasons);
|
|
437
|
+
const entries = array(input, remaining);
|
|
438
|
+
if (!entries) return invalid$1("reasons");
|
|
439
|
+
const reasons = [];
|
|
440
|
+
for (const entry of entries) {
|
|
441
|
+
const fields = record(entry, ["code"], ["value"]);
|
|
442
|
+
if (!fields) return invalid$1("reasons");
|
|
443
|
+
const bound = reasonBound(fields.code);
|
|
444
|
+
if (bound === void 0) return invalid$1("code");
|
|
445
|
+
const code = fields.code;
|
|
446
|
+
if (budget && !budget.consume(code)) return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength);
|
|
447
|
+
if (bound === null) {
|
|
448
|
+
if (Object.hasOwn(fields, "value")) return invalid$1("value");
|
|
449
|
+
reasons.push(Object.freeze({ code }));
|
|
450
|
+
} else {
|
|
451
|
+
if (!integer(fields.value, 0, bound)) return invalid$1("value");
|
|
452
|
+
reasons.push(Object.freeze({
|
|
453
|
+
code,
|
|
454
|
+
value: fields.value + 0
|
|
455
|
+
}));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return success(Object.freeze(reasons));
|
|
459
|
+
}
|
|
460
|
+
function readIds(input, field, budget) {
|
|
461
|
+
const length = arrayLength(input);
|
|
462
|
+
if (length !== null && length > LIMITS.distinctEvents) return failure("RESOURCE_LIMIT_EXCEEDED", field, LIMITS.distinctEvents);
|
|
463
|
+
const entries = array(input, LIMITS.distinctEvents);
|
|
464
|
+
if (!entries) return invalid$1(field);
|
|
465
|
+
const ids = /* @__PURE__ */ new Set();
|
|
466
|
+
for (const entry of entries) {
|
|
467
|
+
if (!identifier(entry) || ids.has(entry)) return invalid$1(field);
|
|
468
|
+
if (budget && !budget.consume(entry)) return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength);
|
|
469
|
+
ids.add(entry);
|
|
470
|
+
}
|
|
471
|
+
return success(Object.freeze([...ids]));
|
|
472
|
+
}
|
|
473
|
+
function count(value) {
|
|
474
|
+
return integer(value, 0, LIMITS.distinctEvents);
|
|
475
|
+
}
|
|
476
|
+
function nullableInstant(value) {
|
|
477
|
+
return value === null || isInstant(value);
|
|
478
|
+
}
|
|
479
|
+
function readCandidate(input, evaluatedAtMs, remaining, budget) {
|
|
480
|
+
const fields = record(input, [
|
|
481
|
+
"readiness",
|
|
482
|
+
"qualifyingSuccesses",
|
|
483
|
+
"distinctSessions",
|
|
484
|
+
"firstQualifyingAtMs",
|
|
485
|
+
"lastQualifyingAtMs",
|
|
486
|
+
"qualifyingSpanMs",
|
|
487
|
+
"reasons"
|
|
488
|
+
]);
|
|
489
|
+
if (!fields) return invalid$1("candidate");
|
|
490
|
+
const { readiness, qualifyingSuccesses, distinctSessions, firstQualifyingAtMs, lastQualifyingAtMs, qualifyingSpanMs } = fields;
|
|
491
|
+
if (readiness !== "unknown" && readiness !== "developing" && readiness !== "candidate_ready") return invalid$1("readiness");
|
|
492
|
+
if (!count(qualifyingSuccesses) || !count(distinctSessions) || distinctSessions > qualifyingSuccesses) return invalid$1("qualifyingSuccesses");
|
|
493
|
+
if (!nullableInstant(firstQualifyingAtMs) || !nullableInstant(lastQualifyingAtMs) || lastQualifyingAtMs !== null && lastQualifyingAtMs > evaluatedAtMs) return failure("INVALID_TIMESTAMP", "qualifyingAtMs");
|
|
494
|
+
if (!integer(qualifyingSpanMs, 0, 864e13)) return invalid$1("qualifyingSpanMs");
|
|
495
|
+
if (qualifyingSuccesses === 0) {
|
|
496
|
+
if (distinctSessions !== 0 || firstQualifyingAtMs !== null || lastQualifyingAtMs !== null || qualifyingSpanMs !== 0 || readiness === "candidate_ready") return invalid$1("candidate");
|
|
497
|
+
} else if (readiness === "unknown" || distinctSessions === 0 || firstQualifyingAtMs === null || lastQualifyingAtMs === null || lastQualifyingAtMs - firstQualifyingAtMs !== qualifyingSpanMs) return invalid$1("candidate");
|
|
498
|
+
if (budget && !budget.consume(readiness)) return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength);
|
|
499
|
+
const reasons = readReasons(fields.reasons, remaining, budget);
|
|
500
|
+
if (!reasons.ok) return reasons;
|
|
501
|
+
return success(Object.freeze({
|
|
502
|
+
readiness,
|
|
503
|
+
qualifyingSuccesses: qualifyingSuccesses + 0,
|
|
504
|
+
distinctSessions: distinctSessions + 0,
|
|
505
|
+
firstQualifyingAtMs,
|
|
506
|
+
lastQualifyingAtMs,
|
|
507
|
+
qualifyingSpanMs: qualifyingSpanMs + 0,
|
|
508
|
+
reasons: reasons.value
|
|
509
|
+
}));
|
|
510
|
+
}
|
|
511
|
+
function readConcept(input, evaluatedAtMs, remaining, budget) {
|
|
512
|
+
const fields = record(input, [
|
|
513
|
+
"conceptId",
|
|
514
|
+
"scheduleState",
|
|
515
|
+
"stageIndex",
|
|
516
|
+
"dueAtMs",
|
|
517
|
+
"lastSeenAtMs",
|
|
518
|
+
"consecutiveMisses",
|
|
519
|
+
"advisorySuccesses",
|
|
520
|
+
"needsSupport",
|
|
521
|
+
"recommendationKind",
|
|
522
|
+
"readiness",
|
|
523
|
+
"reasons"
|
|
524
|
+
], ["candidate"]);
|
|
525
|
+
if (!fields) return invalid$1("concepts");
|
|
526
|
+
const { conceptId, scheduleState, stageIndex, dueAtMs, lastSeenAtMs, consecutiveMisses, advisorySuccesses, needsSupport, recommendationKind, readiness } = fields;
|
|
527
|
+
if (!identifier(conceptId)) return invalid$1("conceptId");
|
|
528
|
+
if (scheduleState !== "unobserved" && scheduleState !== "learning" && scheduleState !== "reviewing" && scheduleState !== "review_ready") return invalid$1("scheduleState");
|
|
529
|
+
if (stageIndex !== null && !integer(stageIndex, 0, LIMITS.intervals - 1)) return invalid$1("stageIndex");
|
|
530
|
+
if (!nullableInstant(dueAtMs)) return failure("INVALID_TIMESTAMP", "dueAtMs");
|
|
531
|
+
if (!nullableInstant(lastSeenAtMs) || lastSeenAtMs !== null && lastSeenAtMs > evaluatedAtMs) return failure("INVALID_TIMESTAMP", "lastSeenAtMs");
|
|
532
|
+
if (!count(consecutiveMisses) || !count(advisorySuccesses) || consecutiveMisses + advisorySuccesses > LIMITS.distinctEvents) return invalid$1("advisorySuccesses");
|
|
533
|
+
if (typeof needsSupport !== "boolean") return invalid$1("needsSupport");
|
|
534
|
+
if (recommendationKind !== "ordinary" && recommendationKind !== "delayed_retrieval" && recommendationKind !== "transfer" && recommendationKind !== "support") return invalid$1("recommendationKind");
|
|
535
|
+
if (readiness !== "unknown" && readiness !== "developing" && readiness !== "review_ready") return invalid$1("readiness");
|
|
536
|
+
if ((scheduleState === "reviewing" || scheduleState === "review_ready") !== (stageIndex !== null) || scheduleState === "unobserved" !== (lastSeenAtMs === null) || scheduleState === "review_ready" !== (readiness === "review_ready") || recommendationKind === "support" !== needsSupport || stageIndex !== null && dueAtMs === null || dueAtMs !== null && lastSeenAtMs === null) return invalid$1("concepts");
|
|
537
|
+
if (budget && !budget.consume(conceptId, scheduleState, recommendationKind, readiness)) return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength);
|
|
538
|
+
const reasons = readReasons(fields.reasons, remaining, budget);
|
|
539
|
+
if (!reasons.ok) return reasons;
|
|
540
|
+
const base = {
|
|
541
|
+
conceptId,
|
|
542
|
+
scheduleState,
|
|
543
|
+
stageIndex,
|
|
544
|
+
dueAtMs,
|
|
545
|
+
lastSeenAtMs,
|
|
546
|
+
consecutiveMisses: consecutiveMisses + 0,
|
|
547
|
+
advisorySuccesses: advisorySuccesses + 0,
|
|
548
|
+
needsSupport,
|
|
549
|
+
recommendationKind,
|
|
550
|
+
readiness,
|
|
551
|
+
reasons: reasons.value
|
|
552
|
+
};
|
|
553
|
+
if (!Object.hasOwn(fields, "candidate")) return success(Object.freeze(base));
|
|
554
|
+
const candidate = readCandidate(fields.candidate, evaluatedAtMs, remaining - reasons.value.length, budget);
|
|
555
|
+
return candidate.ok ? success(Object.freeze({
|
|
556
|
+
...base,
|
|
557
|
+
candidate: candidate.value
|
|
558
|
+
})) : candidate;
|
|
559
|
+
}
|
|
560
|
+
/** Validate closed result shapes and bounded derived values, not evidence or replay correctness. */
|
|
561
|
+
function validateReviewResult(input, allowUnorderedConcepts = false, budget) {
|
|
562
|
+
const fields = record(input, [
|
|
563
|
+
"identity",
|
|
564
|
+
"concepts",
|
|
565
|
+
"appliedEventIds",
|
|
566
|
+
"controlEventIds",
|
|
567
|
+
"lifecycleReasons"
|
|
568
|
+
]);
|
|
569
|
+
if (!fields) return invalid$1("review");
|
|
570
|
+
const identity = validateProjectionIdentity(fields.identity);
|
|
571
|
+
if (!identity.ok) return identity;
|
|
572
|
+
if (budget && !budget.consume(identity.value.algorithmVersion, identity.value.scopeId)) return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength);
|
|
573
|
+
const applied = readIds(fields.appliedEventIds, "appliedEventIds", budget);
|
|
574
|
+
if (!applied.ok) return applied;
|
|
575
|
+
const controls = readIds(fields.controlEventIds, "controlEventIds", budget);
|
|
576
|
+
if (!controls.ok) return controls;
|
|
577
|
+
if ((/* @__PURE__ */ new Set([...applied.value, ...controls.value])).size > LIMITS.distinctEvents) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.distinctEvents);
|
|
578
|
+
const length = arrayLength(fields.concepts);
|
|
579
|
+
if (length !== null && length > LIMITS.concepts) return failure("RESOURCE_LIMIT_EXCEEDED", "concepts", LIMITS.concepts);
|
|
580
|
+
const entries = array(fields.concepts, LIMITS.concepts);
|
|
581
|
+
if (!entries) return invalid$1("concepts");
|
|
582
|
+
const lifecycle = readReasons(fields.lifecycleReasons, maxReasons, budget);
|
|
583
|
+
if (!lifecycle.ok) return lifecycle;
|
|
584
|
+
let remaining = maxReasons - lifecycle.value.length;
|
|
585
|
+
const concepts = [];
|
|
586
|
+
let previousId = null;
|
|
587
|
+
const seen = /* @__PURE__ */ new Set();
|
|
588
|
+
for (const entry of entries) {
|
|
589
|
+
const result = readConcept(entry, identity.value.evaluatedAtMs, remaining, budget);
|
|
590
|
+
if (!result.ok) return result;
|
|
591
|
+
const concept = result.value;
|
|
592
|
+
if (seen.has(concept.conceptId) || !allowUnorderedConcepts && previousId !== null && concept.conceptId <= previousId) return invalid$1("conceptId");
|
|
593
|
+
seen.add(concept.conceptId);
|
|
594
|
+
previousId = concept.conceptId;
|
|
595
|
+
remaining -= concept.reasons.length + (concept.candidate?.reasons.length ?? 0);
|
|
596
|
+
concepts.push(concept);
|
|
597
|
+
}
|
|
598
|
+
return success(Object.freeze({
|
|
599
|
+
identity: identity.value,
|
|
600
|
+
concepts: Object.freeze(concepts),
|
|
601
|
+
appliedEventIds: applied.value,
|
|
602
|
+
controlEventIds: controls.value,
|
|
603
|
+
lifecycleReasons: lifecycle.value
|
|
604
|
+
}));
|
|
605
|
+
}
|
|
606
|
+
// src/validation/priority.ts
|
|
607
|
+
function validateRankingReview(policy, scopeId, input, nowMs, budget) {
|
|
608
|
+
if (!identifier(scopeId)) return failure("INVALID_EVENT", "scopeId");
|
|
609
|
+
if (!isInstant(nowMs)) return failure("INVALID_TIMESTAMP", "nowMs");
|
|
610
|
+
const { scheduling } = policy;
|
|
611
|
+
if (!budget.consume(scopeId) || !budget.consumePolicy(policy)) return failure("RESOURCE_LIMIT_EXCEEDED", "policy", LIMITS.aggregateStringLength);
|
|
612
|
+
const review = validateReviewResult(input, true, budget);
|
|
613
|
+
if (!review.ok) return review;
|
|
614
|
+
const { identity, concepts } = review.value;
|
|
615
|
+
if (identity.scopeId !== scopeId) return failure("SCOPE_MISMATCH", "scopeId");
|
|
616
|
+
if (identity.policyIdentity !== policyIdentity(policy)) return failure("POLICY_MISMATCH", "policyIdentity");
|
|
617
|
+
if (identity.evaluatedAtMs !== nowMs) return failure("REBUILD_REQUIRED", "evaluatedAtMs");
|
|
618
|
+
const lastStage = policy.scheduling.intervalsDays.length - 1;
|
|
619
|
+
for (const concept of concepts) {
|
|
620
|
+
const expectedSupport = concept.consecutiveMisses > 0 && concept.stageIndex === lastStage && scheduling.longProbeAction === "support" || concept.consecutiveMisses >= scheduling.supportAfterMisses;
|
|
621
|
+
if (concept.needsSupport !== expectedSupport || !expectedSupport && (concept.recommendationKind === "transfer" !== (concept.scheduleState === "review_ready") || concept.recommendationKind === "delayed_retrieval" !== (concept.scheduleState !== "review_ready" && concept.stageIndex === lastStage)) || concept.consecutiveMisses > 0 && concept.stageIndex !== null && (concept.stageIndex !== lastStage || scheduling.longProbeAction === "restart") || concept.stageIndex !== null && concept.stageIndex > lastStage || concept.scheduleState === "review_ready" && concept.stageIndex !== lastStage || concept.candidate !== void 0 !== (policy.eligibility !== void 0) || concept.dueAtMs === null && (concept.needsSupport || concept.consecutiveMisses !== 0 || concept.advisorySuccesses !== 0) || concept.stageIndex !== null && concept.advisorySuccesses === 0 || concept.dueAtMs !== null && concept.advisorySuccesses + concept.consecutiveMisses === 0) return failure("INVALID_EVENT", "concepts");
|
|
622
|
+
}
|
|
623
|
+
return review;
|
|
624
|
+
}
|
|
625
|
+
function validateRankingLimit(input) {
|
|
626
|
+
if (input === void 0) return success(LIMITS.concepts);
|
|
627
|
+
return integer(input, 0, LIMITS.concepts) ? success(input + 0) : failure("INVALID_EVENT", "limit");
|
|
628
|
+
}
|
|
629
|
+
function validateRelations(input, concepts, budget) {
|
|
630
|
+
if (input === void 0) return success([]);
|
|
631
|
+
const length = arrayLength(input);
|
|
632
|
+
if (length !== null && length > LIMITS.relations) return failure("RESOURCE_LIMIT_EXCEEDED", "relations", LIMITS.relations);
|
|
633
|
+
const entries = array(input, LIMITS.relations);
|
|
634
|
+
if (!entries) return failure("INVALID_RELATION", "relations");
|
|
635
|
+
const relations = [];
|
|
636
|
+
for (const entry of entries) {
|
|
637
|
+
const fields = record(entry, [
|
|
638
|
+
"kind",
|
|
639
|
+
"fromConceptId",
|
|
640
|
+
"toConceptId"
|
|
641
|
+
]);
|
|
642
|
+
if (!fields) return failure("INVALID_RELATION", "relations");
|
|
643
|
+
const { kind, fromConceptId, toConceptId } = fields;
|
|
644
|
+
if (kind !== "prerequisite" && kind !== "confusable" || !identifier(fromConceptId) || !identifier(toConceptId) || fromConceptId === toConceptId || !concepts.has(fromConceptId) || !concepts.has(toConceptId)) return failure("INVALID_RELATION", "relations");
|
|
645
|
+
if (!budget.consume(kind, fromConceptId, toConceptId)) return failure("RESOURCE_LIMIT_EXCEEDED", "relations", LIMITS.aggregateStringLength);
|
|
646
|
+
relations.push({
|
|
647
|
+
kind,
|
|
648
|
+
fromConceptId,
|
|
649
|
+
toConceptId
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
return success(relations);
|
|
653
|
+
}
|
|
654
|
+
// src/validation/string-budget.ts
|
|
655
|
+
var StringBudget = class {
|
|
656
|
+
total = 0;
|
|
657
|
+
consumeLength(length) {
|
|
658
|
+
this.total += length;
|
|
659
|
+
return this.total <= LIMITS.aggregateStringLength;
|
|
660
|
+
}
|
|
661
|
+
consume(...values) {
|
|
662
|
+
for (const value of values) if (!this.consumeLength(value.length)) return false;
|
|
663
|
+
return true;
|
|
664
|
+
}
|
|
665
|
+
consumePolicy(policy) {
|
|
666
|
+
const { scheduling, eligibility } = policy;
|
|
667
|
+
return this.consume(policy.algorithmVersion, policy.policyId, policy.policyVersion, scheduling.longProbeAction, scheduling.dateArithmetic) && (scheduling.dateArithmetic !== "local_calendar_days" || this.consume(scheduling.calendarProfile.zoneId, scheduling.calendarProfile.rulesVersion)) && (!eligibility || this.consume(eligibility.eligibilityPolicyVersion, eligibility.onFailure, eligibility.onNonqualifying));
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
// src/priority/features.ts
|
|
671
|
+
const dayMs = 864e5;
|
|
672
|
+
const capDays = 3650;
|
|
673
|
+
const capMs = capDays * dayMs;
|
|
674
|
+
function overdueDays(nowMs, dueAtMs) {
|
|
675
|
+
if (nowMs >= -863968464e7 && dueAtMs <= nowMs - capMs) return capDays;
|
|
676
|
+
return Math.floor((nowMs - dueAtMs) / dayMs);
|
|
677
|
+
}
|
|
678
|
+
function dueRecommendation(concept, dueAtMs, nowMs, relation, weights) {
|
|
679
|
+
const features = Object.freeze({
|
|
680
|
+
overdue: overdueDays(nowMs, dueAtMs),
|
|
681
|
+
support: concept.needsSupport ? 1 : 0,
|
|
682
|
+
relation,
|
|
683
|
+
stage: concept.stageIndex === null ? 0 : concept.stageIndex + 1
|
|
684
|
+
});
|
|
685
|
+
const score = features.overdue * (weights?.overdue ?? 0) + features.support * (weights?.support ?? 0) + features.relation * (weights?.relation ?? 0) + features.stage * (weights?.stage ?? 0);
|
|
686
|
+
const reasons = [
|
|
687
|
+
{
|
|
688
|
+
code: "OVERDUE_DAYS",
|
|
689
|
+
value: features.overdue
|
|
690
|
+
},
|
|
691
|
+
{
|
|
692
|
+
code: "SUPPORT_NEEDED",
|
|
693
|
+
value: features.support
|
|
694
|
+
},
|
|
695
|
+
{
|
|
696
|
+
code: "RELATED_DUE",
|
|
697
|
+
value: features.relation
|
|
698
|
+
},
|
|
699
|
+
{
|
|
700
|
+
code: "REVIEW_STAGE",
|
|
701
|
+
value: features.stage
|
|
702
|
+
}
|
|
703
|
+
];
|
|
704
|
+
return Object.freeze({
|
|
705
|
+
conceptId: concept.conceptId,
|
|
706
|
+
dueAtMs,
|
|
707
|
+
recommendationKind: concept.recommendationKind,
|
|
708
|
+
score,
|
|
709
|
+
features,
|
|
710
|
+
reasons: Object.freeze(reasons.map((reason) => Object.freeze(reason)))
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
// src/priority/relations.ts
|
|
714
|
+
function add(index, from, to) {
|
|
715
|
+
const existing = index.get(from);
|
|
716
|
+
if (!existing) {
|
|
717
|
+
index.set(from, /* @__PURE__ */ new Set([to]));
|
|
718
|
+
return true;
|
|
719
|
+
}
|
|
720
|
+
if (existing.has(to)) return false;
|
|
721
|
+
existing.add(to);
|
|
722
|
+
return true;
|
|
723
|
+
}
|
|
724
|
+
function relatedDueCounts(concepts, due, relations) {
|
|
725
|
+
const outgoing = /* @__PURE__ */ new Map();
|
|
726
|
+
const indegree = /* @__PURE__ */ new Map();
|
|
727
|
+
const neighbors = /* @__PURE__ */ new Map();
|
|
728
|
+
for (const { kind, fromConceptId: from, toConceptId: to } of relations) {
|
|
729
|
+
if (kind === "prerequisite" && add(outgoing, from, to)) indegree.set(to, (indegree.get(to) ?? 0) + 1);
|
|
730
|
+
if (due.has(from) && due.has(to)) {
|
|
731
|
+
add(neighbors, from, to);
|
|
732
|
+
if (kind === "confusable") add(neighbors, to, from);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
const queue = [...concepts].filter((id) => !indegree.has(id));
|
|
736
|
+
let visited = 0;
|
|
737
|
+
for (const id of queue) {
|
|
738
|
+
visited += 1;
|
|
739
|
+
for (const dependent of outgoing.get(id) ?? []) {
|
|
740
|
+
const remaining = (indegree.get(dependent) ?? 0) - 1;
|
|
741
|
+
indegree.set(dependent, remaining);
|
|
742
|
+
if (remaining === 0) queue.push(dependent);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (visited !== concepts.size) return failure("INVALID_RELATION", "relations");
|
|
746
|
+
const counts = /* @__PURE__ */ new Map();
|
|
747
|
+
for (const [id, related] of neighbors) counts.set(id, Math.min(1e3, related.size));
|
|
748
|
+
return success(counts);
|
|
749
|
+
}
|
|
750
|
+
// src/priority/rank.ts
|
|
751
|
+
function scheduleDue(inputPolicy, scopeId, inputReview, nowMs, relations, limit) {
|
|
752
|
+
const policy = validatePolicy(inputPolicy);
|
|
753
|
+
if (!policy.ok) return policy;
|
|
754
|
+
const budget = new StringBudget();
|
|
755
|
+
const review = validateRankingReview(policy.value, scopeId, inputReview, nowMs, budget);
|
|
756
|
+
if (!review.ok) return review;
|
|
757
|
+
const maximum = validateRankingLimit(limit);
|
|
758
|
+
if (!maximum.ok) return maximum;
|
|
759
|
+
const clock = review.value.identity.evaluatedAtMs;
|
|
760
|
+
const concepts = new Set(review.value.concepts.map((concept) => concept.conceptId));
|
|
761
|
+
const due = new Set(review.value.concepts.filter((concept) => concept.dueAtMs !== null && concept.dueAtMs <= clock).map((concept) => concept.conceptId));
|
|
762
|
+
const edges = validateRelations(relations, concepts, budget);
|
|
763
|
+
if (!edges.ok) return edges;
|
|
764
|
+
const counts = relatedDueCounts(concepts, due, edges.value);
|
|
765
|
+
if (!counts.ok) return counts;
|
|
766
|
+
const ranked = [];
|
|
767
|
+
for (const concept of review.value.concepts) if (concept.dueAtMs !== null && concept.dueAtMs <= clock) ranked.push(dueRecommendation(concept, concept.dueAtMs, clock, counts.value.get(concept.conceptId) ?? 0, policy.value.priority));
|
|
768
|
+
ranked.sort((left, right) => {
|
|
769
|
+
if (left.score !== right.score) return right.score - left.score;
|
|
770
|
+
if (left.dueAtMs !== right.dueAtMs) return left.dueAtMs < right.dueAtMs ? -1 : 1;
|
|
771
|
+
return left.conceptId < right.conceptId ? -1 : left.conceptId > right.conceptId ? 1 : 0;
|
|
772
|
+
});
|
|
773
|
+
return success(Object.freeze(ranked.slice(0, maximum.value)));
|
|
774
|
+
}
|
|
775
|
+
// src/validation/clock.ts
|
|
776
|
+
function validateClock(nowMs) {
|
|
777
|
+
return isInstant(nowMs) ? success(nowMs + 0) : failure("INVALID_TIMESTAMP", "nowMs");
|
|
778
|
+
}
|
|
779
|
+
// src/validation/events.ts
|
|
780
|
+
const envelope = [
|
|
781
|
+
"schemaVersion",
|
|
782
|
+
"scopeId",
|
|
783
|
+
"eventId",
|
|
784
|
+
"sequence",
|
|
785
|
+
"atMs",
|
|
786
|
+
"kind"
|
|
787
|
+
];
|
|
788
|
+
const concept = [...envelope, "conceptId"];
|
|
789
|
+
const evidence = [
|
|
790
|
+
"sessionId",
|
|
791
|
+
"outcome",
|
|
792
|
+
"fresh",
|
|
793
|
+
"hints",
|
|
794
|
+
"ladder",
|
|
795
|
+
"eligibilityPolicyVersion"
|
|
796
|
+
];
|
|
797
|
+
const maxInteger = Number.MAX_SAFE_INTEGER;
|
|
798
|
+
function invalid(field) {
|
|
799
|
+
return failure("INVALID_EVENT", field);
|
|
800
|
+
}
|
|
801
|
+
function credited(fields) {
|
|
802
|
+
const { sessionId, outcome, fresh, hints, ladder, eligibilityPolicyVersion } = fields;
|
|
803
|
+
if (!identifier(sessionId)) return invalid("sessionId");
|
|
804
|
+
if (!identifier(eligibilityPolicyVersion)) return invalid("eligibilityPolicyVersion");
|
|
805
|
+
if (outcome !== "pass" && outcome !== "fail") return invalid("outcome");
|
|
806
|
+
if (typeof fresh !== "boolean") return invalid("fresh");
|
|
807
|
+
if (!integer(hints, 0, LIMITS.weight)) return invalid("hints");
|
|
808
|
+
if (!integer(ladder, 0, LIMITS.weight)) return invalid("ladder");
|
|
809
|
+
return success(Object.freeze({
|
|
810
|
+
sessionId,
|
|
811
|
+
outcome,
|
|
812
|
+
fresh,
|
|
813
|
+
hints: hints + 0,
|
|
814
|
+
ladder: ladder + 0,
|
|
815
|
+
eligibilityPolicyVersion
|
|
816
|
+
}));
|
|
817
|
+
}
|
|
818
|
+
function eventFields(value) {
|
|
819
|
+
if (value === null || typeof value !== "object") return null;
|
|
820
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, "kind");
|
|
821
|
+
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) return null;
|
|
822
|
+
switch (descriptor.value) {
|
|
823
|
+
case "practice_observation": return record(value, [
|
|
824
|
+
...concept,
|
|
825
|
+
"sessionId",
|
|
826
|
+
"outcome"
|
|
827
|
+
], [
|
|
828
|
+
"fresh",
|
|
829
|
+
"hints",
|
|
830
|
+
"ladder"
|
|
831
|
+
]);
|
|
832
|
+
case "eligible_credited_retrieval": return record(value, [
|
|
833
|
+
...concept,
|
|
834
|
+
...evidence,
|
|
835
|
+
"creditDecisionId",
|
|
836
|
+
"decisionVersion"
|
|
837
|
+
]);
|
|
838
|
+
case "credited_decision_correction": return record(value, [
|
|
839
|
+
...concept,
|
|
840
|
+
"supersedesDecisionId",
|
|
841
|
+
"replacementDecisionId",
|
|
842
|
+
"decisionVersion",
|
|
843
|
+
"replacement",
|
|
844
|
+
"reasonCode"
|
|
845
|
+
]);
|
|
846
|
+
case "credited_decision_revocation": return record(value, [
|
|
847
|
+
...concept,
|
|
848
|
+
"supersedesDecisionId",
|
|
849
|
+
"reasonCode"
|
|
850
|
+
]);
|
|
851
|
+
case "review_event_deletion": return record(value, [...concept, "targetEventId"]);
|
|
852
|
+
case "review_scope_deletion": return record(value, [...envelope, "throughSequence"]);
|
|
853
|
+
default: return null;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function validateEvent(value, expectedScope) {
|
|
857
|
+
const fields = eventFields(value);
|
|
858
|
+
if (!fields) return invalid("events");
|
|
859
|
+
const { schemaVersion, scopeId, eventId, sequence, atMs, kind, conceptId } = fields;
|
|
860
|
+
if (schemaVersion !== 1) return failure("UNSUPPORTED_VERSION", "schemaVersion");
|
|
861
|
+
if (!identifier(scopeId)) return invalid("scopeId");
|
|
862
|
+
if (!identifier(eventId)) return invalid("eventId");
|
|
863
|
+
if (scopeId !== expectedScope) return failure("SCOPE_MISMATCH", "scopeId");
|
|
864
|
+
if (!integer(sequence, 0, maxInteger)) return invalid("sequence");
|
|
865
|
+
if (!isInstant(atMs)) return failure("INVALID_TIMESTAMP", "atMs");
|
|
866
|
+
const base = {
|
|
867
|
+
schemaVersion: 1,
|
|
868
|
+
scopeId,
|
|
869
|
+
eventId,
|
|
870
|
+
sequence: sequence + 0,
|
|
871
|
+
atMs: atMs + 0
|
|
872
|
+
};
|
|
873
|
+
if (kind === "review_scope_deletion") {
|
|
874
|
+
const { throughSequence } = fields;
|
|
875
|
+
if (!integer(throughSequence, 0, sequence - 1)) return invalid("throughSequence");
|
|
876
|
+
return success(Object.freeze({
|
|
877
|
+
...base,
|
|
878
|
+
kind,
|
|
879
|
+
throughSequence: throughSequence + 0
|
|
880
|
+
}));
|
|
881
|
+
}
|
|
882
|
+
if (!identifier(conceptId)) return invalid("conceptId");
|
|
883
|
+
const scoped = {
|
|
884
|
+
...base,
|
|
885
|
+
conceptId
|
|
886
|
+
};
|
|
887
|
+
switch (kind) {
|
|
888
|
+
case "practice_observation": {
|
|
889
|
+
const { sessionId, outcome, fresh, hints, ladder } = fields;
|
|
890
|
+
if (!identifier(sessionId)) return invalid("sessionId");
|
|
891
|
+
if (outcome !== "pass" && outcome !== "fail" && outcome !== "not_observed") return invalid("outcome");
|
|
892
|
+
if (Object.hasOwn(fields, "fresh") && typeof fresh !== "boolean") return invalid("fresh");
|
|
893
|
+
if (Object.hasOwn(fields, "hints") && !integer(hints, 0, LIMITS.weight)) return invalid("hints");
|
|
894
|
+
if (Object.hasOwn(fields, "ladder") && !integer(ladder, 0, LIMITS.weight)) return invalid("ladder");
|
|
895
|
+
return success(Object.freeze({
|
|
896
|
+
...scoped,
|
|
897
|
+
kind,
|
|
898
|
+
sessionId,
|
|
899
|
+
outcome,
|
|
900
|
+
...typeof fresh === "boolean" ? { fresh } : {},
|
|
901
|
+
...typeof hints === "number" ? { hints: hints + 0 } : {},
|
|
902
|
+
...typeof ladder === "number" ? { ladder: ladder + 0 } : {}
|
|
903
|
+
}));
|
|
904
|
+
}
|
|
905
|
+
case "eligible_credited_retrieval": {
|
|
906
|
+
const { creditDecisionId, decisionVersion } = fields;
|
|
907
|
+
if (!identifier(creditDecisionId)) return invalid("creditDecisionId");
|
|
908
|
+
if (decisionVersion !== 1) return invalid("decisionVersion");
|
|
909
|
+
const metadata = credited(fields);
|
|
910
|
+
if (!metadata.ok) return metadata;
|
|
911
|
+
return success(Object.freeze({
|
|
912
|
+
...scoped,
|
|
913
|
+
kind,
|
|
914
|
+
...metadata.value,
|
|
915
|
+
creditDecisionId,
|
|
916
|
+
decisionVersion
|
|
917
|
+
}));
|
|
918
|
+
}
|
|
919
|
+
case "credited_decision_correction": {
|
|
920
|
+
const { supersedesDecisionId, replacementDecisionId, decisionVersion, reasonCode } = fields;
|
|
921
|
+
if (!identifier(supersedesDecisionId) || !identifier(replacementDecisionId) || supersedesDecisionId === replacementDecisionId || !integer(decisionVersion, 2, maxInteger)) return failure("INVALID_CORRECTION", "decisionVersion");
|
|
922
|
+
if (!label(reasonCode)) return invalid("reasonCode");
|
|
923
|
+
const replacementFields = record(fields.replacement, evidence);
|
|
924
|
+
if (!replacementFields) return invalid("replacement");
|
|
925
|
+
const replacement = credited(replacementFields);
|
|
926
|
+
if (!replacement.ok) return replacement;
|
|
927
|
+
return success(Object.freeze({
|
|
928
|
+
...scoped,
|
|
929
|
+
kind,
|
|
930
|
+
supersedesDecisionId,
|
|
931
|
+
replacementDecisionId,
|
|
932
|
+
decisionVersion,
|
|
933
|
+
reasonCode,
|
|
934
|
+
replacement: replacement.value
|
|
935
|
+
}));
|
|
936
|
+
}
|
|
937
|
+
case "credited_decision_revocation": {
|
|
938
|
+
const { supersedesDecisionId, reasonCode } = fields;
|
|
939
|
+
if (!identifier(supersedesDecisionId)) return invalid("supersedesDecisionId");
|
|
940
|
+
if (!label(reasonCode)) return invalid("reasonCode");
|
|
941
|
+
return success(Object.freeze({
|
|
942
|
+
...scoped,
|
|
943
|
+
kind,
|
|
944
|
+
supersedesDecisionId,
|
|
945
|
+
reasonCode
|
|
946
|
+
}));
|
|
947
|
+
}
|
|
948
|
+
case "review_event_deletion": {
|
|
949
|
+
const { targetEventId } = fields;
|
|
950
|
+
if (!identifier(targetEventId)) return invalid("targetEventId");
|
|
951
|
+
return success(Object.freeze({
|
|
952
|
+
...scoped,
|
|
953
|
+
kind,
|
|
954
|
+
targetEventId
|
|
955
|
+
}));
|
|
956
|
+
}
|
|
957
|
+
default: return invalid("kind");
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
function stringLength(event) {
|
|
961
|
+
let length = 0;
|
|
962
|
+
for (const value of Object.values(event)) if (typeof value === "string") length += value.length;
|
|
963
|
+
if (event.kind === "credited_decision_correction") {
|
|
964
|
+
for (const value of Object.values(event.replacement)) if (typeof value === "string") length += value.length;
|
|
965
|
+
}
|
|
966
|
+
return length;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Validate inert JSON for a single caller-bound scope. Identical events collapse to their first
|
|
970
|
+
* occurrence; the result is not chronological and does not establish admission or lifecycle validity.
|
|
971
|
+
*/
|
|
972
|
+
function validateEvents(scopeId, events) {
|
|
973
|
+
return validateEventsWithBudget(scopeId, events, new StringBudget());
|
|
974
|
+
}
|
|
975
|
+
function validateEventsWithBudget(scopeId, events, budget) {
|
|
976
|
+
if (!identifier(scopeId)) return invalid("scopeId");
|
|
977
|
+
if (!budget.consume(scopeId)) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength);
|
|
978
|
+
const length = arrayLength(events);
|
|
979
|
+
if (length !== null && length > LIMITS.rawEvents) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.rawEvents);
|
|
980
|
+
const entries = array(events, LIMITS.rawEvents);
|
|
981
|
+
if (!entries) return invalid("events");
|
|
982
|
+
const validated = normalizeEventEntries(scopeId, entries, budget);
|
|
983
|
+
return validated.ok ? deduplicateEvents(validated.value) : validated;
|
|
984
|
+
}
|
|
985
|
+
function normalizeEventEntries(scopeId, entries, budget) {
|
|
986
|
+
const validated = [];
|
|
987
|
+
for (const entry of entries) {
|
|
988
|
+
const result = validateEvent(entry, scopeId);
|
|
989
|
+
if (!result.ok) return result;
|
|
990
|
+
if (!budget.consumeLength(stringLength(result.value))) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength);
|
|
991
|
+
validated.push(result.value);
|
|
992
|
+
}
|
|
993
|
+
return success(Object.freeze(validated));
|
|
994
|
+
}
|
|
995
|
+
function deduplicateEvents(validated) {
|
|
996
|
+
const identities = /* @__PURE__ */ new Map();
|
|
997
|
+
const sequences = /* @__PURE__ */ new Set();
|
|
998
|
+
const concepts = /* @__PURE__ */ new Set();
|
|
999
|
+
const distinct = [];
|
|
1000
|
+
for (const event of validated) {
|
|
1001
|
+
const identity = eventIdentity(event);
|
|
1002
|
+
const prior = identities.get(event.eventId);
|
|
1003
|
+
if (prior !== void 0) {
|
|
1004
|
+
if (prior !== identity) return failure("EVENT_ID_CONFLICT", "eventId");
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
if (sequences.has(event.sequence)) return failure("SEQUENCE_CONFLICT", "sequence");
|
|
1008
|
+
if (distinct.length >= LIMITS.distinctEvents) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.distinctEvents);
|
|
1009
|
+
if ("conceptId" in event) {
|
|
1010
|
+
concepts.add(event.conceptId);
|
|
1011
|
+
if (concepts.size > LIMITS.concepts) return failure("RESOURCE_LIMIT_EXCEEDED", "conceptId", LIMITS.concepts);
|
|
1012
|
+
}
|
|
1013
|
+
identities.set(event.eventId, identity);
|
|
1014
|
+
sequences.add(event.sequence);
|
|
1015
|
+
distinct.push(event);
|
|
1016
|
+
}
|
|
1017
|
+
return success(Object.freeze(distinct));
|
|
1018
|
+
}
|
|
1019
|
+
// src/explanation/reasons.ts
|
|
1020
|
+
function lifecycleReasons(controls) {
|
|
1021
|
+
const codes = {
|
|
1022
|
+
credited_decision_correction: "CREDIT_CORRECTION",
|
|
1023
|
+
credited_decision_revocation: "CREDIT_REVOCATION",
|
|
1024
|
+
review_event_deletion: "EVENT_DELETION",
|
|
1025
|
+
review_scope_deletion: "SCOPE_DELETION"
|
|
1026
|
+
};
|
|
1027
|
+
return Object.freeze(controls.map((control) => normalizedReason(codes[control.kind])));
|
|
1028
|
+
}
|
|
1029
|
+
function normalizedReason(code, value) {
|
|
1030
|
+
return Object.freeze({
|
|
1031
|
+
code,
|
|
1032
|
+
...value === void 0 ? {} : { value: value + 0 }
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
// src/readiness/qualification.ts
|
|
1036
|
+
function isEligibleObservation(observation) {
|
|
1037
|
+
return observation.kind === "eligible_credited_retrieval";
|
|
1038
|
+
}
|
|
1039
|
+
function classifyQualification(policy, observation) {
|
|
1040
|
+
if (observation.eligibilityPolicyVersion !== policy.eligibilityPolicyVersion) return policy.onNonqualifying;
|
|
1041
|
+
if (observation.outcome === "fail") return policy.onFailure;
|
|
1042
|
+
if (policy.requireFresh && !observation.fresh || observation.hints > policy.maxHints || observation.ladder < policy.minLadder) return policy.onNonqualifying;
|
|
1043
|
+
return "qualifying";
|
|
1044
|
+
}
|
|
1045
|
+
// src/readiness/candidate.ts
|
|
1046
|
+
function projectCandidate(policy, observations) {
|
|
1047
|
+
let qualifyingSuccesses = 0;
|
|
1048
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
1049
|
+
let firstQualifyingAtMs = null;
|
|
1050
|
+
let lastQualifyingAtMs = null;
|
|
1051
|
+
let qualifyingSpanMs = 0;
|
|
1052
|
+
const reasons = [];
|
|
1053
|
+
for (const observation of observations) {
|
|
1054
|
+
const classification = classifyQualification(policy, observation);
|
|
1055
|
+
if (classification === "reset") {
|
|
1056
|
+
qualifyingSuccesses = 0;
|
|
1057
|
+
sessions.clear();
|
|
1058
|
+
firstQualifyingAtMs = null;
|
|
1059
|
+
lastQualifyingAtMs = null;
|
|
1060
|
+
qualifyingSpanMs = 0;
|
|
1061
|
+
reasons.push({ code: "CANDIDATE_RESET" });
|
|
1062
|
+
} else if (classification === "ignore") reasons.push({ code: "CANDIDATE_IGNORE" });
|
|
1063
|
+
else {
|
|
1064
|
+
qualifyingSuccesses += 1;
|
|
1065
|
+
sessions.add(observation.sessionId);
|
|
1066
|
+
firstQualifyingAtMs ??= observation.atMs;
|
|
1067
|
+
lastQualifyingAtMs = observation.atMs;
|
|
1068
|
+
qualifyingSpanMs = lastQualifyingAtMs - firstQualifyingAtMs;
|
|
1069
|
+
if (!Number.isSafeInteger(qualifyingSpanMs) || qualifyingSpanMs > 864e13) return failure("INVALID_TIMESTAMP", "qualifyingSpanMs");
|
|
1070
|
+
reasons.push({
|
|
1071
|
+
code: "QUALIFYING_SUCCESS",
|
|
1072
|
+
value: qualifyingSuccesses
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
const ready = qualifyingSuccesses >= policy.minSuccesses && sessions.size >= policy.minSessions && qualifyingSpanMs >= policy.minSpanMs;
|
|
1077
|
+
return success(Object.freeze({
|
|
1078
|
+
readiness: observations.length === 0 ? "unknown" : ready ? "candidate_ready" : "developing",
|
|
1079
|
+
qualifyingSuccesses,
|
|
1080
|
+
distinctSessions: sessions.size,
|
|
1081
|
+
firstQualifyingAtMs,
|
|
1082
|
+
lastQualifyingAtMs,
|
|
1083
|
+
qualifyingSpanMs,
|
|
1084
|
+
reasons: Object.freeze(reasons.map((reason) => Object.freeze(reason)))
|
|
1085
|
+
}));
|
|
1086
|
+
}
|
|
1087
|
+
// src/scheduling/intervals.ts
|
|
1088
|
+
function dueAfter(policy, anchorMs, days) {
|
|
1089
|
+
return policy.dateArithmetic === "local_calendar_days" ? addCalendarDays(anchorMs, days, policy.calendarProfile) : addElapsedDays(anchorMs, days);
|
|
1090
|
+
}
|
|
1091
|
+
// src/scheduling/transitions.ts
|
|
1092
|
+
function projectPractice(policy, observations) {
|
|
1093
|
+
let scheduleState = "unobserved";
|
|
1094
|
+
let stageIndex = null;
|
|
1095
|
+
let dueAtMs = null;
|
|
1096
|
+
let lastSeenAtMs = null;
|
|
1097
|
+
let consecutiveMisses = 0;
|
|
1098
|
+
let advisorySuccesses = 0;
|
|
1099
|
+
let forcedSupport = false;
|
|
1100
|
+
let observed = false;
|
|
1101
|
+
const reasons = [];
|
|
1102
|
+
const lastStage = policy.intervalsDays.length - 1;
|
|
1103
|
+
for (const observation of observations) {
|
|
1104
|
+
lastSeenAtMs = observation.atMs;
|
|
1105
|
+
if (observation.outcome === "not_observed") {
|
|
1106
|
+
if (scheduleState === "unobserved") scheduleState = "learning";
|
|
1107
|
+
reasons.push({ code: "NO_OBSERVATION" });
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
observed = true;
|
|
1111
|
+
let days;
|
|
1112
|
+
if (observation.outcome === "pass") {
|
|
1113
|
+
advisorySuccesses += 1;
|
|
1114
|
+
consecutiveMisses = 0;
|
|
1115
|
+
forcedSupport = false;
|
|
1116
|
+
if (stageIndex === null) {
|
|
1117
|
+
stageIndex = 0;
|
|
1118
|
+
scheduleState = "reviewing";
|
|
1119
|
+
days = policy.intervalsDays[0];
|
|
1120
|
+
reasons.push({
|
|
1121
|
+
code: "FIRST_PASS",
|
|
1122
|
+
value: stageIndex
|
|
1123
|
+
});
|
|
1124
|
+
} else if (dueAtMs !== null && observation.atMs < dueAtMs) {
|
|
1125
|
+
reasons.push({
|
|
1126
|
+
code: "EARLY_PASS",
|
|
1127
|
+
value: stageIndex
|
|
1128
|
+
});
|
|
1129
|
+
continue;
|
|
1130
|
+
} else {
|
|
1131
|
+
reasons.push({
|
|
1132
|
+
code: "DUE_PASS",
|
|
1133
|
+
value: stageIndex
|
|
1134
|
+
});
|
|
1135
|
+
if (stageIndex === lastStage) {
|
|
1136
|
+
scheduleState = "review_ready";
|
|
1137
|
+
days = policy.maintenanceDays;
|
|
1138
|
+
} else {
|
|
1139
|
+
stageIndex += 1;
|
|
1140
|
+
days = policy.intervalsDays[stageIndex];
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
} else {
|
|
1144
|
+
consecutiveMisses += 1;
|
|
1145
|
+
reasons.push({
|
|
1146
|
+
code: "MISS",
|
|
1147
|
+
value: consecutiveMisses
|
|
1148
|
+
});
|
|
1149
|
+
if (stageIndex !== lastStage || policy.longProbeAction === "restart") {
|
|
1150
|
+
stageIndex = null;
|
|
1151
|
+
scheduleState = "learning";
|
|
1152
|
+
reasons.push({ code: "RESTART" });
|
|
1153
|
+
} else if (policy.longProbeAction === "support") {
|
|
1154
|
+
forcedSupport = true;
|
|
1155
|
+
reasons.push({ code: "FORCED_SUPPORT" });
|
|
1156
|
+
}
|
|
1157
|
+
if (consecutiveMisses >= policy.supportAfterMisses) reasons.push({
|
|
1158
|
+
code: "SUPPORT_THRESHOLD",
|
|
1159
|
+
value: consecutiveMisses
|
|
1160
|
+
});
|
|
1161
|
+
days = policy.retryDays;
|
|
1162
|
+
}
|
|
1163
|
+
const due = dueAfter(policy, observation.atMs, days);
|
|
1164
|
+
if (!due.ok) return due;
|
|
1165
|
+
dueAtMs = due.value;
|
|
1166
|
+
if (scheduleState === "review_ready") reasons.push({ code: "MAINTENANCE" });
|
|
1167
|
+
else if (stageIndex === lastStage) reasons.push({ code: "DELAYED_PROBE" });
|
|
1168
|
+
}
|
|
1169
|
+
const needsSupport = forcedSupport || consecutiveMisses >= policy.supportAfterMisses;
|
|
1170
|
+
return success(Object.freeze({
|
|
1171
|
+
scheduleState,
|
|
1172
|
+
stageIndex,
|
|
1173
|
+
dueAtMs,
|
|
1174
|
+
lastSeenAtMs,
|
|
1175
|
+
consecutiveMisses,
|
|
1176
|
+
advisorySuccesses,
|
|
1177
|
+
needsSupport,
|
|
1178
|
+
recommendationKind: needsSupport ? "support" : scheduleState === "review_ready" ? "transfer" : stageIndex === lastStage ? "delayed_retrieval" : "ordinary",
|
|
1179
|
+
readiness: !observed ? "unknown" : scheduleState === "review_ready" ? "review_ready" : "developing",
|
|
1180
|
+
reasons: Object.freeze(reasons.map((reason) => Object.freeze(reason)))
|
|
1181
|
+
}));
|
|
1182
|
+
}
|
|
1183
|
+
// src/events/corrections.ts
|
|
1184
|
+
function replace(root, control) {
|
|
1185
|
+
return Object.freeze({
|
|
1186
|
+
...root,
|
|
1187
|
+
...control.replacement,
|
|
1188
|
+
eventId: control.eventId,
|
|
1189
|
+
creditDecisionId: control.replacementDecisionId,
|
|
1190
|
+
decisionVersion: control.decisionVersion
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
function resolveCreditChains(events, nowMs) {
|
|
1194
|
+
const decisions = /* @__PURE__ */ new Map();
|
|
1195
|
+
const chains = [];
|
|
1196
|
+
const rootByEventId = /* @__PURE__ */ new Map();
|
|
1197
|
+
for (const event of events) {
|
|
1198
|
+
if (event.kind === "eligible_credited_retrieval") {
|
|
1199
|
+
if (decisions.has(event.creditDecisionId)) return failure("INVALID_CORRECTION", "creditDecisionId");
|
|
1200
|
+
const chain = {
|
|
1201
|
+
root: event,
|
|
1202
|
+
active: event
|
|
1203
|
+
};
|
|
1204
|
+
chains.push(chain);
|
|
1205
|
+
decisions.set(event.creditDecisionId, chain);
|
|
1206
|
+
rootByEventId.set(event.eventId, event.eventId);
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
if (event.kind !== "credited_decision_correction" && event.kind !== "credited_decision_revocation") continue;
|
|
1210
|
+
if (event.atMs > nowMs) return failure("INVALID_TIMESTAMP", "atMs");
|
|
1211
|
+
const chain = decisions.get(event.supersedesDecisionId);
|
|
1212
|
+
if (!chain) return failure("MISSING_CORRECTION_TARGET", "supersedesDecisionId");
|
|
1213
|
+
const active = chain.active;
|
|
1214
|
+
if (active === null || chain.root.conceptId !== event.conceptId || active.creditDecisionId !== event.supersedesDecisionId) return failure("INVALID_CORRECTION", "supersedesDecisionId");
|
|
1215
|
+
rootByEventId.set(event.eventId, chain.root.eventId);
|
|
1216
|
+
if (event.kind === "credited_decision_revocation") {
|
|
1217
|
+
chain.active = null;
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
if (decisions.has(event.replacementDecisionId)) return failure("INVALID_CORRECTION", "replacementDecisionId");
|
|
1221
|
+
if (active.decisionVersion === Number.MAX_SAFE_INTEGER || event.decisionVersion !== active.decisionVersion + 1) return failure("INVALID_CORRECTION", "decisionVersion");
|
|
1222
|
+
chain.active = replace(chain.root, event);
|
|
1223
|
+
decisions.set(event.replacementDecisionId, chain);
|
|
1224
|
+
}
|
|
1225
|
+
const active = [];
|
|
1226
|
+
for (const chain of chains) if (chain.active !== null) active.push({
|
|
1227
|
+
rootEventId: chain.root.eventId,
|
|
1228
|
+
observation: chain.active
|
|
1229
|
+
});
|
|
1230
|
+
return success({
|
|
1231
|
+
active,
|
|
1232
|
+
rootByEventId
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
// src/events/deletions.ts
|
|
1236
|
+
function resolveDeletions(events, creditRoots) {
|
|
1237
|
+
const byEventId = new Map(events.map((event) => [event.eventId, event]));
|
|
1238
|
+
const rootEventIds = /* @__PURE__ */ new Set();
|
|
1239
|
+
let throughSequence = -1;
|
|
1240
|
+
for (const event of events) {
|
|
1241
|
+
if (event.kind === "review_scope_deletion") {
|
|
1242
|
+
throughSequence = Math.max(throughSequence, event.throughSequence);
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
if (event.kind !== "review_event_deletion") continue;
|
|
1246
|
+
const target = byEventId.get(event.targetEventId);
|
|
1247
|
+
if (target === void 0) {
|
|
1248
|
+
rootEventIds.add(event.targetEventId);
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1251
|
+
if (target.kind === "review_event_deletion" || target.kind === "review_scope_deletion" || target.conceptId !== event.conceptId) return failure("INVALID_EVENT", "targetEventId");
|
|
1252
|
+
rootEventIds.add(creditRoots.get(target.eventId) ?? target.eventId);
|
|
1253
|
+
}
|
|
1254
|
+
return success({
|
|
1255
|
+
rootEventIds,
|
|
1256
|
+
throughSequence
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
// src/events/ordering.ts
|
|
1260
|
+
function compareNumber(left, right) {
|
|
1261
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
1262
|
+
}
|
|
1263
|
+
function compareSequence(left, right) {
|
|
1264
|
+
return compareNumber(left.sequence, right.sequence);
|
|
1265
|
+
}
|
|
1266
|
+
function compareObservations(left, right) {
|
|
1267
|
+
return compareNumber(left.atMs, right.atMs) || compareNumber(left.sequence, right.sequence) || (left.eventId < right.eventId ? -1 : left.eventId > right.eventId ? 1 : 0);
|
|
1268
|
+
}
|
|
1269
|
+
// src/replay/watermark.ts
|
|
1270
|
+
function historyWatermark(events) {
|
|
1271
|
+
return canonicalJson(events);
|
|
1272
|
+
}
|
|
1273
|
+
// src/replay/reconcile.ts
|
|
1274
|
+
/** Internal full-history reconciliation. No policy, projection or admission decision is produced. */
|
|
1275
|
+
function reconcile(scopeId, input, nowMs, budget = new StringBudget()) {
|
|
1276
|
+
if (!identifier(scopeId)) return failure("INVALID_EVENT", "scopeId");
|
|
1277
|
+
const validated = validateEventsWithBudget(scopeId, input, budget);
|
|
1278
|
+
if (!validated.ok) return validated;
|
|
1279
|
+
const clock = validateClock(nowMs);
|
|
1280
|
+
if (!clock.ok) return clock;
|
|
1281
|
+
return reconcileValidated(scopeId, validated.value, clock.value);
|
|
1282
|
+
}
|
|
1283
|
+
function reconcileValidated(scopeId, validated, evaluatedAtMs) {
|
|
1284
|
+
const events = [...validated].sort(compareSequence);
|
|
1285
|
+
const credit = resolveCreditChains(events, evaluatedAtMs);
|
|
1286
|
+
if (!credit.ok) return credit;
|
|
1287
|
+
const deletion = resolveDeletions(events, credit.value.rootByEventId);
|
|
1288
|
+
if (!deletion.ok) return deletion;
|
|
1289
|
+
const { rootEventIds, throughSequence } = deletion.value;
|
|
1290
|
+
const conceptIds = /* @__PURE__ */ new Set();
|
|
1291
|
+
const observations = [];
|
|
1292
|
+
const controls = [];
|
|
1293
|
+
function append(rootEventId, observation) {
|
|
1294
|
+
if (!rootEventIds.has(rootEventId) && observation.sequence > throughSequence && observation.atMs <= evaluatedAtMs) observations.push(observation);
|
|
1295
|
+
}
|
|
1296
|
+
for (const event of events) {
|
|
1297
|
+
if ("conceptId" in event) conceptIds.add(event.conceptId);
|
|
1298
|
+
if (event.kind === "practice_observation") append(event.eventId, event);
|
|
1299
|
+
else if (event.kind !== "eligible_credited_retrieval") controls.push(event);
|
|
1300
|
+
}
|
|
1301
|
+
for (const { rootEventId, observation } of credit.value.active) append(rootEventId, observation);
|
|
1302
|
+
observations.sort(compareObservations);
|
|
1303
|
+
return success(Object.freeze({
|
|
1304
|
+
scopeId,
|
|
1305
|
+
evaluatedAtMs,
|
|
1306
|
+
conceptIds: Object.freeze([...conceptIds].sort()),
|
|
1307
|
+
observations: Object.freeze(observations),
|
|
1308
|
+
appliedEventIds: Object.freeze(observations.map((event) => event.eventId)),
|
|
1309
|
+
controls: Object.freeze(controls),
|
|
1310
|
+
controlEventIds: Object.freeze(controls.map((event) => event.eventId)),
|
|
1311
|
+
watermark: historyWatermark(events)
|
|
1312
|
+
}));
|
|
1313
|
+
}
|
|
1314
|
+
// src/replay/rebuild.ts
|
|
1315
|
+
function rebuildReview(inputPolicy, scopeId, events, nowMs) {
|
|
1316
|
+
const policy = validatePolicy(inputPolicy);
|
|
1317
|
+
if (!policy.ok) return policy;
|
|
1318
|
+
const budget = new StringBudget();
|
|
1319
|
+
if (!budget.consumePolicy(policy.value)) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength);
|
|
1320
|
+
const history = reconcile(scopeId, events, nowMs, budget);
|
|
1321
|
+
return history.ok ? projectReview(policy.value, history.value) : history;
|
|
1322
|
+
}
|
|
1323
|
+
function rebuildValidated(policy, scopeId, events, nowMs) {
|
|
1324
|
+
const history = reconcileValidated(scopeId, events, nowMs);
|
|
1325
|
+
return history.ok ? projectReview(policy, history.value) : history;
|
|
1326
|
+
}
|
|
1327
|
+
function projectReview(policy, history) {
|
|
1328
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1329
|
+
for (const observation of history.observations) {
|
|
1330
|
+
const group = grouped.get(observation.conceptId);
|
|
1331
|
+
if (group) group.push(observation);
|
|
1332
|
+
else grouped.set(observation.conceptId, [observation]);
|
|
1333
|
+
}
|
|
1334
|
+
const concepts = [];
|
|
1335
|
+
for (const conceptId of history.conceptIds) {
|
|
1336
|
+
const observations = grouped.get(conceptId) ?? [];
|
|
1337
|
+
const practice = projectPractice(policy.scheduling, observations);
|
|
1338
|
+
if (!practice.ok) return practice;
|
|
1339
|
+
if (policy.eligibility) {
|
|
1340
|
+
const candidate = projectCandidate(policy.eligibility, observations.filter(isEligibleObservation));
|
|
1341
|
+
if (!candidate.ok) return candidate;
|
|
1342
|
+
concepts.push(Object.freeze({
|
|
1343
|
+
conceptId,
|
|
1344
|
+
...practice.value,
|
|
1345
|
+
candidate: candidate.value
|
|
1346
|
+
}));
|
|
1347
|
+
} else concepts.push(Object.freeze({
|
|
1348
|
+
conceptId,
|
|
1349
|
+
...practice.value
|
|
1350
|
+
}));
|
|
1351
|
+
}
|
|
1352
|
+
return success(Object.freeze({
|
|
1353
|
+
identity: Object.freeze({
|
|
1354
|
+
schemaVersion: policy.schemaVersion,
|
|
1355
|
+
algorithmVersion: policy.algorithmVersion,
|
|
1356
|
+
scopeId: history.scopeId,
|
|
1357
|
+
policyIdentity: policyIdentity(policy),
|
|
1358
|
+
evaluatedAtMs: history.evaluatedAtMs,
|
|
1359
|
+
watermark: history.watermark
|
|
1360
|
+
}),
|
|
1361
|
+
concepts: Object.freeze(concepts),
|
|
1362
|
+
appliedEventIds: history.appliedEventIds,
|
|
1363
|
+
controlEventIds: history.controlEventIds,
|
|
1364
|
+
lifecycleReasons: lifecycleReasons(history.controls)
|
|
1365
|
+
}));
|
|
1366
|
+
}
|
|
1367
|
+
function evaluateReadiness(inputPolicy, scopeId, conceptId, events, nowMs) {
|
|
1368
|
+
const policy = validatePolicy(inputPolicy);
|
|
1369
|
+
if (!policy.ok) return policy;
|
|
1370
|
+
if (!identifier(conceptId)) return failure("INVALID_EVENT", "conceptId");
|
|
1371
|
+
const budget = new StringBudget();
|
|
1372
|
+
if (!budget.consumePolicy(policy.value) || !budget.consume(conceptId)) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength);
|
|
1373
|
+
const history = reconcile(scopeId, events, nowMs, budget);
|
|
1374
|
+
if (!history.ok) return history;
|
|
1375
|
+
if (!policy.value.eligibility) return success(null);
|
|
1376
|
+
return projectCandidate(policy.value.eligibility, history.value.observations.filter(isEligibleObservation).filter((observation) => observation.conceptId === conceptId));
|
|
1377
|
+
}
|
|
1378
|
+
// src/replay/advance.ts
|
|
1379
|
+
function advanceReview(inputPolicy, scopeId, previousIdentity, previousEvents, appendedEvents, nowMs) {
|
|
1380
|
+
const policy = validatePolicy(inputPolicy);
|
|
1381
|
+
if (!policy.ok) return policy;
|
|
1382
|
+
const clock = validateClock(nowMs);
|
|
1383
|
+
if (!clock.ok) return clock;
|
|
1384
|
+
const previous = validateProjectionIdentity(previousIdentity);
|
|
1385
|
+
if (!previous.ok || previous.value.scopeId !== scopeId || previous.value.policyIdentity !== policyIdentity(policy.value)) return failure("REBUILD_REQUIRED", "previousIdentity");
|
|
1386
|
+
const previousClock = previous.value.evaluatedAtMs;
|
|
1387
|
+
if (previousClock > clock.value) return failure("REBUILD_REQUIRED", "evaluatedAtMs");
|
|
1388
|
+
const priorLength = arrayLength(previousEvents);
|
|
1389
|
+
const addedLength = arrayLength(appendedEvents);
|
|
1390
|
+
if (priorLength === null) return failure("REBUILD_REQUIRED", "previousEvents");
|
|
1391
|
+
if (addedLength === null) return failure("INVALID_EVENT", "appendedEvents");
|
|
1392
|
+
if (priorLength + addedLength > LIMITS.rawEvents) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.rawEvents);
|
|
1393
|
+
const prior = array(previousEvents, LIMITS.rawEvents);
|
|
1394
|
+
const added = array(appendedEvents, LIMITS.rawEvents);
|
|
1395
|
+
if (!prior) return failure("REBUILD_REQUIRED", "previousEvents");
|
|
1396
|
+
if (!added) return failure("INVALID_EVENT", "appendedEvents");
|
|
1397
|
+
const scope = previous.value.scopeId;
|
|
1398
|
+
const budget = new StringBudget();
|
|
1399
|
+
if (!budget.consumePolicy(policy.value) || !budget.consume(scope, previous.value.algorithmVersion, previous.value.scopeId)) return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.aggregateStringLength);
|
|
1400
|
+
const normalizedPrior = normalizeEventEntries(scope, prior, budget);
|
|
1401
|
+
if (!normalizedPrior.ok) return normalizedPrior.errors[0]?.code === "RESOURCE_LIMIT_EXCEEDED" ? normalizedPrior : failure("REBUILD_REQUIRED", "previousEvents");
|
|
1402
|
+
const normalizedAdded = normalizeEventEntries(scope, added, budget);
|
|
1403
|
+
if (!normalizedAdded.ok) return normalizedAdded;
|
|
1404
|
+
const distinctPrior = deduplicateEvents(normalizedPrior.value);
|
|
1405
|
+
if (!distinctPrior.ok) return distinctPrior.errors[0]?.code === "RESOURCE_LIMIT_EXCEEDED" ? distinctPrior : failure("REBUILD_REQUIRED", "previousEvents");
|
|
1406
|
+
const distinctCombined = deduplicateEvents([...normalizedPrior.value, ...normalizedAdded.value]);
|
|
1407
|
+
if (!distinctCombined.ok) return distinctCombined;
|
|
1408
|
+
const reconstructed = rebuildValidated(policy.value, scope, distinctPrior.value, previousClock);
|
|
1409
|
+
if (!reconstructed.ok || reconstructed.value.identity.watermark !== previous.value.watermark) return failure("REBUILD_REQUIRED", "previousEvents");
|
|
1410
|
+
return rebuildValidated(policy.value, scope, distinctCombined.value, clock.value);
|
|
1411
|
+
}
|
|
1412
|
+
// src/replay/explain.ts
|
|
1413
|
+
/** Explain a successful replay value; this does not revalidate evidence or run scheduling. */
|
|
1414
|
+
function explainReview(input) {
|
|
1415
|
+
const result = validateReviewResult(input, false, new StringBudget());
|
|
1416
|
+
if (!result.ok) return result;
|
|
1417
|
+
const concepts = result.value.concepts.map((concept) => Object.freeze({
|
|
1418
|
+
conceptId: concept.conceptId,
|
|
1419
|
+
practiceReasons: concept.reasons,
|
|
1420
|
+
...concept.candidate ? { candidateReasons: concept.candidate.reasons } : {}
|
|
1421
|
+
}));
|
|
1422
|
+
return success(Object.freeze({
|
|
1423
|
+
lifecycleReasons: result.value.lifecycleReasons,
|
|
1424
|
+
concepts: Object.freeze(concepts)
|
|
1425
|
+
}));
|
|
1426
|
+
}
|
|
1427
|
+
export { advanceReview, evaluateReadiness, explainReview, rebuildReview, scheduleDue, validateEvents, validatePolicy };
|