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