@unblocklabs/unblock-memory 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +19 -18
  2. package/dist/src/analysis.js +1 -1
  3. package/dist/src/cluster-review.d.ts +2 -0
  4. package/dist/src/cluster-review.js +3 -3
  5. package/dist/src/config.d.ts +9 -6
  6. package/dist/src/config.js +31 -20
  7. package/dist/src/curation.d.ts +1 -1
  8. package/dist/src/decision-client.d.ts +39 -0
  9. package/dist/src/decision-client.js +74 -0
  10. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  11. package/dist/src/decision-ranking.js +154 -0
  12. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  13. package/dist/src/decision-review.js +192 -0
  14. package/dist/src/diagnostics.d.ts +5 -5
  15. package/dist/src/emotion-baselines.d.ts +28 -3
  16. package/dist/src/emotion-baselines.js +309 -113
  17. package/dist/src/evidence-review.d.ts +22 -8
  18. package/dist/src/evidence-review.js +4 -4
  19. package/dist/src/extraction-chunk.d.ts +3 -0
  20. package/dist/src/extraction-chunk.js +23 -5
  21. package/dist/src/extraction-model.d.ts +2 -0
  22. package/dist/src/extraction-model.js +73 -48
  23. package/dist/src/extraction-runtime.d.ts +3 -1
  24. package/dist/src/extraction-runtime.js +43 -16
  25. package/dist/src/extraction-source.d.ts +1 -1
  26. package/dist/src/extraction-source.js +19 -11
  27. package/dist/src/extraction-store.d.ts +28 -3
  28. package/dist/src/extraction-store.js +145 -23
  29. package/dist/src/extraction-worker.d.ts +1 -0
  30. package/dist/src/extraction-worker.js +246 -93
  31. package/dist/src/inside-out-runtime.js +41 -29
  32. package/dist/src/inside-out-store.d.ts +2 -2
  33. package/dist/src/inside-out-store.js +110 -69
  34. package/dist/src/inside-out.d.ts +10 -9
  35. package/dist/src/inside-out.js +190 -105
  36. package/dist/src/manager.d.ts +22 -9
  37. package/dist/src/manager.js +275 -169
  38. package/dist/src/memory-search.d.ts +4 -2
  39. package/dist/src/memory-search.js +5 -5
  40. package/dist/src/memory-whisperer.d.ts +1 -1
  41. package/dist/src/memory-whisperer.js +189 -127
  42. package/dist/src/my-turn.d.ts +1 -1
  43. package/dist/src/my-turn.js +87 -68
  44. package/dist/src/people-background.d.ts +4 -0
  45. package/dist/src/people-background.js +29 -6
  46. package/dist/src/people-dossier-review.d.ts +20 -8
  47. package/dist/src/people-dossier-review.js +11 -8
  48. package/dist/src/people-hooks.js +127 -22
  49. package/dist/src/people-learning-cron.d.ts +1 -1
  50. package/dist/src/people-learning-cron.js +106 -57
  51. package/dist/src/people-learning-inventory.d.ts +1 -0
  52. package/dist/src/people-learning-inventory.js +281 -171
  53. package/dist/src/people-learning-prompt.js +1 -1
  54. package/dist/src/people-learning-runtime.d.ts +1 -1
  55. package/dist/src/people-learning-runtime.js +423 -204
  56. package/dist/src/people-learning-store.d.ts +27 -4
  57. package/dist/src/people-learning-store.js +312 -96
  58. package/dist/src/people-primer-tool.js +8 -6
  59. package/dist/src/people-primer.d.ts +3 -1
  60. package/dist/src/people-primer.js +61 -44
  61. package/dist/src/people-store.d.ts +18 -21
  62. package/dist/src/people-store.js +186 -63
  63. package/dist/src/people-tools.js +136 -92
  64. package/dist/src/plugin.js +16 -16
  65. package/dist/src/quality-audit.d.ts +2 -0
  66. package/dist/src/quality-audit.js +8 -7
  67. package/dist/src/query-generator.d.ts +1 -1
  68. package/dist/src/query-generator.js +15 -8
  69. package/dist/src/response-audit.d.ts +1 -1
  70. package/dist/src/response-audit.js +76 -43
  71. package/dist/src/response-episodes.d.ts +1 -1
  72. package/dist/src/response-episodes.js +12 -17
  73. package/dist/src/response-judge.d.ts +151 -145
  74. package/dist/src/response-judge.js +535 -204
  75. package/dist/src/response-reviews.d.ts +29 -1
  76. package/dist/src/response-reviews.js +110 -13
  77. package/dist/src/response-runtime.js +8 -8
  78. package/dist/src/response-stages.d.ts +50 -53
  79. package/dist/src/response-stages.js +10 -4
  80. package/dist/src/response-store.d.ts +7 -6
  81. package/dist/src/response-store.js +332 -210
  82. package/dist/src/response-text.d.ts +2 -0
  83. package/dist/src/response-text.js +182 -36
  84. package/dist/src/review-tools.d.ts +8 -2
  85. package/dist/src/review-tools.js +18 -18
  86. package/dist/src/runtime.d.ts +7 -4
  87. package/dist/src/runtime.js +624 -98
  88. package/dist/src/safety-whisperer.d.ts +2 -2
  89. package/dist/src/safety-whisperer.js +88 -71
  90. package/dist/src/session-sync.d.ts +3 -1
  91. package/dist/src/session-sync.js +200 -95
  92. package/dist/src/skill-whisperer.d.ts +1 -1
  93. package/dist/src/skill-whisperer.js +52 -30
  94. package/dist/src/training-gate.d.ts +8 -21
  95. package/dist/src/training-gate.js +32 -35
  96. package/dist/src/training-judge.d.ts +9 -16
  97. package/dist/src/training-judge.js +5 -5
  98. package/dist/src/training-queries.d.ts +13 -8
  99. package/dist/src/training-queries.js +370 -228
  100. package/dist/src/training-retrieval.d.ts +14 -24
  101. package/dist/src/training-retrieval.js +182 -136
  102. package/dist/src/training-runtime.d.ts +3 -0
  103. package/dist/src/training-runtime.js +76 -18
  104. package/dist/src/training-store.d.ts +18 -3
  105. package/dist/src/training-store.js +138 -50
  106. package/dist/src/training.js +8 -11
  107. package/dist/src/whisperer-context.d.ts +14 -0
  108. package/dist/src/whisperer-context.js +22 -1
  109. package/docs/configuration.md +76 -63
  110. package/docs/extraction.md +9 -7
  111. package/docs/memory-training.md +7 -6
  112. package/docs/people-learning.md +2 -2
  113. package/docs/peoplesql.md +6 -6
  114. package/docs/response-audit.md +10 -8
  115. package/docs/retrieval.md +40 -37
  116. package/openclaw.plugin.json +40 -26
  117. package/package.json +3 -2
  118. package/skills/memory-curator/SKILL.md +1 -1
  119. package/skills/people-whisperer/SKILL.md +1 -1
  120. package/dist/src/typesafe-client.d.ts +0 -30
  121. package/dist/src/typesafe-client.js +0 -92
  122. package/dist/src/typesafe-review.js +0 -154
  123. package/dist/src/typesafe.js +0 -147
