@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
@@ -67,7 +67,7 @@ type ReviewDetails = {
67
67
  };
68
68
  export declare class TrainingStore {
69
69
  #private;
70
- constructor(path: string, agentId: string);
70
+ constructor(path: string, agentId: string, requestedModel?: string);
71
71
  locked<T>(fn: () => T | Promise<T>): Promise<T>;
72
72
  renew(): void;
73
73
  sessions(): string[];
@@ -87,6 +87,7 @@ export declare class TrainingStore {
87
87
  retry(includeAmbiguous: boolean, ids: readonly string[]): number;
88
88
  queryExamples(threshold?: number): (TrainingSourceExample & {
89
89
  recallProbability: number;
90
+ recallModel: string | null;
90
91
  })[];
91
92
  step<S extends keyof TrainingStepResults>(stage: S, parameters: Record<string, unknown>): {
92
93
  id: string;
@@ -97,10 +98,12 @@ export declare class TrainingStore {
97
98
  status: StepStatus;
98
99
  result: TrainingStepResults[S] | undefined;
99
100
  };
100
- flagReview(example: TrainingSourceExample, reason: string, details: ReviewDetails): void;
101
- clearReview(sourceId: string): void;
101
+ get requestedModel(): string;
102
+ flagReview(example: TrainingSourceExample, reason: string, details: ReviewDetails, scope?: string): void;
103
+ clearReview(sourceId: string, scope?: string, matchesLegacyUnresolved?: (details: ReviewDetails) => boolean): void;
102
104
  reviews(): {
103
105
  sourceId: string;
106
+ scope: string;
104
107
  inputHash: string;
105
108
  reason: string;
106
109
  details: ReviewDetails;
@@ -113,6 +116,11 @@ export declare class TrainingStore {
113
116
  status: "failed" | "ambiguous";
114
117
  error: string;
115
118
  }): void;
119
+ saveStep<S extends "score" | "evaluate">(stage: S, id: string, request: unknown, result: TrainingStepResults[S], clearReview?: {
120
+ sourceId: string;
121
+ scope?: string;
122
+ matchesLegacyUnresolved?: (details: ReviewDetails) => boolean;
123
+ }): void;
116
124
  completedEvaluations(versions?: {
117
125
  selection: string;
118
126
  retrieval: string;
@@ -131,6 +139,11 @@ export declare class TrainingStore {
131
139
  completedAt: import("node:sqlite").SQLOutputValue;
132
140
  };
133
141
  stepRecordStatus(id: string): StepStatus | undefined;
142
+ stepScope(id: string): {
143
+ stage: string;
144
+ status: StepStatus;
145
+ request: Record<string, unknown>;
146
+ } | undefined;
134
147
  status(threshold: number): {
135
148
  nodeId: string;
136
149
  agentId: string;
@@ -150,6 +163,7 @@ export declare class TrainingStore {
150
163
  recipe: string;
151
164
  reviews: {
152
165
  sourceId: string;
166
+ scope: string;
153
167
  inputHash: string;
154
168
  reason: string;
155
169
  details: ReviewDetails;
@@ -169,6 +183,7 @@ export declare class TrainingStore {
169
183
  recallNeeded: boolean;
170
184
  threshold: number;
171
185
  model: import("node:sqlite").SQLOutputValue;
186
+ requestedModel: string;
172
187
  promptVersion: import("node:sqlite").SQLOutputValue;
173
188
  usage: {
174
189
  input_tokens: import("node:sqlite").SQLOutputValue;
@@ -1,21 +1,24 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
3
4
  import { TRAINING_PREPARATION } from "./training-input.js";
4
5
  import { TRAINING_GATE_MODEL, TRAINING_GATE_THRESHOLD, TRAINING_GATE_VERSION } from "./training-gate.js";
5
6
  import { TRAINING_RECIPE_VERSION } from "./training-models.js";
6
7
  import { jsonHash } from "./json-hash.js";
7
- const LEASE_MS = 120_000;
8
+ const LEASE_MS = DEFAULTS.training.leaseMs;
8
9
  export class TrainingStore {
9
10
  #db;
10
11
  #owner = randomUUID();
11
12
  #nodeId;
12
13
  #agentId;
13
- constructor(path, agentId) {
14
+ #requestedModel;
15
+ constructor(path, agentId, requestedModel = TRAINING_GATE_MODEL) {
14
16
  this.#db = openMemoryDatabase(path);
15
17
  this.#agentId = agentId;
18
+ this.#requestedModel = requestedModel;
16
19
  try {
17
20
  const version = this.#db.prepare("SELECT version FROM memory_schema WHERE component='training'").get()?.version;
18
- if (version !== undefined && version !== 1)
21
+ if (version !== undefined && version !== 1 && version !== 2)
19
22
  throw new Error("Unsupported training database version");
20
23
  this.#db.exec(`
21
24
  CREATE TABLE IF NOT EXISTS training_identity (singleton INTEGER PRIMARY KEY CHECK(singleton=1), node_id TEXT NOT NULL, agent_id TEXT NOT NULL) STRICT;
@@ -46,15 +49,34 @@ export class TrainingStore {
46
49
  result_json TEXT, error TEXT, completed_at INTEGER
47
50
  ) STRICT;
48
51
  CREATE TABLE IF NOT EXISTS training_reviews (
49
- source_id TEXT PRIMARY KEY REFERENCES training_examples(id), input_hash TEXT NOT NULL,
50
- recipe TEXT NOT NULL, reason TEXT NOT NULL, details_json TEXT NOT NULL, updated_at INTEGER NOT NULL
52
+ source_id TEXT NOT NULL REFERENCES training_examples(id), scope TEXT NOT NULL DEFAULT '',
53
+ input_hash TEXT NOT NULL, recipe TEXT NOT NULL, reason TEXT NOT NULL,
54
+ details_json TEXT NOT NULL, updated_at INTEGER NOT NULL,
55
+ PRIMARY KEY(source_id,scope)
51
56
  ) STRICT;
52
57
  CREATE TABLE IF NOT EXISTS training_step_attempts (
53
58
  id INTEGER PRIMARY KEY, step_id TEXT NOT NULL REFERENCES training_steps(id), started_at INTEGER NOT NULL,
54
59
  finished_at INTEGER, status TEXT NOT NULL, error TEXT, result_json TEXT
55
60
  ) STRICT;
56
- INSERT OR IGNORE INTO memory_schema VALUES ('training',1);
57
61
  `);
62
+ if (!this.#db.prepare("SELECT 1 FROM pragma_table_info('training_reviews') WHERE name='scope'").get()) {
63
+ immediateTransaction(this.#db, () => {
64
+ this.#db.exec(`
65
+ CREATE TABLE training_reviews_v2 (
66
+ source_id TEXT NOT NULL REFERENCES training_examples(id), scope TEXT NOT NULL DEFAULT '',
67
+ input_hash TEXT NOT NULL, recipe TEXT NOT NULL, reason TEXT NOT NULL,
68
+ details_json TEXT NOT NULL, updated_at INTEGER NOT NULL,
69
+ PRIMARY KEY(source_id,scope)
70
+ ) STRICT;
71
+ INSERT INTO training_reviews_v2 (source_id,scope,input_hash,recipe,reason,details_json,updated_at)
72
+ SELECT source_id,CASE WHEN reason='evaluation-unresolved' THEN '__legacy__' ELSE '' END,
73
+ input_hash,recipe,reason,details_json,updated_at FROM training_reviews;
74
+ DROP TABLE training_reviews;
75
+ ALTER TABLE training_reviews_v2 RENAME TO training_reviews;
76
+ `);
77
+ });
78
+ }
79
+ this.#db.exec("INSERT OR REPLACE INTO memory_schema VALUES ('training',2);");
58
80
  this.#db.prepare("INSERT OR IGNORE INTO training_identity VALUES (1,?,?)").run(randomUUID(), agentId);
59
81
  const identity = this.#db.prepare("SELECT node_id,agent_id FROM training_identity WHERE singleton=1").get();
60
82
  if (identity.agent_id !== agentId)
@@ -81,11 +103,11 @@ export class TrainingStore {
81
103
  // A request may have been billed before a crashed process saved the response.
82
104
  this.#db.prepare(`UPDATE training_gates SET status='ambiguous',error='interrupted' WHERE status='attempted'
83
105
  AND prompt_version=? AND requested_model=? AND input_hash IN (SELECT hash FROM training_inputs WHERE preparation=?)`)
84
- .run(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION);
106
+ .run(TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION);
85
107
  this.#db.prepare(`UPDATE training_attempts SET status='ambiguous',error='interrupted' WHERE status='attempted'
86
108
  AND gate_id IN (SELECT g.id FROM training_gates g JOIN training_inputs i ON i.hash=g.input_hash
87
109
  WHERE g.prompt_version=? AND g.requested_model=? AND i.preparation=?)`)
88
- .run(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION);
110
+ .run(TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION);
89
111
  this.#db.prepare(`UPDATE training_steps SET status='ambiguous',error='interrupted' WHERE status='attempted'
90
112
  AND json_extract(request_json,'$.recipe')=?`).run(TRAINING_RECIPE_VERSION);
91
113
  this.#db.prepare(`UPDATE training_step_attempts SET status='ambiguous',error='interrupted' WHERE status='attempted'
@@ -97,7 +119,7 @@ export class TrainingStore {
97
119
  }
98
120
  catch (error) {
99
121
  leaseError = error;
100
- } }, 10_000);
122
+ } }, DEFAULTS.training.heartbeatMs);
101
123
  heartbeat.unref();
102
124
  try {
103
125
  const value = await fn();
@@ -138,8 +160,8 @@ export class TrainingStore {
138
160
  retained.add(example.seq);
139
161
  input.run(example.inputHash, TRAINING_PREPARATION, JSON.stringify(example.input));
140
162
  source.run(jsonHash([this.#nodeId, this.#agentId, sessionId, example.seq]), sessionId, example.seq, example.timestamp, example.inputHash, Number(example.contextLimited));
141
- const id = jsonHash([example.inputHash, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL]);
142
- gate.run(id, example.inputHash, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL);
163
+ const id = jsonHash([example.inputHash, TRAINING_GATE_VERSION, this.#requestedModel]);
164
+ gate.run(id, example.inputHash, TRAINING_GATE_VERSION, this.#requestedModel);
143
165
  if (!old)
144
166
  counts.added++;
145
167
  else if (old.input_hash !== example.inputHash || old.active !== 1)
@@ -152,8 +174,10 @@ export class TrainingStore {
152
174
  });
153
175
  }
154
176
  unavailable(sessionId) {
155
- this.#checkLease();
156
- this.#db.prepare("UPDATE training_examples SET active=-1 WHERE session_id=? AND active=1").run(sessionId);
177
+ immediateTransaction(this.#db, () => {
178
+ this.#checkLease();
179
+ this.#db.prepare("UPDATE training_examples SET active=-1 WHERE session_id=? AND active=1").run(sessionId);
180
+ });
157
181
  }
158
182
  #scope = `g.prompt_version=? AND g.requested_model=? AND EXISTS
159
183
  (SELECT 1 FROM training_examples e JOIN training_inputs i ON i.hash=e.input_hash
@@ -163,7 +187,7 @@ export class TrainingStore {
163
187
  FROM training_gates g JOIN training_inputs i ON i.hash=g.input_hash
164
188
  WHERE ${this.#scope} AND g.status='pending' ORDER BY
165
189
  (SELECT MAX(timestamp) FROM training_examples WHERE input_hash=g.input_hash AND active=1) DESC,g.id LIMIT ?`)
166
- .all(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION, limit ?? -1);
190
+ .all(TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION, limit ?? -1);
167
191
  }
168
192
  start(id) {
169
193
  return immediateTransaction(this.#db, () => {
@@ -180,36 +204,44 @@ export class TrainingStore {
180
204
  this.#checkLease();
181
205
  const ok = "probability" in result;
182
206
  const status = ok ? "complete" : result.status, error = ok ? null : result.error;
183
- this.#db.prepare(`UPDATE training_gates SET status=?,probability=?,actual_model=?,input_tokens=?,output_tokens=?,error=?,completed_at=? WHERE id=?`)
184
- .run(status, ok ? result.probability : null, ok ? result.model : null, ok ? result.usage.input_tokens : null, ok ? result.usage.output_tokens : null, error, Date.now(), id);
185
- this.#db.prepare("UPDATE training_attempts SET status=?,finished_at=?,error=?,result_json=? WHERE id=? AND gate_id=?")
186
- .run(status, Date.now(), error, ok ? JSON.stringify(result) : null, attempt, id);
207
+ const now = Date.now();
208
+ if (!this.#db.prepare(`UPDATE training_gates SET status=?,probability=?,actual_model=?,input_tokens=?,output_tokens=?,error=?,completed_at=? WHERE id=? AND status='attempted'`)
209
+ .run(status, ok ? result.probability : null, ok ? result.model : null, ok ? result.usage.input_tokens : null, ok ? result.usage.output_tokens : null, error, now, id).changes) {
210
+ throw new Error("Training gate attempt lost");
211
+ }
212
+ if (!this.#db.prepare("UPDATE training_attempts SET status=?,finished_at=?,error=?,result_json=? WHERE id=? AND gate_id=? AND status='attempted'")
213
+ .run(status, now, error, ok ? JSON.stringify(result) : null, attempt, id).changes) {
214
+ throw new Error("Training attempt lost");
215
+ }
187
216
  });
188
217
  }
189
218
  retry(includeAmbiguous, ids) {
190
219
  if (!ids.length || ids.some(id => !/^[a-f0-9]{64}$/u.test(id)))
191
220
  throw new Error("Specify exact training gate or step hashes to retry");
192
- this.#checkLease();
193
- return immediateTransaction(this.#db, () => ids.reduce((count, id) => {
221
+ return immediateTransaction(this.#db, () => {
222
+ this.#checkLease();
194
223
  const statuses = includeAmbiguous ? "('failed','ambiguous')" : "('failed')";
195
- const gates = this.#db.prepare(`UPDATE training_gates SET status='pending',error=NULL WHERE id=?
224
+ const resetGate = this.#db.prepare(`UPDATE training_gates SET status='pending',error=NULL,completed_at=NULL WHERE id=?
196
225
  AND prompt_version=? AND requested_model=? AND status IN ${statuses}
197
- AND input_hash IN (SELECT hash FROM training_inputs WHERE preparation=?)`)
198
- .run(id, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION);
199
- const steps = this.#db.prepare(`UPDATE training_steps SET status='pending',error=NULL WHERE id=?
200
- AND json_extract(request_json,'$.recipe')=? AND status IN ${statuses}`).run(id, TRAINING_RECIPE_VERSION);
201
- return count + Number(gates.changes) + Number(steps.changes);
202
- }, 0));
226
+ AND input_hash IN (SELECT hash FROM training_inputs WHERE preparation=?)`);
227
+ const resetStep = this.#db.prepare(`UPDATE training_steps SET status='pending',error=NULL,completed_at=NULL WHERE id=?
228
+ AND json_extract(request_json,'$.recipe')=? AND status IN ${statuses}`);
229
+ return ids.reduce((count, id) => {
230
+ const gates = resetGate.run(id, TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION);
231
+ const steps = resetStep.run(id, TRAINING_RECIPE_VERSION);
232
+ return count + Number(gates.changes) + Number(steps.changes);
233
+ }, 0);
234
+ });
203
235
  }
204
236
  queryExamples(threshold = TRAINING_GATE_THRESHOLD) {
205
237
  if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1)
206
238
  throw new Error("Threshold must be between 0 and 1");
207
239
  return this.#db.prepare(`SELECT e.id,e.input_hash inputHash,i.input_json inputJson,e.session_id sessionId,e.timestamp,
208
- g.probability recallProbability FROM training_examples e JOIN training_inputs i ON i.hash=e.input_hash
240
+ g.probability recallProbability,g.actual_model recallModel FROM training_examples e JOIN training_inputs i ON i.hash=e.input_hash
209
241
  JOIN training_gates g ON g.input_hash=e.input_hash
210
242
  WHERE e.active=1 AND i.preparation=? AND g.prompt_version=? AND g.requested_model=?
211
243
  AND g.status='complete' AND g.probability>=? ORDER BY e.timestamp DESC,e.id`)
212
- .all(TRAINING_PREPARATION, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, threshold);
244
+ .all(TRAINING_PREPARATION, TRAINING_GATE_VERSION, this.#requestedModel, threshold);
213
245
  }
214
246
  step(stage, parameters) {
215
247
  const request = { ...parameters, recipe: TRAINING_RECIPE_VERSION };
@@ -218,24 +250,49 @@ export class TrainingStore {
218
250
  return { id, stage, request, status: (row?.status ?? "pending"),
219
251
  result: row?.status === "complete" ? JSON.parse(String(row.result_json)) : undefined };
220
252
  }
221
- flagReview(example, reason, details) {
222
- this.#checkLease();
223
- this.#db.prepare(`INSERT INTO training_reviews VALUES (?,?,?,?,?,?) ON CONFLICT(source_id) DO UPDATE SET
224
- input_hash=excluded.input_hash,recipe=excluded.recipe,reason=excluded.reason,
225
- details_json=excluded.details_json,updated_at=excluded.updated_at`)
226
- .run(example.id, example.inputHash, TRAINING_RECIPE_VERSION, reason, JSON.stringify(details), Date.now());
253
+ get requestedModel() { return this.#requestedModel; }
254
+ flagReview(example, reason, details, scope = "") {
255
+ immediateTransaction(this.#db, () => {
256
+ this.#checkLease();
257
+ this.#db.prepare(`INSERT INTO training_reviews (source_id,scope,input_hash,recipe,reason,details_json,updated_at)
258
+ VALUES (?,?,?,?,?,?,?) ON CONFLICT(source_id,scope) DO UPDATE SET
259
+ input_hash=excluded.input_hash,recipe=excluded.recipe,reason=excluded.reason,
260
+ details_json=excluded.details_json,updated_at=excluded.updated_at`)
261
+ .run(example.id, scope, example.inputHash, TRAINING_RECIPE_VERSION, reason, JSON.stringify(details), Date.now());
262
+ });
227
263
  }
228
- clearReview(sourceId) {
229
- this.#checkLease();
230
- this.#db.prepare("DELETE FROM training_reviews WHERE source_id=? AND recipe=?").run(sourceId, TRAINING_RECIPE_VERSION);
264
+ #clearReviewLocked(sourceId, scope, matchesLegacyUnresolved) {
265
+ if (scope === undefined) {
266
+ this.#db.prepare("DELETE FROM training_reviews WHERE source_id=? AND recipe=?").run(sourceId, TRAINING_RECIPE_VERSION);
267
+ return;
268
+ }
269
+ this.#db.prepare(`DELETE FROM training_reviews WHERE source_id=? AND recipe=?
270
+ AND (scope=? OR (scope='' AND reason!='evaluation-unresolved'))`)
271
+ .run(sourceId, TRAINING_RECIPE_VERSION, scope);
272
+ if (!matchesLegacyUnresolved)
273
+ return;
274
+ const legacyRows = this.#db.prepare(`SELECT scope,details_json details FROM training_reviews
275
+ WHERE source_id=? AND recipe=? AND scope IN ('','__legacy__') AND reason='evaluation-unresolved'`).all(sourceId, TRAINING_RECIPE_VERSION);
276
+ for (const legacy of legacyRows) {
277
+ if (matchesLegacyUnresolved(JSON.parse(String(legacy.details)))) {
278
+ this.#db.prepare(`DELETE FROM training_reviews WHERE source_id=? AND recipe=? AND scope=? AND reason='evaluation-unresolved'`)
279
+ .run(sourceId, TRAINING_RECIPE_VERSION, String(legacy.scope));
280
+ }
281
+ }
282
+ }
283
+ clearReview(sourceId, scope, matchesLegacyUnresolved) {
284
+ immediateTransaction(this.#db, () => {
285
+ this.#checkLease();
286
+ this.#clearReviewLocked(sourceId, scope, matchesLegacyUnresolved);
287
+ });
231
288
  }
232
289
  reviews() {
233
290
  // Old usefulness-only flags remain in SQLite for audit, but no longer block training.
234
- return this.#db.prepare(`SELECT r.source_id sourceId,r.input_hash inputHash,r.reason,r.details_json details,r.updated_at updatedAt
291
+ return this.#db.prepare(`SELECT r.source_id sourceId,r.scope,r.input_hash inputHash,r.reason,r.details_json details,r.updated_at updatedAt
235
292
  FROM training_reviews r JOIN training_examples e ON e.id=r.source_id
236
293
  WHERE r.recipe=? AND e.active=1 AND e.input_hash=r.input_hash AND r.reason!='no-useful-evidence'
237
- ORDER BY r.updated_at DESC,r.source_id`)
238
- .all(TRAINING_RECIPE_VERSION).map(row => ({ sourceId: String(row.sourceId), inputHash: String(row.inputHash),
294
+ ORDER BY r.updated_at DESC,r.source_id,r.scope`)
295
+ .all(TRAINING_RECIPE_VERSION).map(row => ({ sourceId: String(row.sourceId), scope: String(row.scope), inputHash: String(row.inputHash),
239
296
  reason: String(row.reason), details: JSON.parse(String(row.details)), updatedAt: Number(row.updatedAt) }));
240
297
  }
241
298
  startStep(stage, id, request) {
@@ -255,14 +312,33 @@ export class TrainingStore {
255
312
  this.#checkLease();
256
313
  const ok = "result" in outcome, status = ok ? "complete" : outcome.status;
257
314
  const json = ok ? JSON.stringify(outcome.result) : null, error = ok ? null : outcome.error;
315
+ const now = Date.now();
258
316
  if (!this.#db.prepare(`UPDATE training_steps SET status=?,result_json=?,error=?,completed_at=? WHERE id=? AND stage=? AND status='attempted'`)
259
- .run(status, json, error, Date.now(), id, stage).changes)
317
+ .run(status, json, error, now, id, stage).changes)
260
318
  throw new Error("Training step attempt lost");
261
319
  if (!this.#db.prepare(`UPDATE training_step_attempts SET status=?,finished_at=?,error=?,result_json=? WHERE id=? AND step_id=? AND status='attempted'`)
262
- .run(status, Date.now(), error, json, attempt, id).changes)
320
+ .run(status, now, error, json, attempt, id).changes)
263
321
  throw new Error("Training attempt lost");
264
322
  });
265
323
  }
324
+ saveStep(stage, id, request, result, clearReview) {
325
+ immediateTransaction(this.#db, () => {
326
+ this.#checkLease();
327
+ const now = Date.now();
328
+ const json = JSON.stringify(result);
329
+ this.#db.prepare("INSERT OR IGNORE INTO training_steps (id,stage,request_json,status) VALUES (?,?,?,'pending')")
330
+ .run(id, stage, JSON.stringify(request));
331
+ if (!this.#db.prepare("UPDATE training_steps SET status='complete',result_json=?,error=NULL,completed_at=? WHERE id=? AND stage=? AND status='pending'")
332
+ .run(json, now, id, stage).changes) {
333
+ throw new Error("Training step is not pending");
334
+ }
335
+ this.#db.prepare("INSERT INTO training_step_attempts (step_id,started_at,finished_at,status,error,result_json) VALUES (?,?,?,'complete',NULL,?)")
336
+ .run(id, now, now, json);
337
+ if (clearReview) {
338
+ this.#clearReviewLocked(clearReview.sourceId, clearReview.scope, clearReview.matchesLegacyUnresolved);
339
+ }
340
+ });
341
+ }
266
342
  completedEvaluations(versions) {
267
343
  return this.#db.prepare(`SELECT result_json FROM training_steps WHERE stage='evaluate' AND status='complete'
268
344
  AND json_extract(request_json,'$.recipe')=?
@@ -289,14 +365,25 @@ export class TrainingStore {
289
365
  return this.#db.prepare("SELECT status FROM training_steps WHERE id=? AND json_extract(request_json,'$.recipe')=?")
290
366
  .get(id, TRAINING_RECIPE_VERSION)?.status;
291
367
  }
368
+ stepScope(id) {
369
+ const row = this.#db.prepare("SELECT stage,status,request_json FROM training_steps WHERE id=? AND json_extract(request_json,'$.recipe')=?")
370
+ .get(id, TRAINING_RECIPE_VERSION);
371
+ if (!row)
372
+ return undefined;
373
+ return {
374
+ stage: String(row.stage),
375
+ status: String(row.status),
376
+ request: JSON.parse(String(row.request_json)),
377
+ };
378
+ }
292
379
  status(threshold) {
293
380
  const stages = this.#db.prepare(`SELECT g.status,COUNT(*) count FROM training_gates g WHERE ${this.#scope} GROUP BY g.status`)
294
- .all(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION);
381
+ .all(TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION);
295
382
  const labels = this.#db.prepare(`SELECT COUNT(*) complete,COALESCE(SUM(g.probability>=?),0) positive,
296
383
  COALESCE(SUM(g.input_tokens),0) inputTokens,COALESCE(SUM(g.output_tokens),0) outputTokens
297
- FROM training_gates g WHERE ${this.#scope} AND g.status='complete'`).get(threshold, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION);
384
+ FROM training_gates g WHERE ${this.#scope} AND g.status='complete'`).get(threshold, TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION);
298
385
  return { nodeId: this.#nodeId, agentId: this.#agentId, preparation: TRAINING_PREPARATION,
299
- promptVersion: TRAINING_GATE_VERSION, requestedModel: TRAINING_GATE_MODEL, threshold,
386
+ promptVersion: TRAINING_GATE_VERSION, requestedModel: this.#requestedModel, threshold,
300
387
  examples: this.#db.prepare(`SELECT e.active,COUNT(*) count FROM training_examples e
301
388
  JOIN training_inputs i ON i.hash=e.input_hash WHERE i.preparation=? GROUP BY e.active`).all(TRAINING_PREPARATION),
302
389
  collectedInputs: Number(this.#db.prepare(`SELECT COUNT(DISTINCT e.input_hash) count FROM training_examples e
@@ -310,7 +397,7 @@ export class TrainingStore {
310
397
  WHERE json_extract(request_json,'$.recipe')=? AND status IN ('failed','ambiguous')
311
398
  UNION ALL SELECT g.id,'recall',g.status,g.error FROM training_gates g WHERE ${this.#scope}
312
399
  AND g.status IN ('failed','ambiguous') ORDER BY stage,id`)
313
- .all(TRAINING_RECIPE_VERSION, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION),
400
+ .all(TRAINING_RECIPE_VERSION, TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION),
314
401
  queryStages: this.#db.prepare(`SELECT stage,status,COUNT(*) count FROM training_steps
315
402
  WHERE json_extract(request_json,'$.recipe')=? GROUP BY stage,status ORDER BY stage,status`).all(TRAINING_RECIPE_VERSION),
316
403
  queryAttempts: this.#db.prepare(`SELECT s.stage,a.status,COUNT(*) count,
@@ -323,18 +410,20 @@ export class TrainingStore {
323
410
  COALESCE(SUM(json_extract(a.result_json,'$.usage.input_tokens')),0) inputTokens,
324
411
  COALESCE(SUM(json_extract(a.result_json,'$.usage.output_tokens')),0) outputTokens
325
412
  FROM training_attempts a JOIN training_gates g ON g.id=a.gate_id WHERE ${this.#scope} GROUP BY a.status`)
326
- .all(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION) };
413
+ .all(TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION) };
327
414
  }
328
415
  *exportRows(threshold) {
416
+ const sourcesQuery = this.#db.prepare(`SELECT id,session_id sessionId,event_seq userEventId,timestamp,context_limited contextLimited
417
+ FROM training_examples WHERE input_hash=? AND active=1 ORDER BY session_id,event_seq`);
329
418
  const rows = this.#db.prepare(`SELECT g.*,i.input_json FROM training_gates g JOIN training_inputs i ON i.hash=g.input_hash
330
- WHERE ${this.#scope} AND g.status='complete' ORDER BY g.id`).iterate(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION);
419
+ WHERE ${this.#scope} AND g.status='complete' ORDER BY g.id`).iterate(TRAINING_GATE_VERSION, this.#requestedModel, TRAINING_PREPARATION);
331
420
  for (const row of rows) {
332
421
  yield { stage: "recall-gate", inputHash: row.input_hash, preparation: TRAINING_PREPARATION,
333
422
  input: JSON.parse(String(row.input_json)), recallProbability: row.probability,
334
- recallNeeded: Number(row.probability) >= threshold, threshold, model: row.actual_model, promptVersion: row.prompt_version,
423
+ recallNeeded: Number(row.probability) >= threshold, threshold, model: row.actual_model,
424
+ requestedModel: this.#requestedModel, promptVersion: row.prompt_version,
335
425
  usage: { input_tokens: row.input_tokens, output_tokens: row.output_tokens },
336
- sources: this.#db.prepare(`SELECT id,session_id sessionId,event_seq userEventId,timestamp,context_limited contextLimited
337
- FROM training_examples WHERE input_hash=? AND active=1 ORDER BY session_id,event_seq`).all(String(row.input_hash))
426
+ sources: sourcesQuery.all(String(row.input_hash))
338
427
  .map(source => ({ nodeId: this.#nodeId, agentId: this.#agentId, ...source })) };
339
428
  }
340
429
  }
@@ -1,4 +1,5 @@
1
- import { TypeSafeRequestError, resolveTypeSafeApiKey } from "./typesafe-client.js";
1
+ import { DEFAULTS } from "./defaults.js";
2
+ import { classifyDecisionFailure, resolveDecisionCredential } from "./decision-client.js";
2
3
  import { TrainingTranscriptReader } from "./training-input.js";
3
4
  import { judgeTrainingInput, TRAINING_GATE_QUESTIONS } from "./training-gate.js";
4
5
  /** A full active-branch rescan is cheap/local; only changed exact inputs need inference. */
@@ -49,16 +50,16 @@ export async function runTraining(source, store, config, options) {
49
50
  !Number.isSafeInteger(options.maxInputBytes) || options.maxInputBytes < 1)
50
51
  throw new Error("Invalid training run bounds");
51
52
  const refreshed = collectTraining(source, store, { existingOnly: true });
52
- const concurrency = options.concurrency ?? 256;
53
+ const concurrency = options.concurrency ?? 32;
53
54
  if (!Number.isSafeInteger(concurrency) || concurrency < 1)
54
55
  throw new Error("Invalid training concurrency");
55
56
  const jobs = store.pending(options.maxExamples);
56
57
  const result = { refreshed, pendingSelected: jobs.length, calls: 0, completed: 0, failed: 0, ambiguous: 0,
57
58
  inputBytes: 0, inputTokens: 0, outputTokens: 0, budgetLimited: false };
58
59
  // Resolve only when there is work. Reruns with no pending inputs need no credentials.
59
- const key = jobs.length && !options.dryRun ? await resolveTypeSafeApiKey(config.typesafe) : undefined;
60
+ const key = jobs.length && !options.dryRun ? await resolveDecisionCredential(config.decisionModel) : undefined;
60
61
  if (jobs.length && !options.dryRun && !key)
61
- throw new Error("TypeSafe is disabled or its credential is unavailable");
62
+ throw new Error("Decision model is disabled or its credential is unavailable");
62
63
  let next = 0, stopped = false;
63
64
  const workers = await Promise.allSettled(Array.from({ length: Math.min(concurrency, jobs.length) }, async () => {
64
65
  while (!stopped && !result.budgetLimited) {
@@ -81,15 +82,12 @@ export async function runTraining(source, store, config, options) {
81
82
  let judgment;
82
83
  try {
83
84
  // Offline labeling has its own deadline, not Whisperer's latency-sensitive timeout.
84
- judgment = await judgeTrainingInput(input, key, AbortSignal.timeout(30_000));
85
+ judgment = await judgeTrainingInput(input, key, AbortSignal.timeout(DEFAULTS.training.decisionTimeoutMs), { endpoint: config.decisionModel.endpoint, model: config.decisionModel.model });
85
86
  }
86
87
  catch (error) {
87
- const definite = error instanceof TypeSafeRequestError && error.code === "http_error" &&
88
- error.status !== undefined && error.status >= 400 && error.status < 500;
89
- const status = definite ? "failed" : "ambiguous";
90
- store.finish(job.id, attempt, { status, error: error instanceof TypeSafeRequestError && error.code === "http_error" ?
91
- `http_${error.status}` : "request_or_response_uncertain" });
92
- result[status]++;
88
+ const classified = classifyDecisionFailure(error);
89
+ store.finish(job.id, attempt, { status: classified.status, error: classified.error });
90
+ result[classified.status]++;
93
91
  // Flag this input for operator review; do not stall untouched inputs or retry it.
94
92
  continue;
95
93
  }
@@ -1,3 +1,4 @@
1
+ export declare const MAX_SKILL_QUERY_CHARS: number;
1
2
  /** Only visible user/assistant text; never system, tool, image, or thinking blocks. */
2
3
  export declare function messageText(message: unknown): {
3
4
  role: "user" | "assistant";
@@ -8,3 +9,15 @@ export declare function recentSkillMessages(messages: readonly unknown[], limit:
8
9
  text: string;
9
10
  }[];
10
11
  export declare function buildSkillWhispererQuery(prompt: string, history: readonly NonNullable<ReturnType<typeof messageText>>[]): string;
12
+ /** Collect whole recent entries from newest to oldest within a token budget, returning oldest first. */
13
+ export declare function takeRecentWithinTokens<In, Out = In>(items: readonly In[], options: {
14
+ endIndex?: number;
15
+ maxItems?: number;
16
+ maxTokens: number;
17
+ usedTokens: number;
18
+ estimateTokens: (item: Out) => number;
19
+ transform?: (item: In) => Out | undefined;
20
+ }): {
21
+ items: Out[];
22
+ usedTokens: number;
23
+ };
@@ -1,4 +1,6 @@
1
- const MAX_SKILL_QUERY_CHARS = 12_000;
1
+ import { DEFAULTS } from "./defaults.js";
2
+ export const MAX_SKILL_QUERY_CHARS = DEFAULTS.skillWhisperer.contextMaxChars;
3
+ // Leaves room for the longest decision question under a 32k state-plus-question limit.
2
4
  /** Only visible user/assistant text; never system, tool, image, or thinking blocks. */
3
5
  export function messageText(message) {
4
6
  if (!message || typeof message !== "object" || !("role" in message) || !("content" in message) ||
@@ -24,3 +26,22 @@ export function buildSkillWhispererQuery(prompt, history) {
24
26
  return [...history.map(message => `${message.role}: ${message.text}`), `user: ${prompt.trim()}`]
25
27
  .join("\n\n").slice(-MAX_SKILL_QUERY_CHARS);
26
28
  }
29
+ /** Collect whole recent entries from newest to oldest within a token budget, returning oldest first. */
30
+ export function takeRecentWithinTokens(items, options) {
31
+ const { maxTokens, estimateTokens, transform } = options;
32
+ const maxItems = options.maxItems ?? Infinity;
33
+ let usedTokens = options.usedTokens;
34
+ const kept = [];
35
+ const start = Math.min(options.endIndex ?? items.length - 1, items.length - 1);
36
+ for (let i = start; i >= 0 && kept.length < maxItems; i--) {
37
+ const item = transform ? transform(items[i]) : items[i];
38
+ if (item === undefined)
39
+ continue;
40
+ const cost = estimateTokens(item) + 1;
41
+ if (usedTokens + cost > maxTokens)
42
+ break;
43
+ kept.push(item);
44
+ usedTokens += cost;
45
+ }
46
+ return { items: kept.reverse(), usedTokens };
47
+ }