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