@@ -1,9 +1,10 @@
1
1
  import { collectTraining } from "./training.js";
2
2
  import { TRAINING_GATE_THRESHOLD } from "./training-gate.js";
3
- import { resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
3
+ import { classifyDecisionFailure, resolveDecisionCredential } from "./decision-client.js";
4
4
  import { trainingTeacher, trainingTeacherMessage, trainingTeacherPrompt, TRAINING_TEACHER_MODEL, TRAINING_TEACHER_VERSION } from "./training-models.js";
5
5
  import { historicalTrainingSource, HistoricalCorpusUnavailableError, TRAINING_RETRIEVAL_VERSION, TRAINING_SEARCH_OPTIONS } from "./training-retrieval.js";
6
6
  import { contextJudgeRequest, judgeTrainingPassage, CONTEXT_JUDGE_VERSION } from "./training-judge.js";
7
+ import { memoryJudgeVersion } from "./decision-ranking.js";
7
8
  import { jsonHash } from "./json-hash.js";
8
9
  const LANES = ["lex", "vec"];
9
10
  const SELECTION_VERSION = "independent-lanes-top3-mean-v2";
@@ -46,13 +47,16 @@ async function checkpoint(store, step, result, operation) {
46
47
  throw error;
47
48
  const hostCode = error && typeof error === "object" && "code" in error && typeof error.code === "string" &&
48
49
  /^LLM_[A-Z_]+$/u.test(error.code) ? error.code : undefined;
49
- const status = error instanceof HistoricalCorpusUnavailableError || hostCode === "LLM_COMPLETION_NOT_AUTHORIZED" ||
50
- (error instanceof TypeSafeRequestError && error.code === "http_error" &&
51
- error.status !== undefined && error.status >= 400 && error.status < 500) ? "failed" : "ambiguous";
52
- store.finishStep(step.stage, step.id, attempt, { status,
53
- error: error instanceof TypeSafeRequestError && error.code === "http_error" ?
54
- `http_${error.status}` : error instanceof HistoricalCorpusUnavailableError ? "historical_corpus_unavailable" :
55
- hostCode ?? "request_or_response_uncertain" });
50
+ const classified = classifyDecisionFailure(error);
51
+ const status = error instanceof HistoricalCorpusUnavailableError || hostCode === "LLM_COMPLETION_NOT_AUTHORIZED"
52
+ ? "failed"
53
+ : classified.status;
54
+ store.finishStep(step.stage, step.id, attempt, {
55
+ status,
56
+ error: error instanceof HistoricalCorpusUnavailableError
57
+ ? "historical_corpus_unavailable"
58
+ : hostCode ?? classified.error,
59
+ });
56
60
  result[status]++;
57
61
  return;
58
62
  }
@@ -60,9 +64,8 @@ async function checkpoint(store, step, result, operation) {
60
64
  result.completed++;
61
65
  return value;
62
66
  }
63
- function save(store, step, value) {
64
- const attempt = store.startStep(step.stage, step.id, step.request);
65
- store.finishStep(step.stage, step.id, attempt, { result: value });
67
+ function save(store, step, value, clearReview) {
68
+ store.saveStep(step.stage, step.id, step.request, value, clearReview);
66
69
  return value;
67
70
  }
68
71
  async function drain(tasks) {
@@ -154,259 +157,396 @@ export function selectTrainingQueries(queries) {
154
157
  };
155
158
  return { lex: winner("lex"), vec: winner("vec") };
156
159
  }
157
- export async function evaluateTrainingQueries(source, store, config, runtime, options, createSearch) {
158
- bounds(options);
159
- const corpus = config.corpora.find(c => c.kind === "sessions");
160
- if (!corpus)
161
- throw new Error("Training retrieval requires a configured sessions corpus");
162
- const refreshed = collectTraining(source, store, { existingOnly: true });
163
- const result = { ...summary(), retrievals: 0, evaluated: 0, awaitingTeacher: 0 };
164
- const concurrency = options.concurrency ?? TRAINING_EVALUATION_CONCURRENCY;
165
- let historicalSource;
166
- let key, teacher;
167
- const apiKey = () => key ??= resolveTypeSafeApiKey(config.typesafe).then(value => {
160
+ function stepBelongsToJudge(info, judgeVersion) {
161
+ if (!info)
162
+ return false;
163
+ if (info.stage === "evaluate" || info.stage === "score")
164
+ return info.request.judgeVersion === judgeVersion;
165
+ if (info.stage === "judge") {
166
+ return typeof info.request.identity === "string" &&
167
+ jsonHash([judgeVersion, info.request.request]) === info.request.identity;
168
+ }
169
+ return true;
170
+ }
171
+ function isCorpusScopedRetrievalStep(info) {
172
+ return !!info && info.stage === "retrieve" && typeof info.request.corpusHash === "string";
173
+ }
174
+ /** Admission holds: defer corpus-scoped retrieval failures until the current corpusHash is known. */
175
+ function blockedStepsForExample(store, reviews, judgeVersion, corpusHash) {
176
+ return reviews.flatMap(review => {
177
+ if (!("steps" in review.details))
178
+ return [];
179
+ if (review.reason === "evaluation-unresolved") {
180
+ if (review.scope && review.scope !== "__legacy__" && review.scope !== judgeVersion)
181
+ return [];
182
+ return review.details.steps.filter(id => {
183
+ const info = store.stepScope(id);
184
+ if (!info || info.status === "pending" || info.status === "complete" || !stepBelongsToJudge(info, judgeVersion))
185
+ return false;
186
+ if (corpusHash === undefined)
187
+ return !isCorpusScopedRetrievalStep(info);
188
+ return isCorpusScopedRetrievalStep(info) && info.request.corpusHash === corpusHash;
189
+ });
190
+ }
191
+ if (corpusHash !== undefined)
192
+ return [];
193
+ return review.details.steps.filter(id => {
194
+ const status = store.stepRecordStatus(id);
195
+ return status !== undefined && status !== "pending" && status !== "complete";
196
+ });
197
+ });
198
+ }
199
+ /** Export holds: any uncleared review row for this judge blocks exporting prior evaluations. */
200
+ function reviewBlocksJudge(store, review, judgeVersion) {
201
+ if (review.reason !== "evaluation-unresolved")
202
+ return true;
203
+ if (review.scope && review.scope !== "__legacy__")
204
+ return review.scope === judgeVersion;
205
+ if (!("steps" in review.details))
206
+ return true;
207
+ return review.details.steps.some(id => stepBelongsToJudge(store.stepScope(id), judgeVersion));
208
+ }
209
+ function legacyUnresolvedMatchesJudge(store, judgeVersion) {
210
+ return (details) => "steps" in details && details.steps.length > 0 && details.steps.every(id => stepBelongsToJudge(store.stepScope(id), judgeVersion));
211
+ }
212
+ function shouldStop(ctx) {
213
+ return ctx.stopped || ctx.result.budgetLimited;
214
+ }
215
+ function hasCallRoom(ctx) {
216
+ if (shouldStop(ctx))
217
+ return false;
218
+ if (ctx.options.maxCalls !== undefined && ctx.result.calls >= ctx.options.maxCalls) {
219
+ ctx.result.budgetLimited = true;
220
+ return false;
221
+ }
222
+ return true;
223
+ }
224
+ function resolveApiKey(ctx) {
225
+ return ctx.key ??= resolveDecisionCredential(ctx.config.decisionModel).then(value => {
168
226
  if (!value)
169
- throw new Error("TypeSafe is disabled or its credential is unavailable");
227
+ throw new Error("Decision model is disabled or its credential is unavailable");
170
228
  return value;
171
229
  });
172
- let stopped = false;
173
- const shouldStop = () => stopped || result.budgetLimited;
174
- const room = () => {
175
- if (shouldStop())
176
- return false;
177
- if (options.maxCalls !== undefined && result.calls >= options.maxCalls) {
178
- result.budgetLimited = true;
179
- return false;
180
- }
181
- return true;
182
- };
183
- const judgments = new Map();
184
- const revisions = new Map();
185
- const reviews = new Map(store.reviews().map(review => [review.sourceId, review]));
186
- const evaluate = async (example) => {
187
- const previousReview = reviews.get(example.id);
188
- if (previousReview && "steps" in previousReview.details) {
189
- const blocked = previousReview.details.steps.filter(id => {
190
- const status = store.stepRecordStatus(id);
191
- return status !== undefined && status !== "pending" && status !== "complete";
192
- });
193
- // A known failed example cannot resolve before manual retry. Do not scan its
194
- // historical corpus or consume the example budget on every invocation.
195
- if (blocked.length) {
196
- result.blocked += blocked.length;
197
- result.flagged++;
198
- return;
230
+ }
231
+ function resolveTeacher(ctx) {
232
+ return ctx.teacher ??= trainingTeacher(ctx.runtime, ctx.source.agentId);
233
+ }
234
+ async function openSnapshot(ctx, timestamp) {
235
+ // By default one source capture serves the whole run; an injected search owns its own capture.
236
+ if (ctx.createSearch)
237
+ return ctx.createSearch(ctx.source.stateDir, ctx.chatTypes, timestamp);
238
+ const sourceForCutoff = await (ctx.historicalSource ??= historicalTrainingSource(ctx.source.stateDir, ctx.chatTypes));
239
+ return sourceForCutoff(timestamp);
240
+ }
241
+ function judgePassageOnce(ctx, input, maxDate, hit) {
242
+ const request = contextJudgeRequest(input, maxDate, hit, ctx.config.decisionModel.model);
243
+ const identity = jsonHash([ctx.judgeVersion, request]);
244
+ let pending = ctx.judgments.get(identity);
245
+ if (!pending) {
246
+ pending = (async () => {
247
+ const step = ctx.store.step("judge", { identity, request });
248
+ if (step.result) {
249
+ ctx.result.cached++;
250
+ return { id: step.id, result: step.result };
199
251
  }
200
- }
201
- const initial = LANES.map(lane => ({ lane, step: store.step("generate", teacherRequest(example, lane)) }));
202
- if (initial.some(({ step }) => !step.result)) {
203
- const blocked = initial.filter(({ step }) => !step.result && step.status !== "pending");
204
- if (blocked.length) {
205
- result.blocked += blocked.length;
206
- result.flagged++;
207
- store.flagReview(example, "generation-unresolved", { steps: blocked.map(({ step }) => step.id) });
252
+ if (step.status !== "pending") {
253
+ ctx.result.blocked++;
254
+ return { id: step.id, result: undefined };
208
255
  }
209
- else
210
- result.awaitingTeacher++;
211
- return;
212
- }
213
- if (options.maxExamples !== undefined && result.examples >= options.maxExamples)
214
- return;
215
- store.renew();
216
- let snapshot;
217
- try {
218
- // By default one source capture serves the whole run; an injected search owns its own capture.
219
- snapshot = createSearch
220
- ? await createSearch(source.stateDir, corpus.chatTypes, example.timestamp)
221
- : await (await (historicalSource ??= historicalTrainingSource(source.stateDir, corpus.chatTypes)))(example.timestamp);
222
- }
223
- catch (error) {
224
- if (!(error instanceof HistoricalCorpusUnavailableError))
225
- throw error;
226
- store.flagReview(example, "historical-snapshot-unavailable", { timestamp: example.timestamp });
227
- result.flagged++;
228
- return;
229
- }
256
+ const credential = await resolveApiKey(ctx);
257
+ if (!hasCallRoom(ctx))
258
+ return { id: step.id, result: undefined };
259
+ return { id: step.id, result: await checkpoint(ctx.store, step, ctx.result, () => judgeTrainingPassage(request, credential, ctx.evaluationOptions)) };
260
+ })();
261
+ ctx.judgments.set(identity, pending);
262
+ }
263
+ return pending;
264
+ }
265
+ async function scoreLaneQueries(ctx, example, input, snapshot, lane, round, generation, generationId, problems) {
266
+ return drain(generation.queries.map(async (query) => {
230
267
  try {
231
- const evaluation = store.step("evaluate", { version: SELECTION_VERSION, sourceId: example.id, inputHash: example.inputHash,
232
- timestamp: example.timestamp, teacherIds: initial.map(({ step }) => step.id), corpusHash: snapshot.corpusHash,
233
- retrievalVersion: TRAINING_RETRIEVAL_VERSION, judgeVersion: CONTEXT_JUDGE_VERSION,
234
- options: TRAINING_SEARCH_OPTIONS });
235
- if (evaluation.result) {
236
- result.cached++;
237
- store.clearReview(example.id);
238
- return;
268
+ const score = ctx.store.step("score", { version: SELECTION_VERSION, lane, round, generationId, query,
269
+ sourceId: example.id, corpusHash: snapshot.corpusHash, judgeVersion: ctx.judgeVersion,
270
+ retrievalVersion: TRAINING_RETRIEVAL_VERSION });
271
+ if (score.result) {
272
+ ctx.result.cached++;
273
+ return score.result;
239
274
  }
240
- if (evaluation.status !== "pending") {
241
- result.blocked++;
242
- result.flagged++;
243
- store.flagReview(example, "evaluation-unresolved", { steps: [evaluation.id] });
275
+ if (score.status !== "pending") {
276
+ problems.add(score.id);
277
+ ctx.result.blocked++;
244
278
  return;
245
279
  }
246
- if (shouldStop() || (options.maxExamples !== undefined && result.examples >= options.maxExamples))
280
+ const retrieval = ctx.store.step("retrieve", { version: TRAINING_RETRIEVAL_VERSION, query, lane,
281
+ sourceId: example.id, maxDate: snapshot.maxDate, corpusHash: snapshot.corpusHash, options: TRAINING_SEARCH_OPTIONS });
282
+ if (!retrieval.result && retrieval.status === "pending" && !hasCallRoom(ctx))
247
283
  return;
248
- result.examples++;
249
- if (options.dryRun)
284
+ const retrieved = await checkpoint(ctx.store, retrieval, ctx.result, async () => ({ query, lane, maxDate: snapshot.maxDate,
285
+ corpusHash: snapshot.corpusHash, hits: await snapshot.search(query, lane) }));
286
+ if (!retrieved) {
287
+ problems.add(retrieval.id);
250
288
  return;
251
- const input = JSON.parse(example.inputJson);
252
- const problems = new Set();
253
- const judge = (hit) => {
254
- const request = contextJudgeRequest(input, snapshot.maxDate, hit);
255
- const identity = jsonHash([CONTEXT_JUDGE_VERSION, request]);
256
- let pending = judgments.get(identity);
257
- if (!pending) {
258
- pending = (async () => {
259
- const step = store.step("judge", { identity, request });
260
- if (step.result) {
261
- result.cached++;
262
- return { id: step.id, result: step.result };
263
- }
264
- if (step.status !== "pending") {
265
- result.blocked++;
266
- return { id: step.id, result: undefined };
267
- }
268
- const credential = await apiKey();
269
- if (!room())
270
- return { id: step.id, result: undefined };
271
- return { id: step.id, result: await checkpoint(store, step, result, () => judgeTrainingPassage(request, credential)) };
272
- })();
273
- judgments.set(identity, pending);
274
- }
275
- return pending;
276
- };
277
- const scoreQueries = async (lane, round, generation, generationId) => await drain(generation.queries.map(async (query) => {
278
- try {
279
- const score = store.step("score", { version: SELECTION_VERSION, lane, round, generationId, query,
280
- sourceId: example.id, corpusHash: snapshot.corpusHash, judgeVersion: CONTEXT_JUDGE_VERSION,
281
- retrievalVersion: TRAINING_RETRIEVAL_VERSION });
282
- if (score.result) {
283
- result.cached++;
284
- return score.result;
285
- }
286
- if (score.status !== "pending") {
287
- problems.add(score.id);
288
- result.blocked++;
289
- return;
290
- }
291
- const retrieval = store.step("retrieve", { version: TRAINING_RETRIEVAL_VERSION, query, lane,
292
- sourceId: example.id, maxDate: snapshot.maxDate, corpusHash: snapshot.corpusHash, options: TRAINING_SEARCH_OPTIONS });
293
- if (!retrieval.result && retrieval.status === "pending" && !room())
294
- return;
295
- const retrieved = await checkpoint(store, retrieval, result, async () => ({ query, lane, maxDate: snapshot.maxDate,
296
- corpusHash: snapshot.corpusHash, hits: await snapshot.search(query, lane) }));
297
- if (!retrieved) {
298
- problems.add(retrieval.id);
299
- return;
300
- }
301
- if (!retrieval.result)
302
- result.retrievals++;
303
- const scored = await drain(retrieved.hits.map(judge));
304
- const missing = scored.filter(item => !item.result);
305
- if (missing.length) {
306
- for (const item of missing) {
307
- const record = store.stepRecordStatus(item.id);
308
- if (record && record !== "pending")
309
- problems.add(item.id);
310
- }
311
- return;
312
- }
313
- const probabilities = scored.map(item => item.result.probability);
314
- return save(store, score, { query, lane, round, retrievalId: retrieval.id,
315
- score: trainingQueryScore(probabilities), maxProbability: Math.max(0, ...probabilities), judgments: scored.map(item => item.id) });
316
- }
317
- catch (error) {
318
- stopped = true;
319
- throw error;
320
- }
321
- }));
322
- const lanes = await drain(initial.map(async ({ lane, step }) => {
323
- try {
324
- const first = await scoreQueries(lane, 1, step.result, step.id);
325
- if (first.some(item => !item) || shouldStop())
326
- return;
327
- const feedback = first.map(item => ({ query: item.query, score: item.score }));
328
- // The only feedback sent to Luna is this lane's exact earlier queries and scores.
329
- const revision = store.step("generate", teacherRequest(example, lane, feedback));
330
- let pending = revisions.get(revision.id);
331
- if (!pending) {
332
- pending = (async () => {
333
- if (!revision.result && revision.status === "pending") {
334
- const bytes = Buffer.byteLength(trainingTeacherMessage(input, lane, feedback)) + Buffer.byteLength(trainingTeacherPrompt(lane));
335
- if (!room())
336
- return;
337
- if (result.inputBytes + bytes > (options.maxInputBytes ?? 3_000_000)) {
338
- result.budgetLimited = true;
339
- return;
340
- }
341
- result.inputBytes += bytes;
342
- teacher ??= trainingTeacher(runtime, source.agentId);
343
- }
344
- return checkpoint(store, revision, result, () => teacher(input, lane, feedback));
345
- })();
346
- revisions.set(revision.id, pending);
347
- }
348
- const revised = await pending;
349
- if (!revised) {
350
- if (store.stepRecordStatus(revision.id))
351
- problems.add(revision.id);
352
- return;
353
- }
354
- const second = await scoreQueries(lane, 2, revised, revision.id);
355
- if (second.some(item => !item))
356
- return;
357
- return { teacherIds: [step.id, revision.id], queries: [...first, ...second].filter((item) => !!item) };
358
- }
359
- catch (error) {
360
- stopped = true;
361
- throw error;
289
+ }
290
+ if (!retrieval.result)
291
+ ctx.result.retrievals++;
292
+ const scored = await drain(retrieved.hits.map(hit => judgePassageOnce(ctx, input, snapshot.maxDate, hit)));
293
+ const missing = scored.filter(item => !item.result);
294
+ if (missing.length) {
295
+ for (const item of missing) {
296
+ const record = ctx.store.stepRecordStatus(item.id);
297
+ if (record && record !== "pending")
298
+ problems.add(item.id);
362
299
  }
363
- }));
364
- if (problems.size) {
365
- result.flagged++;
366
- store.flagReview(example, "evaluation-unresolved", { steps: [...problems] });
367
300
  return;
368
301
  }
369
- if (lanes.some(lane => !lane))
370
- return; // Budget pause: completed operations remain reusable.
371
- const queries = lanes.flatMap(lane => lane.queries);
372
- const selected = selectTrainingQueries(queries);
373
- save(store, evaluation, { sourceId: example.id, inputHash: example.inputHash, timestamp: example.timestamp,
374
- corpusHash: snapshot.corpusHash, corpusReport: snapshot.report, teacherIds: lanes.flatMap(lane => lane.teacherIds), queries, selected, review: [] });
375
- store.clearReview(example.id);
376
- result.evaluated++;
302
+ const probabilities = scored.map(item => item.result.probability);
303
+ return save(ctx.store, score, { query, lane, round, retrievalId: retrieval.id,
304
+ score: trainingQueryScore(probabilities), maxProbability: Math.max(0, ...probabilities), judgments: scored.map(item => item.id) });
377
305
  }
378
- finally {
379
- await snapshot.close();
306
+ catch (error) {
307
+ ctx.stopped = true;
308
+ throw error;
309
+ }
310
+ }));
311
+ }
312
+ async function reviseLaneOnce(ctx, example, input, lane, feedback) {
313
+ // The only feedback sent to Luna is this lane's exact earlier queries and scores.
314
+ const revision = ctx.store.step("generate", teacherRequest(example, lane, feedback));
315
+ let pending = ctx.revisions.get(revision.id);
316
+ if (!pending) {
317
+ pending = (async () => {
318
+ if (!revision.result && revision.status === "pending") {
319
+ const bytes = Buffer.byteLength(trainingTeacherMessage(input, lane, feedback)) + Buffer.byteLength(trainingTeacherPrompt(lane));
320
+ if (!hasCallRoom(ctx))
321
+ return;
322
+ if (ctx.result.inputBytes + bytes > (ctx.options.maxInputBytes ?? 3_000_000)) {
323
+ ctx.result.budgetLimited = true;
324
+ return;
325
+ }
326
+ ctx.result.inputBytes += bytes;
327
+ resolveTeacher(ctx);
328
+ }
329
+ return checkpoint(ctx.store, revision, ctx.result, () => ctx.teacher(input, lane, feedback));
330
+ })();
331
+ ctx.revisions.set(revision.id, pending);
332
+ }
333
+ return { id: revision.id, result: await pending };
334
+ }
335
+ async function evaluateExample(ctx, example) {
336
+ const reviews = ctx.reviewsBySource.get(example.id) ?? [];
337
+ const preBlocked = blockedStepsForExample(ctx.store, reviews, ctx.judgeVersion);
338
+ // A known non-retrieval failure for this judge cannot resolve before manual retry.
339
+ // Do not scan its historical corpus or consume the example budget on every invocation.
340
+ if (preBlocked.length) {
341
+ ctx.result.blocked += preBlocked.length;
342
+ ctx.result.flagged++;
343
+ return;
344
+ }
345
+ const initial = LANES.map(lane => ({ lane, step: ctx.store.step("generate", teacherRequest(example, lane)) }));
346
+ if (initial.some(({ step }) => !step.result)) {
347
+ const blocked = initial.filter(({ step }) => !step.result && step.status !== "pending");
348
+ if (blocked.length) {
349
+ ctx.result.blocked += blocked.length;
350
+ ctx.result.flagged++;
351
+ ctx.store.flagReview(example, "generation-unresolved", { steps: blocked.map(({ step }) => step.id) });
352
+ }
353
+ else
354
+ ctx.result.awaitingTeacher++;
355
+ return;
356
+ }
357
+ if (ctx.options.maxExamples !== undefined && ctx.result.examples >= ctx.options.maxExamples)
358
+ return;
359
+ ctx.store.renew();
360
+ let snapshot;
361
+ try {
362
+ snapshot = await openSnapshot(ctx, example.timestamp);
363
+ }
364
+ catch (error) {
365
+ if (!(error instanceof HistoricalCorpusUnavailableError))
366
+ throw error;
367
+ ctx.store.flagReview(example, "historical-snapshot-unavailable", { timestamp: example.timestamp });
368
+ ctx.result.flagged++;
369
+ return;
370
+ }
371
+ try {
372
+ const retrievalBlocked = blockedStepsForExample(ctx.store, reviews, ctx.judgeVersion, snapshot.corpusHash);
373
+ if (retrievalBlocked.length) {
374
+ ctx.result.blocked += retrievalBlocked.length;
375
+ ctx.result.flagged++;
376
+ return;
377
+ }
378
+ const evaluation = ctx.store.step("evaluate", { version: SELECTION_VERSION, sourceId: example.id, inputHash: example.inputHash,
379
+ timestamp: example.timestamp, teacherIds: initial.map(({ step }) => step.id), corpusHash: snapshot.corpusHash,
380
+ retrievalVersion: TRAINING_RETRIEVAL_VERSION, judgeVersion: ctx.judgeVersion,
381
+ options: TRAINING_SEARCH_OPTIONS });
382
+ const clearReview = { sourceId: example.id, scope: ctx.judgeVersion,
383
+ matchesLegacyUnresolved: legacyUnresolvedMatchesJudge(ctx.store, ctx.judgeVersion) };
384
+ if (evaluation.result) {
385
+ ctx.result.cached++;
386
+ ctx.store.clearReview(clearReview.sourceId, clearReview.scope, clearReview.matchesLegacyUnresolved);
387
+ return;
388
+ }
389
+ if (evaluation.status !== "pending") {
390
+ ctx.result.blocked++;
391
+ ctx.result.flagged++;
392
+ ctx.store.flagReview(example, "evaluation-unresolved", { steps: [evaluation.id] }, ctx.judgeVersion);
393
+ return;
394
+ }
395
+ if (shouldStop(ctx) || (ctx.options.maxExamples !== undefined && ctx.result.examples >= ctx.options.maxExamples))
396
+ return;
397
+ ctx.result.examples++;
398
+ if (ctx.options.dryRun)
399
+ return;
400
+ const input = JSON.parse(example.inputJson);
401
+ const problems = new Set();
402
+ const lanes = await drain(initial.map(async ({ lane, step }) => {
403
+ try {
404
+ const first = await scoreLaneQueries(ctx, example, input, snapshot, lane, 1, step.result, step.id, problems);
405
+ if (first.some(item => !item) || shouldStop(ctx))
406
+ return;
407
+ const feedback = first.map(item => ({ query: item.query, score: item.score }));
408
+ const revision = await reviseLaneOnce(ctx, example, input, lane, feedback);
409
+ if (!revision.result) {
410
+ const revisionStatus = ctx.store.stepRecordStatus(revision.id);
411
+ if (revisionStatus && revisionStatus !== "pending")
412
+ problems.add(revision.id);
413
+ return;
414
+ }
415
+ const second = await scoreLaneQueries(ctx, example, input, snapshot, lane, 2, revision.result, revision.id, problems);
416
+ if (second.some(item => !item))
417
+ return;
418
+ return { teacherIds: [step.id, revision.id], queries: [...first, ...second].filter((item) => !!item) };
419
+ }
420
+ catch (error) {
421
+ ctx.stopped = true;
422
+ throw error;
423
+ }
424
+ }));
425
+ if (problems.size) {
426
+ ctx.result.flagged++;
427
+ ctx.store.flagReview(example, "evaluation-unresolved", { steps: [...problems] }, ctx.judgeVersion);
428
+ return;
380
429
  }
430
+ if (lanes.some(lane => !lane))
431
+ return; // Budget pause: completed operations remain reusable.
432
+ const queries = lanes.flatMap(lane => lane.queries);
433
+ const selected = selectTrainingQueries(queries);
434
+ save(ctx.store, evaluation, { sourceId: example.id, inputHash: example.inputHash, timestamp: example.timestamp,
435
+ corpusHash: snapshot.corpusHash, corpusReport: snapshot.report, teacherIds: lanes.flatMap(lane => lane.teacherIds), queries, selected, review: [] }, clearReview);
436
+ ctx.result.evaluated++;
437
+ }
438
+ finally {
439
+ await snapshot.close();
440
+ }
441
+ }
442
+ export async function evaluateTrainingQueries(source, store, config, runtime, options, createSearch) {
443
+ bounds(options);
444
+ const corpus = config.corpora.find(c => c.kind === "sessions");
445
+ if (!corpus)
446
+ throw new Error("Training retrieval requires a configured sessions corpus");
447
+ const refreshed = collectTraining(source, store, { existingOnly: true });
448
+ const concurrency = options.concurrency ?? TRAINING_EVALUATION_CONCURRENCY;
449
+ const reviewsBySource = new Map();
450
+ for (const review of store.reviews()) {
451
+ const list = reviewsBySource.get(review.sourceId);
452
+ if (list)
453
+ list.push(review);
454
+ else
455
+ reviewsBySource.set(review.sourceId, [review]);
456
+ }
457
+ const ctx = {
458
+ source, store, config, runtime, options, chatTypes: corpus.chatTypes,
459
+ judgeVersion: memoryJudgeVersion(config.decisionModel.model, config.decisionModel.endpoint),
460
+ evaluationOptions: { endpoint: config.decisionModel.endpoint, model: config.decisionModel.model },
461
+ result: { ...summary(), retrievals: 0, evaluated: 0, awaitingTeacher: 0 },
462
+ reviewsBySource, judgments: new Map(), revisions: new Map(), createSearch, stopped: false,
381
463
  };
382
464
  const examples = store.queryExamples(options.threshold);
383
465
  let next = 0;
384
466
  await drain(Array.from({ length: Math.min(concurrency, examples.length) }, async () => {
385
- while (!shouldStop() && (options.maxExamples === undefined || result.examples < options.maxExamples)) {
467
+ while (!shouldStop(ctx) && (options.maxExamples === undefined || ctx.result.examples < options.maxExamples)) {
386
468
  const example = examples[next++];
387
469
  if (!example)
388
470
  return;
389
471
  try {
390
- await evaluate(example);
472
+ await evaluateExample(ctx, example);
391
473
  }
392
474
  catch (error) {
393
- stopped = true;
475
+ ctx.stopped = true;
394
476
  throw error;
395
477
  }
396
478
  }
397
479
  }));
398
- return { refreshed, ...result, concurrency, threshold: options.threshold ?? TRAINING_GATE_THRESHOLD,
480
+ return { refreshed, ...ctx.result, concurrency, threshold: options.threshold ?? TRAINING_GATE_THRESHOLD,
399
481
  retrievalMethod: "independent-lex10-vec10", callUnit: "teacher completion, retrieval operation or uncached passage judgment" };
400
482
  }
401
- export function* exportQueryTraining(store, threshold = TRAINING_GATE_THRESHOLD) {
483
+ export async function currentTrainingCorpusHashes(source, store, config, threshold = TRAINING_GATE_THRESHOLD, createSearch) {
484
+ const corpus = config.corpora.find(c => c.kind === "sessions");
485
+ if (!corpus)
486
+ throw new Error("Training retrieval requires a configured sessions corpus");
487
+ const examples = store.queryExamples(threshold);
488
+ const hashes = new Map();
489
+ if (!examples.length)
490
+ return hashes;
491
+ const sourceForCutoff = createSearch ? undefined : await historicalTrainingSource(source.stateDir, corpus.chatTypes);
492
+ for (const example of examples) {
493
+ store.renew();
494
+ const snapshot = createSearch
495
+ ? await createSearch(source.stateDir, corpus.chatTypes, example.timestamp)
496
+ : await sourceForCutoff(example.timestamp);
497
+ try {
498
+ const proven = snapshot.proven ?? (snapshot.report.sessions === 0 || snapshot.report.chunks > 0);
499
+ if (proven)
500
+ hashes.set(example.id, snapshot.corpusHash);
501
+ }
502
+ finally {
503
+ await snapshot.close();
504
+ }
505
+ }
506
+ return hashes;
507
+ }
508
+ function hasMatchingRetrievalProof(store, source, evaluation, expectedCorpusHash) {
509
+ if (!evaluation.corpusHash)
510
+ return false;
511
+ if (expectedCorpusHash !== undefined && evaluation.corpusHash !== expectedCorpusHash)
512
+ return false;
513
+ if (!evaluation.queries.length)
514
+ return false;
515
+ for (const query of evaluation.queries) {
516
+ const info = store.stepScope(query.retrievalId);
517
+ if (!info || info.stage !== "retrieve" || info.status !== "complete")
518
+ return false;
519
+ if (info.request.sourceId !== source.id || info.request.corpusHash !== evaluation.corpusHash)
520
+ return false;
521
+ if (info.request.lane !== query.lane || info.request.query !== query.query)
522
+ return false;
523
+ }
524
+ return true;
525
+ }
526
+ export function* exportQueryTraining(store, threshold = TRAINING_GATE_THRESHOLD, judgeVersion = CONTEXT_JUDGE_VERSION, options) {
402
527
  const active = new Map(store.queryExamples(threshold).map(e => [e.id, e]));
403
- const unresolved = new Set(store.reviews().map(review => review.sourceId)), exported = new Set();
404
- for (const evaluation of store.completedEvaluations({ selection: SELECTION_VERSION, retrieval: TRAINING_RETRIEVAL_VERSION, judge: CONTEXT_JUDGE_VERSION })) {
528
+ const unresolved = new Set(store.reviews().filter(review => reviewBlocksJudge(store, review, judgeVersion)).map(review => review.sourceId));
529
+ const exported = new Set();
530
+ for (const evaluation of store.completedEvaluations({ selection: SELECTION_VERSION, retrieval: TRAINING_RETRIEVAL_VERSION, judge: judgeVersion })) {
405
531
  const source = active.get(evaluation.sourceId);
406
532
  if (!source || source.inputHash !== evaluation.inputHash || source.timestamp !== evaluation.timestamp || exported.has(source.id))
407
533
  continue;
534
+ if (unresolved.has(source.id)) {
535
+ exported.add(source.id);
536
+ continue;
537
+ }
538
+ let expectedCorpusHash;
539
+ if (options?.corpusHashes !== undefined) {
540
+ expectedCorpusHash = options.corpusHashes.get(source.id);
541
+ if (!expectedCorpusHash) {
542
+ exported.add(source.id);
543
+ continue;
544
+ }
545
+ if (evaluation.corpusHash !== expectedCorpusHash)
546
+ continue;
547
+ }
408
548
  exported.add(source.id); // Never fall back to an older accepted corpus after a newer flagged result.
409
- if (unresolved.has(source.id))
549
+ if (!hasMatchingRetrievalProof(store, source, evaluation, expectedCorpusHash))
410
550
  continue;
411
551
  if (!LANES.every(lane => evaluation.teacherIds.includes(store.step("generate", teacherRequest(source, lane)).id)))
412
552
  continue;
@@ -415,7 +555,9 @@ export function* exportQueryTraining(store, threshold = TRAINING_GATE_THRESHOLD)
415
555
  const selected = selectTrainingQueries(evaluation.queries);
416
556
  const provenance = [...evaluation.teacherIds, ...evaluation.queries.flatMap(q => [q.retrievalId, ...q.judgments])];
417
557
  yield { stage: "query-training", input: JSON.parse(source.inputJson), inputHash: source.inputHash,
418
- recallProbability: source.recallProbability, threshold, target: selected, targetPolicy: TARGET_POLICY,
558
+ recallProbability: source.recallProbability, ...(source.recallModel ? { recallModel: source.recallModel } : {}),
559
+ recallRequestedModel: store.requestedModel,
560
+ threshold, target: selected, targetPolicy: TARGET_POLICY,
419
561
  source: store.sourceDetails(source.id), evaluation: { ...evaluation, selected, review: [] }, splitGroup: jsonHash(source.sessionId),
420
562
  provenance: [...new Set(provenance)].map(id => store.stepRecord(id)) };
421
563
  }